MCPcopy Create free account
hub / github.com/Effect-TS/effect / raceAllFirst

Function raceAllFirst

packages/effect/src/internal/effect.ts:1838–1881  ·  view source on GitHub ↗
(
  all: Iterable<Eff>,
  options?: {
    readonly onWinner?: (options: {
      readonly fiber: Fiber.Fiber<any, any>
      readonly index: number
      readonly parentFiber: Fiber.Fiber<any, any>
    }) => void
  }
)

Source from the content-addressed store, hash-verified

1836
1837/** @internal */
1838export const raceAllFirst = <Eff extends Effect.Effect<any, any, any>>(
1839 all: Iterable<Eff>,
1840 options?: {
1841 readonly onWinner?: (options: {
1842 readonly fiber: Fiber.Fiber<any, any>
1843 readonly index: number
1844 readonly parentFiber: Fiber.Fiber<any, any>
1845 }) => void
1846 }
1847): Effect.Effect<
1848 Effect.Success<Eff>,
1849 Effect.Error<Eff>,
1850 Effect.Services<Eff>
1851> =>
1852 withFiber((parent) => {
1853 const fibers = new Set<Fiber.Fiber<any, any>>()
1854 onExitUnsafe(parent, () => fibers.size === 0 ? undefined : fiberInterruptAll(fibers))
1855 return callbackNoSignal((resume) => {
1856 let done = false
1857 let i = 0
1858 for (const effect of all) {
1859 if (done) break
1860 const index = i++
1861 // Register the fiber before it runs, so a race it settles during its
1862 // first step interrupts it.
1863 const fiber = new FiberImpl(parent.context)
1864 fibers.add(fiber)
1865 fiber.addObserver((exit) => {
1866 fibers.delete(fiber)
1867 const isWinner = !done
1868 done = true
1869 resume(exit)
1870 if (isWinner) {
1871 interruptRaceLosers(fibers, parent)
1872 options?.onWinner?.({ fiber, index, parentFiber: parent })
1873 }
1874 })
1875 // Constructing the fiber runs the runtime metrics hook, which can settle the race.
1876 if (done) fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent))
1877 else fiber.evaluate(effect as any)
1878 if (done) break
1879 }
1880 }, fibers)
1881 })
1882
1883// Interrupt the losers as soon as the race settles. Waiting for the parent to
1884// resume leaves a gap, for example a scheduler yield, where a loser can

Callers 1

effect.tsFile · 0.85

Calls 10

addObserverMethod · 0.95
interruptUnsafeMethod · 0.95
evaluateMethod · 0.95
fiberInterruptAllFunction · 0.85
callbackNoSignalFunction · 0.85
interruptRaceLosersFunction · 0.85
fiberStackAnnotationsFunction · 0.85
addMethod · 0.65
deleteMethod · 0.65
resumeFunction · 0.50

Tested by

no test coverage detected