-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add semaphore concurrency rate limiting. Closes #60
- Loading branch information
1 parent
ff84026
commit 8c0a46b
Showing
9 changed files
with
5,512 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
'use strict'; | ||
|
||
module.exports = exports = semaphore; | ||
|
||
function semaphore (count) { | ||
const resolvers = []; | ||
let counter = count; | ||
|
||
let sem = { | ||
take, | ||
release, | ||
test | ||
}; | ||
|
||
Object.defineProperty(sem, 'count', { | ||
get: _ => counter, | ||
enumerable: true | ||
}); | ||
|
||
return sem; | ||
|
||
function take (timeout) { | ||
if (counter > 0) { | ||
--counter; | ||
return Promise.resolve(release); | ||
} | ||
return new Promise((resolve, reject) => { | ||
resolvers.push(_ => { | ||
--counter; | ||
resolve(release); | ||
}); | ||
if (timeout) { | ||
setTimeout(_ => { | ||
resolvers.shift(); | ||
const err = new Error(`Timed out after ${timeout}ms`); | ||
err.code = 'ETIMEDOUT'; | ||
reject(err); | ||
}, timeout); | ||
} | ||
}); | ||
} | ||
|
||
function release () { | ||
counter++; | ||
if (resolvers.length > 0) { | ||
resolvers.shift()(); | ||
} | ||
} | ||
|
||
function test () { | ||
if (counter < 1) return false; | ||
return take() && true; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.