Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
async-sema
Advanced tools
The async-sema package is a lightweight semaphore implementation for async/await in JavaScript. It is designed to control concurrent access to a common resource by multiple asynchronous operations. This is particularly useful in scenarios where you need to rate-limit access to an API, manage concurrent database transactions, or simply ensure that a certain section of your code does not get overwhelmed with too many concurrent executions.
Semaphore
This feature allows you to create a semaphore that limits the number of concurrent asynchronous operations. In the code sample, a semaphore with a concurrency limit of 1 is created, meaning only one async operation can enter the critical section at a time. This is useful for rate-limiting or ensuring that certain operations do not run concurrently.
const { Sema } = require('async-sema');
const s = new Sema(1); // Allow 1 concurrent async call
async function criticalSection() {
await s.acquire();
try {
// Your async logic here
} finally {
s.release();
}
}
RateLimiter
This feature implements a rate limiter, which is useful for controlling the rate at which functions are executed. In the example, a rate limiter is set to allow 5 operations per interval. This is particularly useful for API rate limiting or controlling the execution rate of any set of operations.
const { RateLimit } = require('async-sema');
const rl = new RateLimit(5); // 5 operations per interval
async function limitedOperation() {
await rl.acquire();
// Your async operation here
}
p-limit is a package that limits the number of promises running at any one time. It is similar to async-sema in that it helps manage concurrency, but it specifically works by limiting the number of promises rather than using a semaphore model. This can be simpler to use for promise-based control flow.
Bottleneck is a comprehensive rate limiter for Node.js and the browser. It offers more advanced features compared to async-sema, such as clustering support, priority, and weight options for jobs. It's a more feature-rich option for complex rate-limiting needs.
This is a semaphore implementation for use with async
and await
. The
implementation follows the traditional definition of a semaphore rather than the
definition of an asynchronous semaphore seen in some js community examples.
Where as the latter one generally allows every defined task to proceed
immediately and synchronizes at the end, async-sema allows only a selected
number of tasks to proceed at once while the rest will remain waiting.
Async-sema manages the semaphore count as a list of tokens instead of a single
variable containing the number of available resources. This enables an
interesting application of managing the actual resources with the semaphore
object itself. To make it practical the constructor for Sema includes an option
for providing an init function for the semaphore tokens. Use of a custom token
initializer is demonstrated in examples/pooling.js
.
Firstly, add the package to your project's dependencies
:
npm install --save async-sema
or
yarn add async-sema
Then start using it like shown in the following example. Check more use case examples here.
const { Sema } = require('async-sema');
const s = new Sema(
4, // Allow 4 concurrent async calls
{
capacity: 100 // Prealloc space for 100 tokens
}
);
async function fetchData(x) {
await s.acquire()
try {
console.log(s.nrWaiting() + ' calls to fetch are waiting')
// ... do some async stuff with x
} finally {
s.release();
}
}
const data = await Promise.all(array.map(fetchData));
The package also offers a simple rate limiter utilizing the semaphore implementation.
const { RateLimit } = require('async-sema');
async function f() {
const lim = RateLimit(5); // rps
for (let i = 0; i < n; i++) {
await lim();
// ... do something async
}
}
Creates a semaphore object. The first argument is mandatory and the second argument is optional.
nr
The maximum number of callers allowed to acquire the semaphore
concurrently.initFn
Function that is used to initialize the tokens used to manage
the semaphore. The default is () => '1'
.pauseFn
An optional fuction that is called to opportunistically request
pausing the the incoming stream of data, instead of piling up waiting
promises and possibly running out of memory.
See examples/pausing.js.resumeFn
An optional function that is called when there is room again
to accept new waiters on the semaphore. This function must be declared
if a pauseFn
is declared.capacity
Sets the size of the preallocated waiting list inside the
semaphore. This is typically used by high performance where the developer
can make a rough estimate of the number of concurrent users of a semaphore.Drains the semaphore and returns all the initialized tokens in an array. Draining is an ideal way to ensure there are no pending async tasks, for example before a process will terminate.
Returns the number of callers waiting on the semaphore, i.e. the number of pending promises.
Attempt to acquire a token from the semaphore, if one is available immediately.
Otherwise, return undefined
.
Acquire a token from the semaphore, thus decrement the number of available
execution slots. If initFn
is not used then the return value of the function
can be discarded.
Release the semaphore, thus increment the number of free execution slots. If
initFn
is used then the token
returned by acquire()
should be given as
an argument when calling this function.
Creates a rate limiter function that blocks with a promise whenever the rate
limit is hit and resolves the promise once the call rate is within the limit
set by rps
. The second argument is optional.
The timeUnit
is an optional argument setting the width of the rate limiting
window in milliseconds. The default timeUnit
is 1000 ms
, therefore making
the rps
argument act as requests per second limit.
The uniformDistribution
argument enforces a discrete uniform distribution over
time, instead of the default that allows hitting the function rps
time and
then pausing for timeWindow
milliseconds. Setting the uniformDistribution
option is mainly useful in a situation where the flow of rate limit function
calls is continuous and and occuring faster than timeUnit
(e.g. reading a
file) and not enabling it would cause the maximum number of calls to resolve
immediately (thus exhaust the limit immediately) and therefore the next bunch
calls would need to wait for timeWindow
milliseconds. However if the flow is
sparse then this option may make the
code run slower with no advantages.
cd async-sema
npm link
Inside the project where you want to test your clone of the package, you can now either use npm link async-sema
to link the clone to the local dependencies.
Olli Vanhoja (@OVanhoja)
FAQs
Semaphore using `async` and `await`
The npm package async-sema receives a total of 2,258,610 weekly downloads. As such, async-sema popularity was classified as popular.
We found that async-sema demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 61 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.