Skip to main content

Class: Semaphore

Defined in: limiter.ts:84

Counting semaphore with abort-aware acquire and dynamic priority. Internal primitive used by PerOriginSemaphore and LimiterMiddleware.

Hands out up to maxRequests concurrent slots. Further acquire()s queue. On every slot-open, the queue is searched for the lowest-priority waiter (re-evaluating getPriority on each — so panning the viewport re-sorts the queue if callers' priorities depend on viewport state). Ties break by FIFO arrival order. A Semaphore with no priorities is therefore equivalent to a plain FIFO queue.

Acquires with an AbortSignal reject (and never consume a slot) if the signal aborts before the slot is granted — either because it's already aborted at call time, or because it aborts while queued.

We use a single linear-scan find-min instead of a priority queue (heap) because priorities are dynamic — we have to re-evaluate every waiter's getPriority on each release anyway, which costs O(N). Linear scan + find- min in the same pass also costs O(N), with a smaller constant and simpler code; a heap would only win if we extracted multiple minima per release, which we don't (one slot opens at a time).

Constructors​

Constructor​

new Semaphore(options): Semaphore

Defined in: limiter.ts:89

Parameters​

options​
maxRequests​

number

Returns​

Semaphore

Methods​

acquire()​

acquire(signal?, getPriority?): Promise<() => void>

Defined in: limiter.ts:93

Parameters​

signal?​

AbortSignal

getPriority?​

() => Priority

Returns​

Promise<() => void>