1 | # async-sema
|
2 |
|
3 | This is a semaphore implementation for use with `async` and `await`. The
|
4 | implementation follows the traditional definition of a semaphore rather than the
|
5 | definition of an asynchronous semaphore seen in some js community examples.
|
6 | Where as the latter one generally allows every defined task to proceed
|
7 | immediately and synchronizes at the end, async-sema allows only a selected
|
8 | number of tasks to proceed at once while the rest will remain waiting.
|
9 |
|
10 | Async-sema manages the semaphore count as a list of tokens instead of a single
|
11 | variable containing the number of available resources. This enables an
|
12 | interesting application of managing the actual resources with the semaphore
|
13 | object itself. To make it practical the constructor for Sema includes an option
|
14 | for providing an init function for the semaphore tokens. Use of a custom token
|
15 | initializer is demonstrated in `examples/pooling.js`.
|
16 |
|
17 | ## Usage
|
18 |
|
19 | Firstly, add the package to your project's `dependencies`:
|
20 |
|
21 | ```bash
|
22 | npm install --save async-sema
|
23 | ```
|
24 |
|
25 | or
|
26 |
|
27 | ```bash
|
28 | yarn add async-sema
|
29 | ```
|
30 |
|
31 | Then start using it like shown in the following example. Check more
|
32 | use case examples [here](./examples).
|
33 |
|
34 | ## Example
|
35 |
|
36 | ```js
|
37 | const { Sema } = require('async-sema');
|
38 | const s = new Sema(
|
39 | 4, // Allow 4 concurrent async calls
|
40 | {
|
41 | capacity: 100 // Prealloc space for 100 tokens
|
42 | }
|
43 | );
|
44 |
|
45 | async function fetchData(x) {
|
46 | await s.acquire()
|
47 | try {
|
48 | console.log(s.nrWaiting() + ' calls to fetch are waiting')
|
49 | // ... do some async stuff with x
|
50 | } finally {
|
51 | s.release();
|
52 | }
|
53 | }
|
54 |
|
55 | const data = await Promise.all(array.map(fetchData));
|
56 | ```
|
57 |
|
58 | The package also offers a simple rate limiter utilizing the semaphore
|
59 | implementation.
|
60 |
|
61 | ```js
|
62 | const { RateLimit } = require('async-sema');
|
63 |
|
64 | async function f() {
|
65 | const lim = RateLimit(5); // rps
|
66 |
|
67 | for (let i = 0; i < n; i++) {
|
68 | await lim();
|
69 | // ... do something async
|
70 | }
|
71 | }
|
72 | ```
|
73 |
|
74 | ## API
|
75 |
|
76 | ### Sema
|
77 |
|
78 | #### Constructor(nr, { initFn, pauseFn, resumeFn, capacity })
|
79 |
|
80 | Creates a semaphore object. The first argument is mandatory and the second
|
81 | argument is optional.
|
82 |
|
83 | - `nr` The maximum number of callers allowed to acquire the semaphore
|
84 | concurrently.
|
85 | - `initFn` Function that is used to initialize the tokens used to manage
|
86 | the semaphore. The default is `() => '1'`.
|
87 | - `pauseFn` An optional fuction that is called to opportunistically request
|
88 | pausing the the incoming stream of data, instead of piling up waiting
|
89 | promises and possibly running out of memory.
|
90 | See [examples/pausing.js](./examples/pausing.js).
|
91 | - `resumeFn` An optional function that is called when there is room again
|
92 | to accept new waiters on the semaphore. This function must be declared
|
93 | if a `pauseFn` is declared.
|
94 | - `capacity` Sets the size of the preallocated waiting list inside the
|
95 | semaphore. This is typically used by high performance where the developer
|
96 | can make a rough estimate of the number of concurrent users of a semaphore.
|
97 |
|
98 | #### async drain()
|
99 |
|
100 | Drains the semaphore and returns all the initialized tokens in an array.
|
101 | Draining is an ideal way to ensure there are no pending async tasks, for
|
102 | example before a process will terminate.
|
103 |
|
104 | #### nrWaiting()
|
105 |
|
106 | Returns the number of callers waiting on the semaphore, i.e. the number of
|
107 | pending promises.
|
108 |
|
109 | #### tryAcquire()
|
110 |
|
111 | Attempt to acquire a token from the semaphore, if one is available immediately.
|
112 | Otherwise, return `undefined`.
|
113 |
|
114 | #### async acquire()
|
115 |
|
116 | Acquire a token from the semaphore, thus decrement the number of available
|
117 | execution slots. If `initFn` is not used then the return value of the function
|
118 | can be discarded.
|
119 |
|
120 | #### release(token)
|
121 |
|
122 | Release the semaphore, thus increment the number of free execution slots. If
|
123 | `initFn` is used then the `token` returned by `acquire()` should be given as
|
124 | an argument when calling this function.
|
125 |
|
126 | ### RateLimit(rps, { timeUnit, uniformDistribution })
|
127 |
|
128 | Creates a rate limiter function that blocks with a promise whenever the rate
|
129 | limit is hit and resolves the promise once the call rate is within the limit
|
130 | set by `rps`. The second argument is optional.
|
131 |
|
132 | The `timeUnit` is an optional argument setting the width of the rate limiting
|
133 | window in milliseconds. The default `timeUnit` is `1000 ms`, therefore making
|
134 | the `rps` argument act as requests per second limit.
|
135 |
|
136 | The `uniformDistribution` argument enforces a discrete uniform distribution over
|
137 | time, instead of the default that allows hitting the function `rps` time and
|
138 | then pausing for `timeWindow` milliseconds. Setting the `uniformDistribution`
|
139 | option is mainly useful in a situation where the flow of rate limit function
|
140 | calls is continuous and and occuring faster than `timeUnit` (e.g. reading a
|
141 | file) and not enabling it would cause the maximum number of calls to resolve
|
142 | immediately (thus exhaust the limit immediately) and therefore the next bunch
|
143 | calls would need to wait for `timeWindow` milliseconds. However if the flow is
|
144 | sparse then this option may make the
|
145 | code run slower with no advantages.
|
146 |
|
147 | ## Contributing
|
148 |
|
149 | 1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
|
150 | 2. Move into the directory of the clone: `cd async-sema`
|
151 | 3. Link it to the global module directory of Node.js: `npm link`
|
152 |
|
153 | 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.
|
154 |
|
155 | ## Author
|
156 |
|
157 | Olli Vanhoja ([@OVanhoja](https://twitter.com/OVanhoja))
|