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

Class Latch

packages/effect/src/internal/effect.ts:6008–6092  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6006const LatchTypeId = "~effect/Latch"
6007
6008class Latch implements _Latch.Latch {
6009 readonly [LatchTypeId] = LatchTypeId
6010 waiters: Array<(_: Effect.Effect<void>) => void> = []
6011 scheduled: Array<(_: Effect.Effect<void>) => void> | undefined = undefined
6012 private _isOpen: boolean
6013
6014 constructor(isOpen: boolean) {
6015 this._isOpen = isOpen
6016 }
6017
6018 private scheduleUnsafe(fiber: Fiber.Fiber<unknown, unknown>) {
6019 if (this.waiters.length === 0) {
6020 return succeedTrue
6021 }
6022 if (this.scheduled === undefined) {
6023 this.scheduled = this.waiters
6024 fiber.currentDispatcher.scheduleTask(this.flushScheduled, 0)
6025 } else {
6026 for (let i = 0; i < this.waiters.length; i++) {
6027 this.scheduled.push(this.waiters[i])
6028 }
6029 }
6030 this.waiters = []
6031 return succeedTrue
6032 }
6033 private flushScheduled = () => {
6034 if (this.scheduled === undefined) return
6035 const waiters = this.scheduled
6036 this.scheduled = undefined
6037 for (let i = 0; i < waiters.length; i++) {
6038 waiters[i](exitVoid)
6039 }
6040 }
6041 private flushWaiters() {
6042 // swap both arrays out before any resume runs: a resumed waiter can
6043 // reentrantly close the latch and register new waiters, which must not
6044 // be drained by this flush
6045 const waiters = this.waiters
6046 this.waiters = []
6047 this.flushScheduled()
6048 for (let i = 0; i < waiters.length; i++) {
6049 waiters[i](exitVoid)
6050 }
6051 }
6052
6053 open = withFiber<boolean>((fiber) => {
6054 if (this._isOpen) return succeedFalse
6055 this._isOpen = true
6056 return this.scheduleUnsafe(fiber)
6057 })
6058 release = withFiber<boolean>((fiber) => this._isOpen ? succeedFalse : this.scheduleUnsafe(fiber))
6059 openUnsafe() {
6060 if (this._isOpen) return false
6061 this._isOpen = true
6062 this.flushWaiters()
6063 return true
6064 }
6065 await = callbackNoSignal<void>((resume) => {

Callers

nothing calls this directly

Calls 7

scheduleUnsafeMethod · 0.95
closeUnsafeMethod · 0.95
callbackNoSignalFunction · 0.85
flatMapFunction · 0.85
pushMethod · 0.65
resumeFunction · 0.50
syncFunction · 0.50

Tested by

no test coverage detected