import * as Chunk from "@effect/data/Chunk" import * as Context from "@effect/data/Context" import * as Duration from "@effect/data/Duration" import * as Either from "@effect/data/Either" import type { LazyArg } from "@effect/data/Function" import { constFalse, constTrue, constVoid, dual, identity, pipe } from "@effect/data/Function" import * as HashMap from "@effect/data/HashMap" import * as HashSet from "@effect/data/HashSet" import * as List from "@effect/data/List" import * as Option from "@effect/data/Option" import * as Predicate from "@effect/data/Predicate" import * as ReadonlyArray from "@effect/data/ReadonlyArray" import type * as Cause from "@effect/io/Cause" import * as Clock from "@effect/io/Clock" import type * as Effect from "@effect/io/Effect" import type * as Fiber from "@effect/io/Fiber" import * as FiberId from "@effect/io/FiberId" import type * as FiberRef from "@effect/io/FiberRef" import * as FiberRefs from "@effect/io/FiberRefs" 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 defaultServices from "@effect/io/internal/defaultServices" import * as fiberRefsPatch from "@effect/io/internal/fiberRefs/patch" import * as metricLabel from "@effect/io/internal/metric/label" import * as runtimeFlags from "@effect/io/internal/runtimeFlags" import * as SingleShotGen from "@effect/io/internal/singleShotGen" import type * as Logger from "@effect/io/Logger" import * as LogLevel from "@effect/io/LogLevel" import * as LogSpan from "@effect/io/LogSpan" import type * as Metric from "@effect/io/Metric" import type * as MetricLabel from "@effect/io/MetricLabel" import type * as Random from "@effect/io/Random" import * as Ref from "@effect/io/Ref" import type * as runtimeFlagsPatch from "@effect/io/RuntimeFlagsPatch" import * as Tracer from "@effect/io/Tracer" /* @internal */ export const annotateLogs = dual< { (key: string, value: Logger.AnnotationValue): (effect: Effect.Effect) => Effect.Effect ( values: Record ): (effect: Effect.Effect) => Effect.Effect }, { (effect: Effect.Effect, key: string, value: Logger.AnnotationValue): Effect.Effect (effect: Effect.Effect, values: Record): Effect.Effect } >( (args) => core.isEffect(args[0]), function() { const args = arguments return core.fiberRefLocallyWith( args[0] as Effect.Effect, core.currentLogAnnotations, typeof args[1] === "string" ? HashMap.set(args[1], args[2]) : (annotations) => Object.entries(args[1] as Record).reduce( (acc, [key, value]) => HashMap.set(acc, key, value), annotations ) ) } ) /* @internal */ export const asSome = (self: Effect.Effect): Effect.Effect> => core.map(self, Option.some) /* @internal */ export const asSomeError = (self: Effect.Effect): Effect.Effect, A> => core.mapError(self, Option.some) /* @internal */ export const asyncOption = ( register: (callback: (_: Effect.Effect) => void) => Option.Option>, blockingOn: FiberId.FiberId = FiberId.none ): Effect.Effect => core.asyncEither( (cb) => { const option = register(cb) switch (option._tag) { case "None": { return Either.left(core.unit) } case "Some": { return Either.right(option.value) } } }, blockingOn ) /* @internal */ export const try_: { (options: { readonly try: LazyArg; readonly catch: (error: unknown) => E }): Effect.Effect (evaluate: LazyArg): Effect.Effect } = (arg: LazyArg | { readonly try: LazyArg; readonly catch: (error: unknown) => E }) => { let evaluate: LazyArg let onFailure: ((error: unknown) => E) | undefined = undefined if (typeof arg === "function") { evaluate = arg } else { evaluate = arg.try onFailure = arg.catch } return core.sync(() => { try { return evaluate() } catch (error) { throw core.makeEffectError(internalCause.fail( onFailure ? onFailure(error) : error )) } }) } /* @internal */ export const _catch = dual< ( discriminator: N, options: { readonly failure: K readonly onFailure: (error: Extract) => Effect.Effect } ) => (self: Effect.Effect) => Effect.Effect< R | R1, Exclude | E1, A | A1 >, ( self: Effect.Effect, discriminator: N, options: { readonly failure: K readonly onFailure: (error: Extract) => Effect.Effect } ) => Effect.Effect | E1, A | A1> >( // @ts-expect-error 3, (self, tag, options) => core.catchAll(self, (e) => { if (typeof e === "object" && e != null && tag in e && e[tag] === options.failure) { return options.onFailure(e as any) } return core.fail(e as any) }) ) /* @internal */ export const catchAllDefect = dual< ( f: (defect: unknown) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (defect: unknown) => Effect.Effect ) => Effect.Effect >(2, (self, f) => core.catchAllCause( self, core.unified((cause) => { const option = internalCause.find(cause, (_) => internalCause.isDieType(_) ? Option.some(_) : Option.none()) switch (option._tag) { case "None": { return core.failCause(cause) } case "Some": { return f(option.value.defect) } } }) )) /* @internal */ export const catchSomeCause = dual< ( f: (cause: Cause.Cause) => Option.Option> ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (cause: Cause.Cause) => Option.Option> ) => Effect.Effect >( 2, ( self: Effect.Effect, f: (cause: Cause.Cause) => Option.Option> ) => core.matchCauseEffect(self, { onFailure: (cause): Effect.Effect => { const option = f(cause) switch (option._tag) { case "None": { return core.failCause(cause) } case "Some": { return option.value } } }, onSuccess: core.succeed }) ) /* @internal */ export const catchSomeDefect = dual< ( pf: (defect: unknown) => Option.Option> ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, pf: (defect: unknown) => Option.Option> ) => Effect.Effect >( 2, (self: Effect.Effect, pf: (_: unknown) => Option.Option>) => core.catchAllCause( self, core.unified((cause) => { const option = internalCause.find(cause, (_) => internalCause.isDieType(_) ? Option.some(_) : Option.none()) switch (option._tag) { case "None": { return core.failCause(cause) } case "Some": { const optionEffect = pf(option.value.defect) return optionEffect._tag === "Some" ? optionEffect.value : core.failCause(cause) } } }) ) ) /* @internal */ export const catchTag = dual< ( k: K, f: (e: Extract) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect | E1, A | A1>, ( self: Effect.Effect, k: K, f: (e: Extract) => Effect.Effect ) => Effect.Effect | E1, A | A1> >(3, (self, k, f) => core.catchIf(self, Predicate.isTagged(k), f) as any) /** @internal */ export const catchTags: { < E, Cases extends (E extends { _tag: string } ? { [K in E["_tag"]]+?: (error: Extract) => Effect.Effect } : {}) >( cases: Cases ): (self: Effect.Effect) => Effect.Effect< | R | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? R : never }[keyof Cases], | Exclude | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? E : never }[keyof Cases], | A | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? A : never }[keyof Cases] > < R, E, A, Cases extends (E extends { _tag: string } ? { [K in E["_tag"]]+?: (error: Extract) => Effect.Effect } : {}) >( self: Effect.Effect, cases: Cases ): Effect.Effect< | R | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? R : never }[keyof Cases], | Exclude | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? E : never }[keyof Cases], | A | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? A : never }[keyof Cases] > } = dual(2, (self, cases) => { let keys: Array return core.catchIf( self, (e): e is { readonly _tag: string } => { keys ??= Object.keys(cases) return Predicate.isObject(e) && "_tag" in e && keys.includes(e["_tag"] as any) }, (e) => cases[e["_tag"] as any](e as any) ) }) /* @internal */ export const cause = (self: Effect.Effect): Effect.Effect> => core.matchCause(self, { onFailure: identity, onSuccess: () => internalCause.empty }) /* @internal */ export const clockWith: (f: (clock: Clock.Clock) => Effect.Effect) => Effect.Effect = Clock.clockWith /* @internal */ export const clock: Effect.Effect = clockWith(core.succeed) /* @internal */ export const delay = dual< (duration: Duration.DurationInput) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, duration: Duration.DurationInput) => Effect.Effect >(2, (self, duration) => core.zipRight(Clock.sleep(duration), self)) /* @internal */ export const descriptorWith = ( f: (descriptor: Fiber.Fiber.Descriptor) => Effect.Effect ): Effect.Effect => core.withFiberRuntime((state, status) => f({ id: state.id(), status, interruptors: internalCause.interruptors(state.getFiberRef(core.currentInterruptedCause)) }) ) as Effect.Effect /* @internal */ export const allowInterrupt: Effect.Effect = descriptorWith( (descriptor) => HashSet.size(descriptor.interruptors) > 0 ? core.interrupt : core.unit ) /* @internal */ export const descriptor: Effect.Effect = descriptorWith(core.succeed) /* @internal */ export const diffFiberRefs = ( self: Effect.Effect ): Effect.Effect => summarized(self, fiberRefs, fiberRefsPatch.diff) /* @internal */ export const diffFiberRefsAndRuntimeFlags = ( self: Effect.Effect ) => summarized( self, core.zip(fiberRefs, core.runtimeFlags), ([refs, flags], [refsNew, flagsNew]) => [fiberRefsPatch.diff(refs, refsNew), runtimeFlags.diff(flags, flagsNew)] as const ) /* @internal */ export const Do: Effect.Effect = core.succeed({}) /* @internal */ export const bind = dual< ( tag: Exclude, f: (_: K) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect< R | R2, E | E2, Effect.MergeRecord >, ( self: Effect.Effect, tag: Exclude, f: (_: K) => Effect.Effect ) => Effect.Effect< R | R2, E | E2, Effect.MergeRecord > >(3, ( self: Effect.Effect, tag: Exclude, f: (_: K) => Effect.Effect ) => core.flatMap(self, (k) => core.map( f(k), (a): Effect.MergeRecord => ({ ...k, [tag]: a } as any) ))) /* @internal */ export const bindTo = dual< (tag: N) => (self: Effect.Effect) => Effect.Effect< R, E, Record >, ( self: Effect.Effect, tag: N ) => Effect.Effect< R, E, Record > >( 2, (self: Effect.Effect, tag: N): Effect.Effect> => core.map(self, (a) => ({ [tag]: a } as Record)) ) /* @internal */ export const bindValue = dual< ( tag: Exclude, f: (_: K) => A ) => (self: Effect.Effect) => Effect.Effect< R, E, Effect.MergeRecord >, ( self: Effect.Effect, tag: Exclude, f: (_: K) => A ) => Effect.Effect< R, E, Effect.MergeRecord > >(3, (self: Effect.Effect, tag: Exclude, f: (_: K) => A) => core.map( self, (k): Effect.MergeRecord => ({ ...k, [tag]: f(k) } as any) )) /* @internal */ export const dropUntil = dual< ( predicate: (a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect>, ( elements: Iterable, predicate: (a: A, i: number) => Effect.Effect ) => Effect.Effect> >(2, ( elements: Iterable, predicate: (a: A, i: number) => Effect.Effect ) => core.suspend(() => { const iterator = elements[Symbol.iterator]() const builder: Array = [] let next: IteratorResult let dropping: Effect.Effect = core.succeed(false) let i = 0 while ((next = iterator.next()) && !next.done) { const a = next.value const index = i++ dropping = core.flatMap(dropping, (bool) => { if (bool) { builder.push(a) return core.succeed(true) } return predicate(a, index) }) } return core.map(dropping, () => builder) })) /* @internal */ export const dropWhile = dual< ( f: (a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect>, ( elements: Iterable, f: (a: A, i: number) => Effect.Effect ) => Effect.Effect> >(2, (elements: Iterable, f: (a: A, i: number) => Effect.Effect) => core.suspend(() => { const iterator = elements[Symbol.iterator]() const builder: Array = [] let next let dropping: Effect.Effect = core.succeed(true) let i = 0 while ((next = iterator.next()) && !next.done) { const a = next.value const index = i++ dropping = core.flatMap(dropping, (d) => core.map(d ? f(a, index) : core.succeed(false), (b) => { if (!b) { builder.push(a) } return b })) } return core.map(dropping, () => builder) })) /* @internal */ export const contextWith = (f: (context: Context.Context) => A): Effect.Effect => core.map(core.context(), f) /* @internal */ export const eventually = (self: Effect.Effect): Effect.Effect => core.orElse(self, () => core.flatMap(core.yieldNow(), () => eventually(self))) /* @internal */ export const filterMap = dual< ( pf: (a: A) => Option.Option ) => (elements: Iterable>) => Effect.Effect>, ( elements: Iterable>, pf: (a: A) => Option.Option ) => Effect.Effect> >(2, (elements, pf) => core.map( core.forEachSequential(elements, identity), ReadonlyArray.filterMap(pf) )) /* @internal */ export const filterOrDie = dual< { ( filter: Predicate.Refinement, orDieWith: (a: X) => unknown ): (self: Effect.Effect) => Effect.Effect ( filter: Predicate.Predicate, orDieWith: (a: Y) => unknown ): (self: Effect.Effect) => Effect.Effect }, { ( self: Effect.Effect, filter: Predicate.Refinement, orDieWith: (a: X) => unknown ): Effect.Effect ( self: Effect.Effect, filter: Predicate.Predicate, orDieWith: (a: Y) => unknown ): Effect.Effect } >(3, ( self: Effect.Effect, filter: Predicate.Predicate, orDieWith: (a: Y) => unknown ): Effect.Effect => filterOrElse(self, filter, (a) => core.dieSync(() => orDieWith(a as Y)))) /* @internal */ export const filterOrDieMessage = dual< { ( filter: Predicate.Refinement, message: string ): (self: Effect.Effect) => Effect.Effect ( filter: Predicate.Predicate, message: string ): (self: Effect.Effect) => Effect.Effect }, { ( self: Effect.Effect, filter: Predicate.Refinement, message: string ): Effect.Effect ( self: Effect.Effect, filter: Predicate.Predicate, message: string ): Effect.Effect } >(3, ( self: Effect.Effect, filter: Predicate.Predicate, message: string ): Effect.Effect => filterOrElse(self, filter, () => core.dieMessage(message))) /* @internal */ export const filterOrElse = dual< { ( filter: Predicate.Refinement, orElse: (a: X) => Effect.Effect ): (self: Effect.Effect) => Effect.Effect ( filter: Predicate.Predicate, orElse: (a: Y) => Effect.Effect ): (self: Effect.Effect) => Effect.Effect }, { ( self: Effect.Effect, filter: Predicate.Refinement, orElse: (a: X) => Effect.Effect ): Effect.Effect ( self: Effect.Effect, filter: Predicate.Predicate, orElse: (a: Y) => Effect.Effect ): Effect.Effect } >(3, ( self: Effect.Effect, filter: Predicate.Predicate, orElse: (a: A) => Effect.Effect ): Effect.Effect => core.flatMap( self, (a) => filter(a) ? core.succeed(a) : orElse(a) )) /* @internal */ export const filterOrFail = dual< { ( filter: Predicate.Refinement, orFailWith: (a: X) => E2 ): (self: Effect.Effect) => Effect.Effect ( filter: Predicate.Predicate, orFailWith: (a: Y) => E2 ): (self: Effect.Effect) => Effect.Effect }, { ( self: Effect.Effect, filter: Predicate.Refinement, orFailWith: (a: X) => E2 ): Effect.Effect ( self: Effect.Effect, filter: Predicate.Predicate, orFailWith: (a: Y) => E2 ): Effect.Effect } >(3, ( self: Effect.Effect, filter: Predicate.Predicate, orFailWith: (a: Y) => E2 ): Effect.Effect => filterOrElse(self, filter, (a) => core.failSync(() => orFailWith(a as Y)))) /* @internal */ export const findFirst = dual< ( f: (a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect>, ( elements: Iterable, f: (a: A, i: number) => Effect.Effect ) => Effect.Effect> >(2, (elements, f) => core.suspend(() => { const iterator = elements[Symbol.iterator]() const next = iterator.next() if (!next.done) { return findLoop(iterator, 0, f, next.value) } return core.succeed(Option.none()) })) const findLoop = ( iterator: Iterator, index: number, f: (a: A, i: number) => Effect.Effect, value: A ): Effect.Effect> => core.flatMap(f(value, index), (result) => { if (result) { return core.succeed(Option.some(value)) } const next = iterator.next() if (!next.done) { return findLoop(iterator, index + 1, f, next.value) } return core.succeed(Option.none()) }) /* @internal */ export const firstSuccessOf = (effects: Iterable>): Effect.Effect => core.suspend(() => { const list = Chunk.fromIterable(effects) if (!Chunk.isNonEmpty(list)) { return core.dieSync(() => internalCause.IllegalArgumentException(`Received an empty collection of effects`)) } return pipe( Chunk.tailNonEmpty(list), ReadonlyArray.reduce(Chunk.headNonEmpty(list), (left, right) => core.orElse(left, () => right)) ) }) /* @internal */ export const flipWith = dual< ( f: (effect: Effect.Effect) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (effect: Effect.Effect) => Effect.Effect ) => Effect.Effect >(2, (self, f) => core.flip(f(core.flip(self)))) /* @internal */ export const match = dual< ( options: { readonly onFailure: (error: E) => A2 readonly onSuccess: (value: A) => A3 } ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, options: { readonly onFailure: (error: E) => A2 readonly onSuccess: (value: A) => A3 } ) => Effect.Effect >(2, (self, { onFailure, onSuccess }) => core.matchEffect(self, { onFailure: (e) => core.succeed(onFailure(e)), onSuccess: (a) => core.succeed(onSuccess(a)) })) /* @internal */ export const every = dual< ( f: (a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect, (elements: Iterable, f: (a: A, i: number) => Effect.Effect) => Effect.Effect >(2, (elements, f) => core.suspend(() => forAllLoop(elements[Symbol.iterator](), 0, f))) const forAllLoop = ( iterator: Iterator, index: number, f: (a: A, i: number) => Effect.Effect ): Effect.Effect => { const next = iterator.next() return next.done ? core.succeed(true) : core.flatMap( f(next.value, index), (b) => b ? forAllLoop(iterator, index + 1, f) : core.succeed(b) ) } /* @internal */ export const forever = (self: Effect.Effect): Effect.Effect => { const loop: Effect.Effect = core.flatMap(core.flatMap(self, () => core.yieldNow()), () => loop) return loop } /** @internal */ class EffectGen { constructor(readonly value: Effect.Effect) { } [Symbol.iterator]() { return new SingleShotGen.SingleShotGen(this) } } const adapter = function() { let x = arguments[0] for (let i = 1; i < arguments.length; i++) { x = arguments[i](x) } return new EffectGen(x) as any } /** * Inspired by https://github.com/tusharmath/qio/pull/22 (revised) @internal */ export const gen: typeof Effect.gen = (f) => core.suspend(() => { const iterator = f(adapter) const state = iterator.next() const run = ( state: IteratorYieldResult | IteratorReturnResult ): Effect.Effect => (state.done ? core.succeed(state.value) : pipe( state.value.value as unknown as Effect.Effect, core.flatMap((val: any) => run(iterator.next(val))) )) return run(state) }) /* @internal */ export const fiberRefs: Effect.Effect = core.withFiberRuntime< never, never, FiberRefs.FiberRefs >((state) => core.succeed(state.getFiberRefs())) /* @internal */ export const head = ( self: Effect.Effect> ): Effect.Effect, A> => core.matchEffect(self, { onFailure: (e) => core.fail(Option.some(e)), onSuccess: (as) => { const iterator = as[Symbol.iterator]() const next = iterator.next() if (next.done) { return core.fail(Option.none()) } return core.succeed(next.value) } }) /* @internal */ export const ignore = (self: Effect.Effect): Effect.Effect => match(self, { onFailure: constVoid, onSuccess: constVoid }) /* @internal */ export const ignoreLogged = (self: Effect.Effect): Effect.Effect => core.matchCauseEffect(self, { onFailure: (cause) => logDebug(cause, "An error was silently ignored because it is not anticipated to be useful"), onSuccess: () => core.unit }) /* @internal */ export const inheritFiberRefs = (childFiberRefs: FiberRefs.FiberRefs) => updateFiberRefs((parentFiberId, parentFiberRefs) => FiberRefs.joinAs(parentFiberRefs, parentFiberId, childFiberRefs)) /* @internal */ export const isFailure = (self: Effect.Effect): Effect.Effect => match(self, { onFailure: constTrue, onSuccess: constFalse }) /* @internal */ export const isSuccess = (self: Effect.Effect): Effect.Effect => match(self, { onFailure: constFalse, onSuccess: constTrue }) /* @internal */ export const iterate = ( initial: Z, options: { readonly while: (z: Z) => boolean readonly body: (z: Z) => Effect.Effect } ): Effect.Effect => core.suspend(() => { if (options.while(initial)) { return core.flatMap(options.body(initial), (z2) => iterate(z2, options)) } return core.succeed(initial) }) const logWithLevel = (level?: LogLevel.LogLevel) => ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ): Effect.Effect => { const levelOption = Option.fromNullable(level) let message: unknown let cause: Cause.Cause if (internalCause.isCause(messageOrCause)) { cause = messageOrCause message = (supplementary as unknown) ?? "" } else { message = messageOrCause cause = (supplementary as Cause.Cause) ?? internalCause.empty } return core.withFiberRuntime((fiberState) => { fiberState.log(message, cause, levelOption) return core.unit }) } /** @internal */ export const log: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect.Effect = logWithLevel() /** @internal */ export const logTrace: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect.Effect = logWithLevel(LogLevel.Trace) /** @internal */ export const logDebug: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect.Effect = logWithLevel(LogLevel.Debug) /** @internal */ export const logInfo: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect.Effect = logWithLevel(LogLevel.Info) /** @internal */ export const logWarning: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect.Effect = logWithLevel(LogLevel.Warning) /** @internal */ export const logError: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect.Effect = logWithLevel(LogLevel.Error) /** @internal */ export const logFatal: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect.Effect = logWithLevel(LogLevel.Fatal) /* @internal */ export const withLogSpan = dual< (label: string) => (effect: Effect.Effect) => Effect.Effect, (effect: Effect.Effect, label: string) => Effect.Effect >(2, (effect, label) => core.flatMap(Clock.currentTimeMillis, (now) => core.fiberRefLocallyWith( effect, core.currentLogSpan, List.prepend(LogSpan.make(label, now)) ))) /* @internal */ export const logAnnotations: Effect.Effect> = core .fiberRefGet( core.currentLogAnnotations ) /* @internal */ // @ts-expect-error export const loop: { ( initial: Z, options: { readonly while: (z: Z) => boolean readonly step: (z: Z) => Z readonly body: (z: Z) => Effect.Effect readonly discard?: false | undefined } ): Effect.Effect> ( initial: Z, options: { readonly while: (z: Z) => boolean readonly step: (z: Z) => Z readonly body: (z: Z) => Effect.Effect readonly discard: true } ): Effect.Effect } = ( initial: Z, options: { readonly while: (z: Z) => boolean readonly step: (z: Z) => Z readonly body: (z: Z) => Effect.Effect readonly discard?: boolean } ): Effect.Effect> | Effect.Effect => options.discard ? loopDiscard(initial, options.while, options.step, options.body) : core.map(loopInternal(initial, options.while, options.step, options.body), (x) => Array.from(x)) const loopInternal = ( initial: Z, cont: (z: Z) => boolean, inc: (z: Z) => Z, body: (z: Z) => Effect.Effect ): Effect.Effect> => core.suspend(() => cont(initial) ? core.flatMap(body(initial), (a) => core.map( loopInternal(inc(initial), cont, inc, body), List.prepend(a) )) : core.sync(() => List.empty()) ) const loopDiscard = ( initial: Z, cont: (z: Z) => boolean, inc: (z: Z) => Z, body: (z: Z) => Effect.Effect ): Effect.Effect => core.suspend(() => cont(initial) ? core.flatMap( body(initial), () => loopDiscard(inc(initial), cont, inc, body) ) : core.unit ) /* @internal */ export const mapAccum = dual< ( zero: Z, f: (z: Z, a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect]>, ( elements: Iterable, zero: Z, f: (z: Z, a: A, i: number) => Effect.Effect ) => Effect.Effect]> >(3, ( elements: Iterable, zero: Z, f: (z: Z, a: A, i: number) => Effect.Effect ) => core.suspend(() => { const iterator = elements[Symbol.iterator]() const builder: Array = [] let result: Effect.Effect = core.succeed(zero) let next: IteratorResult let i = 0 while (!(next = iterator.next()).done) { const index = i++ result = core.flatMap(result, (state) => core.map(f(state, next.value, index), ([z, b]) => { builder.push(b) return z })) } return core.map(result, (z) => [z, builder] as const) })) /* @internal */ export const mapErrorCause = dual< ( f: (cause: Cause.Cause) => Cause.Cause ) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, f: (cause: Cause.Cause) => Cause.Cause) => Effect.Effect >(2, (self, f) => core.matchCauseEffect(self, { onFailure: (c) => core.failCauseSync(() => f(c)), onSuccess: core.succeed })) /* @internal */ export const memoize = ( self: Effect.Effect ): Effect.Effect> => pipe( core.deferredMake< E, readonly [ readonly [ FiberRefsPatch.FiberRefsPatch, runtimeFlagsPatch.RuntimeFlagsPatch ], A ] >(), core.flatMap((deferred) => pipe( diffFiberRefsAndRuntimeFlags(self), core.intoDeferred(deferred), once, core.map((complete) => core.zipRight( complete, pipe( core.deferredAwait(deferred), core.flatMap(([patch, a]) => core.as(core.zip(patchFiberRefs(patch[0]), core.updateRuntimeFlags(patch[1])), a) ) ) ) ) ) ) ) /* @internal */ export const merge = (self: Effect.Effect): Effect.Effect => core.matchEffect(self, { onFailure: (e) => core.succeed(e), onSuccess: core.succeed }) /* @internal */ export const negate = (self: Effect.Effect): Effect.Effect => core.map(self, (b) => !b) /* @internal */ export const none = ( self: Effect.Effect> ): Effect.Effect, void> => core.matchEffect(self, { onFailure: (e) => core.fail(Option.some(e)), onSuccess: (option) => { switch (option._tag) { case "None": { return core.unit } case "Some": { return core.fail(Option.none()) } } } }) /* @internal */ export const once = ( self: Effect.Effect ): Effect.Effect> => core.map( Ref.make(true), (ref) => core.asUnit(core.whenEffect(self, Ref.getAndSet(ref, false))) ) /* @internal */ export const option = (self: Effect.Effect): Effect.Effect> => core.matchEffect(self, { onFailure: () => core.succeed(Option.none()), onSuccess: (a) => core.succeed(Option.some(a)) }) /* @internal */ export const orElseFail = dual< (evaluate: LazyArg) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, evaluate: LazyArg) => Effect.Effect >(2, (self, evaluate) => core.orElse(self, () => core.failSync(evaluate))) /* @internal */ export const orElseSucceed = dual< (evaluate: LazyArg) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, evaluate: LazyArg) => Effect.Effect >(2, (self, evaluate) => core.orElse(self, () => core.sync(evaluate))) /* @internal */ export const parallelErrors = (self: Effect.Effect): Effect.Effect, A> => core.matchCauseEffect(self, { onFailure: (cause) => { const errors = Array.from(internalCause.failures(cause)) return errors.length === 0 ? core.failCause(cause as Cause.Cause) : core.fail(errors) }, onSuccess: core.succeed }) /* @internal */ export const patchFiberRefs = (patch: FiberRefsPatch.FiberRefsPatch): Effect.Effect => updateFiberRefs((fiberId, fiberRefs) => pipe(patch, fiberRefsPatch.patch(fiberId, fiberRefs))) /* @internal */ export const promise = (evaluate: (signal: AbortSignal) => Promise): Effect.Effect => evaluate.length >= 1 ? core.async((resolve, signal) => { evaluate(signal) .then((a) => resolve(core.exitSucceed(a))) .catch((e) => resolve(core.exitDie(e))) }) : core.async((resolve) => { ;(evaluate as LazyArg>)() .then((a) => resolve(core.exitSucceed(a))) .catch((e) => resolve(core.exitDie(e))) }) /* @internal */ export const provideService = dual< >( tag: T, service: Context.Tag.Service ) => (self: Effect.Effect) => Effect.Effect>, E, A>, >( self: Effect.Effect, tag: T, service: Context.Tag.Service ) => Effect.Effect>, E, A> >(3, (self, tag, service) => provideServiceEffect(self, tag, core.succeed(service))) /* @internal */ export const provideServiceEffect = dual< , R1, E1>( tag: T, effect: Effect.Effect> ) => (self: Effect.Effect) => Effect.Effect>, E | E1, A>, , R1, E1>( self: Effect.Effect, tag: T, effect: Effect.Effect> ) => Effect.Effect>, E | E1, A> >(3, , R1, E1>( self: Effect.Effect, tag: T, effect: Effect.Effect> ) => core.contextWithEffect((env: Context.Context>>) => core.flatMap( effect, (service) => core.provideContext(self, pipe(env, Context.add(tag, service)) as Context.Context) ) )) /* @internal */ export const random: Effect.Effect = defaultServices.randomWith(core.succeed) /* @internal */ export const reduce = dual< ( zero: Z, f: (z: Z, a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect, ( elements: Iterable, zero: Z, f: (z: Z, a: A, i: number) => Effect.Effect ) => Effect.Effect >( 3, (elements: Iterable, zero: Z, f: (z: Z, a: A, i: number) => Effect.Effect) => ReadonlyArray.fromIterable(elements).reduce( (acc, el, i) => core.flatMap(acc, (a) => f(a, el, i)), core.succeed(zero) as Effect.Effect ) ) /* @internal */ export const reduceRight = dual< ( zero: Z, f: (a: A, z: Z, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect, ( elements: Iterable, zero: Z, f: (a: A, z: Z, i: number) => Effect.Effect ) => Effect.Effect >( 3, (elements: Iterable, zero: Z, f: (a: A, z: Z, i: number) => Effect.Effect) => ReadonlyArray.fromIterable(elements).reduceRight( (acc, el, i) => core.flatMap(acc, (a) => f(el, a, i)), core.succeed(zero) as Effect.Effect ) ) /* @internal */ export const reduceWhile = dual< ( zero: Z, options: { readonly while: Predicate.Predicate readonly body: (s: Z, a: A, i: number) => Effect.Effect } ) => (elements: Iterable) => Effect.Effect, ( elements: Iterable, zero: Z, options: { readonly while: Predicate.Predicate readonly body: (s: Z, a: A, i: number) => Effect.Effect } ) => Effect.Effect >(3, ( elements: Iterable, zero: Z, options: { readonly while: Predicate.Predicate readonly body: (s: Z, a: A, i: number) => Effect.Effect } ) => core.flatMap( core.sync(() => elements[Symbol.iterator]()), (iterator) => reduceWhileLoop(iterator, 0, zero, options.while, options.body) )) const reduceWhileLoop = ( iterator: Iterator, index: number, state: Z, predicate: Predicate.Predicate, f: (s: Z, a: A, i: number) => Effect.Effect ): Effect.Effect => { const next = iterator.next() if (!next.done && predicate(state)) { return core.flatMap( f(state, next.value, index), (nextState) => reduceWhileLoop(iterator, index + 1, nextState, predicate, f) ) } return core.succeed(state) } /* @internal */ export const repeatN = dual< (n: number) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, n: number) => Effect.Effect >(2, (self, n) => core.suspend(() => repeatNLoop(self, n))) /* @internal */ const repeatNLoop = (self: Effect.Effect, n: number): Effect.Effect => core.flatMap(self, (a) => n <= 0 ? core.succeed(a) : core.zipRight(core.yieldNow(), repeatNLoop(self, n - 1))) /* @internal */ export const sandbox = (self: Effect.Effect): Effect.Effect, A> => core.matchCauseEffect(self, { onFailure: core.fail, onSuccess: core.succeed }) /* @internal */ export const setFiberRefs = (fiberRefs: FiberRefs.FiberRefs): Effect.Effect => core.suspend(() => FiberRefs.setAll(fiberRefs)) /* @internal */ export const sleep: (duration: Duration.DurationInput) => Effect.Effect = Clock.sleep /* @internal */ export const succeedNone: Effect.Effect> = core.succeed(Option.none()) /* @internal */ export const succeedSome = (value: A): Effect.Effect> => core.succeed(Option.some(value)) /* @internal */ export const summarized = dual< ( summary: Effect.Effect, f: (start: B, end: B) => C ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, summary: Effect.Effect, f: (start: B, end: B) => C ) => Effect.Effect >( 3, (self, summary, f) => core.flatMap( summary, (start) => core.flatMap(self, (value) => core.map(summary, (end) => [f(start, end), value] as const)) ) ) /* @internal */ export const tagMetrics = dual< (key: string, value: string) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, key: string, value: string) => Effect.Effect >(3, (self, key, value) => labelMetrics(self, [metricLabel.make(key, value)])) /* @internal */ export const labelMetrics = dual< (labels: Iterable) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, labels: Iterable) => Effect.Effect >(2, (self, labels) => labelMetricsSet(self, HashSet.fromIterable(labels))) /* @internal */ export const labelMetricsSet = dual< (labels: HashSet.HashSet) => ( self: Effect.Effect ) => Effect.Effect, (self: Effect.Effect, labels: HashSet.HashSet) => Effect.Effect >( 2, (self, labels) => core.fiberRefLocallyWith(core.currentMetricLabels, (set) => pipe(set, HashSet.union(labels)))(self) ) /* @internal */ export const takeUntil = dual< ( predicate: (a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect>, ( elements: Iterable, predicate: (a: A, i: number) => Effect.Effect ) => Effect.Effect> >( 2, (elements: Iterable, predicate: (a: A, i: number) => Effect.Effect) => core.suspend(() => { const iterator = elements[Symbol.iterator]() const builder: Array = [] let next: IteratorResult let effect: Effect.Effect = core.succeed(false) let i = 0 while ((next = iterator.next()) && !next.done) { const a = next.value const index = i++ effect = core.flatMap(effect, (bool) => { if (bool) { return core.succeed(true) } builder.push(a) return predicate(a, index) }) } return core.map(effect, () => builder) }) ) /* @internal */ export const takeWhile = dual< ( predicate: (a: A, i: number) => Effect.Effect ) => (elements: Iterable) => Effect.Effect>, ( elements: Iterable, predicate: (a: A, i: number) => Effect.Effect ) => Effect.Effect> >( 2, (elements: Iterable, predicate: (a: A, i: number) => Effect.Effect) => core.suspend(() => { const iterator = elements[Symbol.iterator]() const builder: Array = [] let next: IteratorResult let taking: Effect.Effect = core.succeed(true) let i = 0 while ((next = iterator.next()) && !next.done) { const a = next.value const index = i++ taking = core.flatMap(taking, (taking) => pipe( taking ? predicate(a, index) : core.succeed(false), core.map((bool) => { if (bool) { builder.push(a) } return bool }) )) } return core.map(taking, () => builder) }) ) /* @internal */ export const tapBoth = dual< ( options: { readonly onFailure: (e: XE) => Effect.Effect readonly onSuccess: (a: XA) => Effect.Effect } ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, options: { readonly onFailure: (e: XE) => Effect.Effect readonly onSuccess: (a: XA) => Effect.Effect } ) => Effect.Effect >(2, (self, { onFailure, onSuccess }) => core.matchCauseEffect(self, { onFailure: (cause) => { const either = internalCause.failureOrCause(cause) switch (either._tag) { case "Left": { return core.zipRight(onFailure(either.left as any), core.failCause(cause)) } case "Right": { return core.failCause(cause) } } }, onSuccess: (a) => core.as(onSuccess(a as any), a) })) /* @internal */ export const tapDefect = dual< ( f: (cause: Cause.Cause) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (cause: Cause.Cause) => Effect.Effect ) => Effect.Effect >(2, (self, f) => core.catchAllCause(self, (cause) => Option.match(internalCause.keepDefects(cause), { onNone: () => core.failCause(cause), onSome: (a) => core.zipRight(f(a), core.failCause(cause)) }))) /* @internal */ export const tapError = dual< ( f: (e: XE) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (e: XE) => Effect.Effect ) => Effect.Effect >(2, (self, f) => core.matchCauseEffect(self, { onFailure: (cause) => { const either = internalCause.failureOrCause(cause) switch (either._tag) { case "Left": { return core.zipRight(f(either.left as any), core.failCause(cause)) } case "Right": { return core.failCause(cause) } } }, onSuccess: core.succeed })) /* @internal */ export const tapErrorTag = dual< ( k: K, f: (e: Extract) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, k: K, f: (e: Extract) => Effect.Effect ) => Effect.Effect >(3, (self, k, f) => tapError(self, (e) => { if (Predicate.isTagged(e, k)) { return f(e as any) } return core.unit as any })) /* @internal */ export const tapErrorCause = dual< ( f: (cause: Cause.Cause) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (cause: Cause.Cause) => Effect.Effect ) => Effect.Effect >(2, (self, f) => core.matchCauseEffect(self, { onFailure: (cause) => core.zipRight(f(cause as any), core.failCause(cause)), onSuccess: core.succeed })) /* @internal */ export const timed = ( self: Effect.Effect ): Effect.Effect => timedWith(self, Clock.currentTimeNanos) /* @internal */ export const timedWith = dual< ( nanoseconds: Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, nanoseconds: Effect.Effect ) => Effect.Effect >( 2, (self, nanos) => summarized(self, nanos, (start, end) => Duration.nanos(end - start)) ) /* @internal */ export const tracerWith: (f: (tracer: Tracer.Tracer) => Effect.Effect) => Effect.Effect = Tracer.tracerWith /** @internal */ export const tracer: Effect.Effect = tracerWith(core.succeed) /* @internal */ export const tryPromise: { ( options: { readonly try: (signal: AbortSignal) => Promise readonly catch: (error: unknown) => E } ): Effect.Effect (try_: (signal: AbortSignal) => Promise): Effect.Effect } = ( arg: ((signal: AbortSignal) => Promise) | { readonly try: (signal: AbortSignal) => Promise readonly catch: (error: unknown) => E } ): Effect.Effect => { let evaluate: (signal?: AbortSignal) => Promise let catcher: ((error: unknown) => E) | undefined = undefined if (typeof arg === "function") { evaluate = arg as (signal?: AbortSignal) => Promise } else { evaluate = arg.try as (signal?: AbortSignal) => Promise catcher = arg.catch } if (evaluate.length >= 1) { return core.suspend(() => { const controller = new AbortController() return core.flatMap(try_(() => evaluate(controller.signal)), (promise) => core.async((resolve) => { promise .then((a) => resolve(core.exitSucceed(a))) .catch((e) => resolve(core.exitFail( catcher ? catcher(e) : e )) ) return core.sync(() => controller.abort()) })) }) } return core.flatMap( try_( arg as { readonly try: LazyArg> readonly catch: (error: unknown) => E } ), (promise) => core.async((resolve) => { promise .then((a) => resolve(core.exitSucceed(a))) .catch((e) => resolve(core.exitFail( catcher ? catcher(e) : e )) ) }) ) } /* @internal */ export const tryMap = dual< ( options: { readonly try: (a: A) => B readonly catch: (error: unknown) => E1 } ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, options: { readonly try: (a: A) => B readonly catch: (error: unknown) => E1 } ) => Effect.Effect >(2, (self, options) => core.flatMap(self, (a) => try_({ try: () => options.try(a), catch: options.catch }))) /* @internal */ export const tryMapPromise = dual< ( options: { readonly try: (a: A, signal: AbortSignal) => Promise readonly catch: (error: unknown) => E1 } ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, options: { readonly try: (a: A, signal: AbortSignal) => Promise readonly catch: (error: unknown) => E1 } ) => Effect.Effect >(2, ( self: Effect.Effect, options: { readonly try: (a: A, signal: AbortSignal) => Promise readonly catch: (error: unknown) => E1 } ): Effect.Effect => core.flatMap(self, (a) => tryPromise({ try: options.try.length >= 1 ? (signal) => options.try(a, signal) : () => (options.try as (a: A) => Promise)(a), catch: options.catch }))) /* @internal */ export const unless = dual< (predicate: LazyArg) => (self: Effect.Effect) => Effect.Effect>, (self: Effect.Effect, predicate: LazyArg) => Effect.Effect> >(2, (self, predicate) => core.suspend(() => predicate() ? succeedNone : asSome(self) )) /* @internal */ export const unlessEffect = dual< ( predicate: Effect.Effect ) => (self: Effect.Effect) => Effect.Effect>, ( self: Effect.Effect, predicate: Effect.Effect ) => Effect.Effect> >(2, (self, predicate) => core.flatMap(predicate, (b) => (b ? succeedNone : asSome(self)))) /* @internal */ export const unsandbox = (self: Effect.Effect, A>) => mapErrorCause(self, internalCause.flatten) /* @internal */ export const updateFiberRefs = ( f: (fiberId: FiberId.Runtime, fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs ): Effect.Effect => core.withFiberRuntime((state) => { state.setFiberRefs(f(state.id(), state.getFiberRefs())) return core.unit }) /* @internal */ export const updateService = dual< >( tag: T, f: (service: Context.Tag.Service) => Context.Tag.Service ) => (self: Effect.Effect) => Effect.Effect, E, A>, >( self: Effect.Effect, tag: T, f: (service: Context.Tag.Service) => Context.Tag.Service ) => Effect.Effect, E, A> >(3, >( self: Effect.Effect, tag: T, f: (service: Context.Tag.Service) => Context.Tag.Service ) => core.mapInputContext(self, (context) => Context.add( context, tag, f(Context.unsafeGet(context, tag)) )) as Effect.Effect, E, A>) /* @internal */ export const when = dual< (predicate: LazyArg) => (self: Effect.Effect) => Effect.Effect>, (self: Effect.Effect, predicate: LazyArg) => Effect.Effect> >(2, (self, predicate) => core.suspend(() => predicate() ? core.map(self, Option.some) : core.succeed(Option.none()) )) /* @internal */ export const whenFiberRef = dual< ( fiberRef: FiberRef.FiberRef, predicate: Predicate.Predicate ) => (self: Effect.Effect) => Effect.Effect]>, ( self: Effect.Effect, fiberRef: FiberRef.FiberRef, predicate: Predicate.Predicate ) => Effect.Effect]> >( 3, (self: Effect.Effect, fiberRef: FiberRef.FiberRef, predicate: Predicate.Predicate) => core.flatMap(core.fiberRefGet(fiberRef), (s) => predicate(s) ? core.map(self, (a) => [s, Option.some(a)] as const) : core.succeed<[S, Option.Option]>([s, Option.none()])) ) /* @internal */ export const whenRef = dual< ( ref: Ref.Ref, predicate: Predicate.Predicate ) => (self: Effect.Effect) => Effect.Effect]>, ( self: Effect.Effect, ref: Ref.Ref, predicate: Predicate.Predicate ) => Effect.Effect]> >( 3, (self: Effect.Effect, ref: Ref.Ref, predicate: Predicate.Predicate) => core.flatMap(Ref.get(ref), (s) => predicate(s) ? core.map(self, (a) => [s, Option.some(a)] as const) : core.succeed<[S, Option.Option]>([s, Option.none()])) ) /* @internal */ export const withMetric = dual< ( metric: Metric.Metric ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, metric: Metric.Metric ) => Effect.Effect >(2, (self, metric) => metric(self)) /** @internal */ export const serviceFunctionEffect = , Args extends Array, R, E, A>( service: T, f: (_: Context.Tag.Service) => (...args: Args) => Effect.Effect ) => (...args: Args): Effect.Effect, E, A> => core.flatMap(service, (a) => f(a)(...args)) /** @internal */ export const serviceFunction = , Args extends Array, A>( service: T, f: (_: Context.Tag.Service) => (...args: Args) => A ) => (...args: Args): Effect.Effect, never, A> => core.map(service, (a) => f(a)(...args)) /** @internal */ export const serviceFunctions = ( tag: Context.Tag ): { [k in { [k in keyof S]: S[k] extends (...args: Array) => Effect.Effect ? k : never }[keyof S]]: S[k] extends (...args: infer Args) => Effect.Effect ? (...args: Args) => Effect.Effect : never } => new Proxy({} as any, { get(_target: any, prop: any, _receiver) { return (...args: Array) => core.flatMap(tag, (s: any) => s[prop](...args)) } }) /** @internal */ export const serviceConstants = ( tag: Context.Tag ): { [k in { [k in keyof S]: S[k] extends Effect.Effect ? k : never }[keyof S]]: S[k] extends Effect.Effect ? Effect.Effect : never } => new Proxy({} as any, { get(_target: any, prop: any, _receiver) { return core.flatMap(tag, (s: any) => s[prop]) } }) /** @internal */ export const serviceMembers = (tag: Context.Tag): { functions: { [k in { [k in keyof S]: S[k] extends (...args: Array) => Effect.Effect ? k : never }[keyof S]]: S[k] extends (...args: infer Args) => Effect.Effect ? (...args: Args) => Effect.Effect : never } constants: { [k in { [k in keyof S]: S[k] extends Effect.Effect ? k : never }[keyof S]]: S[k] extends Effect.Effect ? Effect.Effect : never } } => ({ functions: serviceFunctions(tag), constants: serviceConstants(tag) }) // ----------------------------------------------------------------------------- // tracing // ----------------------------------------------------------------------------- /* @internal */ export const annotateCurrentSpan: { (key: string, value: Tracer.AttributeValue): Effect.Effect (values: Record): Effect.Effect } = function(): Effect.Effect { const args = arguments return core.flatMap( currentSpan, (span) => span._tag === "Some" ? core.sync(() => { if (typeof args[0] === "string") { span.value.attribute(args[0], args[1]) } else { for (const key in args[0]) { span.value.attribute(key, args[0][key]) } } }) : core.unit ) } /* @internal */ export const annotateSpans = dual< { (key: string, value: Tracer.AttributeValue): (effect: Effect.Effect) => Effect.Effect ( values: Record ): (effect: Effect.Effect) => Effect.Effect }, { (effect: Effect.Effect, key: string, value: Tracer.AttributeValue): Effect.Effect (effect: Effect.Effect, values: Record): Effect.Effect } >( (args) => core.isEffect(args[0]), function() { const args = arguments return core.fiberRefLocallyWith( args[0] as Effect.Effect, core.currentTracerSpanAnnotations, typeof args[1] === "string" ? HashMap.set(args[1], args[2]) : (annotations) => Object.entries(args[1] as Record).reduce( (acc, [key, value]) => HashMap.set(acc, key, value), annotations ) ) } ) /* @internal */ export const currentParentSpan: Effect.Effect> = core.map( core.fiberRefGet(core.currentTracerSpan), List.head ) /* @internal */ export const currentSpan: Effect.Effect> = core.map( core.fiberRefGet(core.currentTracerSpan), List.findFirst((span): span is Tracer.Span => span._tag === "Span") ) const bigint0 = BigInt(0) /** @internal */ export const currentTimeNanosTracing = core.fiberRefGetWith( core.currentTracerTimingEnabled, (enabled) => enabled ? Clock.currentTimeNanos : core.succeed(bigint0) ) /* @internal */ export const linkSpans = dual< ( span: Tracer.ParentSpan, attributes?: Record ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, span: Tracer.ParentSpan, attributes?: Record ) => Effect.Effect >( (args) => core.isEffect(args[0]), (self, span, attributes) => core.fiberRefLocallyWith( self, core.currentTracerSpanLinks, Chunk.append( { _tag: "SpanLink", span, attributes: attributes ?? {} } as const ) ) ) /** @internal */ export const makeSpan = ( name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } ) => tracerWith((tracer) => core.flatMap( options?.parent ? succeedSome(options.parent) : options?.root ? succeedNone : currentParentSpan, (parent) => core.flatMap( core.fiberRefGet(core.currentTracerSpanAnnotations), (annotations) => core.flatMap( core.fiberRefGet(core.currentTracerSpanLinks), (links) => core.flatMap( currentTimeNanosTracing, (startTime) => core.sync(() => { const linksArray = options?.links ? [...Chunk.toReadonlyArray(links), ...options.links] : Chunk.toReadonlyArray(links) const span = tracer.span( name, parent, options?.context ?? Context.empty(), linksArray, startTime ) HashMap.forEach(annotations, (value, key) => span.attribute(key, value)) Object.entries(options?.attributes ?? {}).forEach(([k, v]) => span.attribute(k, v)) return span }) ) ) ) ) ) /* @internal */ export const spanAnnotations: Effect.Effect> = core .fiberRefGet(core.currentTracerSpanAnnotations) /* @internal */ export const spanLinks: Effect.Effect> = core .fiberRefGet(core.currentTracerSpanLinks) /** @internal */ export const useSpan: { (name: string, evaluate: (span: Tracer.Span) => Effect.Effect): Effect.Effect (name: string, options: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context }, evaluate: (span: Tracer.Span) => Effect.Effect): Effect.Effect } = ( name: string, ...args: [evaluate: (span: Tracer.Span) => Effect.Effect] | [ options: any, evaluate: (span: Tracer.Span) => Effect.Effect ] ) => { const options: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } | undefined = args.length === 1 ? undefined : args[0] const evaluate: (span: Tracer.Span) => Effect.Effect = args[args.length - 1] return core.acquireUseRelease( makeSpan(name, options), evaluate, (span, exit) => core.flatMap( currentTimeNanosTracing, (endTime) => core.sync(() => span.end(endTime, exit)) ) ) } /** @internal */ export const withParentSpan = dual< (span: Tracer.ParentSpan) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, span: Tracer.ParentSpan) => Effect.Effect >(2, (self, span) => core.fiberRefLocallyWith( self, core.currentTracerSpan, List.prepend(span) )) /** @internal */ export const withSpan = dual< (name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context }) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context }) => Effect.Effect >( (args) => typeof args[0] !== "string", (self, name, options) => useSpan( name, options ?? {}, (span) => withParentSpan(self, span) ) ) // ------------------------------------------------------------------------------------- // optionality // ------------------------------------------------------------------------------------- /* @internal */ export const fromNullable = (value: A): Effect.Effect> => value == null ? core.fail(internalCause.NoSuchElementException()) : core.succeed(value as NonNullable) /* @internal */ export const optionFromOptional = ( self: Effect.Effect ): Effect.Effect, Option.Option> => core.catchAll( core.map(self, Option.some), (error) => internalCause.isNoSuchElementException(error) ? succeedNone : core.fail(error as Exclude) )