import * as Either from "@effect/data/Either" import { dual, pipe } from "@effect/data/Function" import * as HashSet from "@effect/data/HashSet" import * as number from "@effect/data/Number" import * as Option from "@effect/data/Option" import * as order from "@effect/data/Order" import { pipeArguments } from "@effect/data/Pipeable" import type * as Cause from "@effect/io/Cause" import * as Clock from "@effect/io/Clock" 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 * as FiberStatus from "@effect/io/FiberStatus" import * as core from "@effect/io/internal/core" import * as fiberScope from "@effect/io/internal/fiberScope" import * as runtimeFlags from "@effect/io/internal/runtimeFlags" /** @internal */ const FiberSymbolKey = "@effect/io/Fiber" /** @internal */ export const FiberTypeId: Fiber.FiberTypeId = Symbol.for( FiberSymbolKey ) as Fiber.FiberTypeId /** @internal */ export const fiberVariance = { _E: (_: never) => _, _A: (_: never) => _ } /** @internal */ const fiberProto = { [FiberTypeId]: fiberVariance, pipe() { return pipeArguments(this, arguments) } } /** @internal */ const RuntimeFiberSymbolKey = "@effect/io/Fiber" /** @internal */ export const RuntimeFiberTypeId: Fiber.RuntimeFiberTypeId = Symbol.for( RuntimeFiberSymbolKey ) as Fiber.RuntimeFiberTypeId /** @internal */ export const Order: order.Order> = pipe( order.tuple, order.Order]>(number.Order, number.Order), order.mapInput((fiber: Fiber.RuntimeFiber) => [ (fiber.id() as FiberId.Runtime).startTimeMillis, (fiber.id() as FiberId.Runtime).id ] as const ) ) /** @internal */ export const isFiber = (u: unknown): u is Fiber.Fiber => typeof u === "object" && u != null && FiberTypeId in u /** @internal */ export const isRuntimeFiber = (self: Fiber.Fiber): self is Fiber.RuntimeFiber => RuntimeFiberTypeId in self /** @internal */ export const _await = (self: Fiber.Fiber): Effect.Effect> => self.await() /** @internal */ export const children = ( self: Fiber.Fiber ): Effect.Effect>> => self.children() /** @internal */ export const done = (exit: Exit.Exit): Fiber.Fiber => ({ ...fiberProto, id: () => FiberId.none, await: () => core.succeed(exit), children: () => core.succeed([]), inheritAll: () => core.unit, poll: () => core.succeed(Option.some(exit)), interruptAsFork: () => core.unit }) /** @internal */ export const dump = (self: Fiber.RuntimeFiber): Effect.Effect => core.map(self.status(), (status) => ({ id: self.id(), status })) /** @internal */ export const dumpAll = ( fibers: Iterable> ): Effect.Effect> => core.forEachSequential(fibers, dump) /** @internal */ export const fail = (error: E): Fiber.Fiber => done(Exit.fail(error)) /** @internal */ export const failCause = (cause: Cause.Cause): Fiber.Fiber => done(Exit.failCause(cause)) /** @internal */ export const fromEffect = (effect: Effect.Effect): Effect.Effect> => core.map(core.exit(effect), done) /** @internal */ export const id = (self: Fiber.Fiber): FiberId.FiberId => self.id() /** @internal */ export const inheritAll = (self: Fiber.Fiber): Effect.Effect => self.inheritAll() /** @internal */ export const interrupted = (fiberId: FiberId.FiberId): Fiber.Fiber => done(Exit.interrupt(fiberId)) /** @internal */ export const interruptAll = (fibers: Iterable>): Effect.Effect => core.flatMap(core.fiberId, (fiberId) => pipe(fibers, interruptAllAs(fiberId))) /** @internal */ export const interruptAllAs = dual< (fiberId: FiberId.FiberId) => (fibers: Iterable>) => Effect.Effect, (fibers: Iterable>, fiberId: FiberId.FiberId) => Effect.Effect >(2, (fibers, fiberId) => pipe( core.forEachSequentialDiscard(fibers, interruptAsFork(fiberId)), core.zipRight(pipe(fibers, core.forEachSequentialDiscard(_await))) )) /** @internal */ export const interruptAsFork = dual< (fiberId: FiberId.FiberId) => (self: Fiber.Fiber) => Effect.Effect, (self: Fiber.Fiber, fiberId: FiberId.FiberId) => Effect.Effect >(2, (self, fiberId) => self.interruptAsFork(fiberId)) /** @internal */ export const join = (self: Fiber.Fiber): Effect.Effect => core.zipLeft(core.flatten(self.await()), self.inheritAll()) /** @internal */ export const map = dual< (f: (a: A) => B) => (self: Fiber.Fiber) => Fiber.Fiber, (self: Fiber.Fiber, f: (a: A) => B) => Fiber.Fiber >(2, (self, f) => mapEffect(self, (a) => core.sync(() => f(a)))) /** @internal */ export const mapEffect = dual< (f: (a: A) => Effect.Effect) => (self: Fiber.Fiber) => Fiber.Fiber, (self: Fiber.Fiber, f: (a: A) => Effect.Effect) => Fiber.Fiber >(2, (self, f) => ({ ...fiberProto, id: () => self.id(), await: () => core.flatMap(self.await(), Exit.forEachEffect(f)), children: () => self.children(), inheritAll: () => self.inheritAll(), poll: () => core.flatMap(self.poll(), (result) => { switch (result._tag) { case "None": { return core.succeed(Option.none()) } case "Some": { return pipe( Exit.forEachEffect(result.value, f), core.map(Option.some) ) } } }), interruptAsFork: (id) => self.interruptAsFork(id) })) /** @internal */ export const mapFiber = dual< ( f: (a: A) => Fiber.Fiber ) => (self: Fiber.Fiber) => Effect.Effect>, ( self: Fiber.Fiber, f: (a: A) => Fiber.Fiber ) => Effect.Effect> >(2, ( self: Fiber.Fiber, f: (a: A) => Fiber.Fiber ) => core.map( self.await(), Exit.match({ onFailure: (cause): Fiber.Fiber => failCause(cause), onSuccess: (a) => f(a) }) )) /** @internal */ export const match = dual< ( options: { readonly onFiber: (fiber: Fiber.Fiber) => Z readonly onRuntimeFiber: (fiber: Fiber.RuntimeFiber) => Z } ) => (self: Fiber.Fiber) => Z, ( self: Fiber.Fiber, options: { readonly onFiber: (fiber: Fiber.Fiber) => Z readonly onRuntimeFiber: (fiber: Fiber.RuntimeFiber) => Z } ) => Z >(2, (self, { onFiber, onRuntimeFiber }) => { if (isRuntimeFiber(self)) { return onRuntimeFiber(self) } return onFiber(self) }) /** @internal */ export const never: Fiber.Fiber = { ...fiberProto, id: () => FiberId.none, await: () => core.never, children: () => core.succeed([]), inheritAll: () => core.never, poll: () => core.succeed(Option.none()), interruptAsFork: () => core.never } /** @internal */ export const orElse = dual< (that: Fiber.Fiber) => (self: Fiber.Fiber) => Fiber.Fiber, (self: Fiber.Fiber, that: Fiber.Fiber) => Fiber.Fiber >(2, (self, that) => ({ ...fiberProto, id: () => FiberId.getOrElse(self.id(), that.id()), await: () => core.zipWith( self.await(), that.await(), (exit1, exit2) => (Exit.isSuccess(exit1) ? exit1 : exit2) ), children: () => self.children(), inheritAll: () => core.zipRight(that.inheritAll(), self.inheritAll()), poll: () => core.zipWith( self.poll(), that.poll(), (option1, option2) => { switch (option1._tag) { case "None": { return Option.none() } case "Some": { return Exit.isSuccess(option1.value) ? option1 : option2 } } } ), interruptAsFork: (id) => pipe( core.interruptAsFiber(self, id), core.zipRight(pipe(that, core.interruptAsFiber(id))), core.asUnit ) })) /** @internal */ export const orElseEither = dual< (that: Fiber.Fiber) => (self: Fiber.Fiber) => Fiber.Fiber>, (self: Fiber.Fiber, that: Fiber.Fiber) => Fiber.Fiber> >(2, (self, that) => orElse(map(self, Either.left), map(that, Either.right))) /** @internal */ export const poll = (self: Fiber.Fiber): Effect.Effect>> => self.poll() // forked from https://github.com/sindresorhus/parse-ms/blob/4da2ffbdba02c6e288c08236695bdece0adca173/index.js // MIT License // Copyright (c) Sindre Sorhus (sindresorhus.com) /** @internal */ const parseMs = (milliseconds: number) => { const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil return { days: roundTowardsZero(milliseconds / 86400000), hours: roundTowardsZero(milliseconds / 3600000) % 24, minutes: roundTowardsZero(milliseconds / 60000) % 60, seconds: roundTowardsZero(milliseconds / 1000) % 60, milliseconds: roundTowardsZero(milliseconds) % 1000, microseconds: roundTowardsZero(milliseconds * 1000) % 1000, nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000 } } /** @internal */ const renderStatus = (status: FiberStatus.FiberStatus): string => { if (FiberStatus.isDone(status)) { return "Done" } if (FiberStatus.isRunning(status)) { return "Running" } const isInterruptible = runtimeFlags.interruptible(status.runtimeFlags) ? "interruptible" : "uninterruptible" return `Suspended(${isInterruptible})` } /** @internal */ export const pretty = (self: Fiber.RuntimeFiber): Effect.Effect => core.flatMap(Clock.currentTimeMillis, (now) => core.map(dump(self), (dump) => { const time = now - dump.id.startTimeMillis const { days, hours, milliseconds, minutes, seconds } = parseMs(time) const lifeMsg = (days === 0 ? "" : `${days}d`) + (days === 0 && hours === 0 ? "" : `${hours}h`) + (days === 0 && hours === 0 && minutes === 0 ? "" : `${minutes}m`) + (days === 0 && hours === 0 && minutes === 0 && seconds === 0 ? "" : `${seconds}s`) + `${milliseconds}ms` const waitMsg = FiberStatus.isSuspended(dump.status) ? (() => { const ids = FiberId.ids(dump.status.blockingOn) return HashSet.size(ids) > 0 ? `waiting on ` + Array.from(ids).map((id) => `${id}`).join(", ") : "" })() : "" const statusMsg = renderStatus(dump.status) return `[Fiber](#${dump.id.id}) (${lifeMsg}) ${waitMsg}\n Status: ${statusMsg}` })) /** @internal */ export const unsafeRoots = (): Array> => Array.from(fiberScope.globalScope.roots) /** @internal */ export const roots: Effect.Effect>> = core.sync(unsafeRoots) /** @internal */ export const status = (self: Fiber.RuntimeFiber): Effect.Effect => self.status() /** @internal */ export const succeed = (value: A): Fiber.Fiber => done(Exit.succeed(value)) /** @internal */ export const unit: Fiber.Fiber = succeed(void 0) /** @internal */ export const currentFiberURI = "@effect/io/FiberCurrent" /** @internal */ export const getCurrentFiber = (): Option.Option> => Option.fromNullable((globalThis as any)[currentFiberURI])