All files / src/sso mutex.ts

100% Statements 21/21
100% Branches 4/4
100% Functions 4/4
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411x   1x               1x 2x 2x     10x 10x 1x 1x   9x 9x 9x 9x       10x 10x 10x 1x 1x   9x 9x         1x  
import dbg from 'debug';
 
const debug = dbg('node-expose-sspi:mutex');
 
type ReleaseFn = () => void;
 
interface Task {
  resolve(releaseFn: ReleaseFn): void;
}
 
export class Mutex {
  private isBusy = false;
  private queue: Task[] = [];
 
  private onRelease(): void {
    debug('release');
    if (this.queue.length === 0) {
      this.isBusy = false;
      return;
    }
    const { resolve } = this.queue.shift() as Task;
    debug('decrease queue size', this.queue.length);
    this.isBusy = true;
    resolve(this.onRelease.bind(this));
  }
 
  async acquire(): Promise<ReleaseFn> {
    return new Promise((resolve) => {
      debug('acquire');
      if (!this.isBusy) {
        this.isBusy = true;
        return resolve(this.onRelease.bind(this));
      }
      this.queue.push({ resolve });
      debug('increase queue size', this.queue.length);
    });
  }
}
 
export const activeDirectoryMutex = new Mutex();