File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11import { Semaphore } from "async-mutex"
22
3+ /**
4+ * A thin wrapper around `async-mutex`'s `Semaphore` that adds observable
5+ * queue-depth (`waiting`) and safe bulk-cancellation (`cancel()`).
6+ *
7+ * **Why not use `Semaphore` directly?**
8+ * `Semaphore` has no way to inspect how many callers are blocked waiting for a
9+ * permit. `TaskSemaphore` tracks that count so callers can make scheduling
10+ * decisions (e.g. "don't enqueue more work when the queue is already deep").
11+ *
12+ * **`_waiting`** is incremented before `sem.acquire()` is awaited (only when
13+ * the semaphore is already locked, i.e. the caller will actually block) and
14+ * decremented once the permit is granted or the acquire is rejected.
15+ *
16+ * **`_generation`** is a monotonically-increasing counter bumped on every
17+ * `cancel()` call. Each in-flight `acquire()` captures the generation at
18+ * enqueue time; when the acquire settles it only adjusts `_waiting` if the
19+ * generation hasn't changed, preventing stale decrements after a cancel has
20+ * already reset the counter to 0.
21+ */
322export class TaskSemaphore {
423 private sem : Semaphore
524 private _waiting = 0
@@ -32,6 +51,12 @@ export class TaskSemaphore {
3251 }
3352 }
3453
54+ /**
55+ * Rejects all queued waiters and resets the waiting count to 0.
56+ * Does NOT release or alter any held permits — callers that already
57+ * received a release function must still call it.
58+ * The semaphore remains usable after cancellation.
59+ */
3560 cancel ( ) : void {
3661 this . _waiting = 0
3762 this . _generation ++
Original file line number Diff line number Diff line change 11import { TaskSemaphore } from "../TaskSemaphore"
22
33describe ( "TaskSemaphore" , ( ) => {
4- beforeEach ( ( ) => {
5- vi . useFakeTimers ( )
6- } )
7-
8- afterEach ( ( ) => {
9- vi . useRealTimers ( )
10- } )
11-
124 it ( "acquire() resolves immediately when permits are available" , async ( ) => {
135 const sem = new TaskSemaphore ( 2 )
146 const release = await sem . acquire ( )
@@ -141,4 +133,20 @@ describe("TaskSemaphore", () => {
141133 expect ( sem . waiting ) . toBe ( 0 )
142134 release ( )
143135 } )
136+
137+ it ( "acquire() works after cancel() with permits still available" , async ( ) => {
138+ const sem = new TaskSemaphore ( 1 )
139+ sem . cancel ( ) // no waiters, no holders
140+ const release = await sem . acquire ( )
141+ expect ( sem . available ) . toBe ( 0 )
142+ release ( )
143+ expect ( sem . available ) . toBe ( 1 )
144+ } )
145+
146+ it ( "cancel() on an idle semaphore is a safe no-op" , ( ) => {
147+ const sem = new TaskSemaphore ( 2 )
148+ expect ( ( ) => sem . cancel ( ) ) . not . toThrow ( )
149+ expect ( sem . waiting ) . toBe ( 0 )
150+ expect ( sem . available ) . toBe ( 2 )
151+ } )
144152} )
You can’t perform that action at this time.
0 commit comments