No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

README.md 5.3 KiB

hace 3 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # limiter #
  2. [![Build Status](https://travis-ci.org/jhurliman/node-rate-limiter.png)](https://travis-ci.org/jhurliman/node-rate-limiter)
  3. [![NPM Downloads](https://img.shields.io/npm/dm/limiter.svg?style=flat)](https://www.npmjs.com/package/limiter)
  4. Provides a generic rate limiter for node.js. Useful for API clients, web
  5. crawling, or other tasks that need to be throttled. Two classes are exposed,
  6. RateLimiter and TokenBucket. TokenBucket provides a lower level interface to
  7. rate limiting with a configurable burst rate and drip rate. RateLimiter sits
  8. on top of the token bucket and adds a restriction on the maximum number of
  9. tokens that can be removed each interval to comply with common API
  10. restrictions like "150 requests per hour maximum".
  11. ## Installation ##
  12. Use NPM to install:
  13. npm install limiter
  14. ## Usage ##
  15. A simple example allowing 150 requests per hour:
  16. ```javascript
  17. var RateLimiter = require('limiter').RateLimiter;
  18. // Allow 150 requests per hour (the Twitter search limit). Also understands
  19. // 'second', 'minute', 'day', or a number of milliseconds
  20. var limiter = new RateLimiter(150, 'hour');
  21. // Throttle requests
  22. limiter.removeTokens(1, function(err, remainingRequests) {
  23. // err will only be set if we request more than the maximum number of
  24. // requests we set in the constructor
  25. // remainingRequests tells us how many additional requests could be sent
  26. // right this moment
  27. callMyRequestSendingFunction(...);
  28. });
  29. ```
  30. Another example allowing one message to be sent every 250ms:
  31. ```javascript
  32. var RateLimiter = require('limiter').RateLimiter;
  33. var limiter = new RateLimiter(1, 250);
  34. limiter.removeTokens(1, function() {
  35. callMyMessageSendingFunction(...);
  36. });
  37. ```
  38. The default behaviour is to wait for the duration of the rate limiting
  39. that’s currently in effect before the callback is fired, but if you
  40. pass in ```true``` as the third parameter, the callback will be fired
  41. immediately with remainingRequests set to -1:
  42. ```javascript
  43. var RateLimiter = require('limiter').RateLimiter;
  44. var limiter = new RateLimiter(150, 'hour', true); // fire CB immediately
  45. // Immediately send 429 header to client when rate limiting is in effect
  46. limiter.removeTokens(1, function(err, remainingRequests) {
  47. if (remainingRequests < 1) {
  48. response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
  49. response.end('429 Too Many Requests - your IP is being rate limited');
  50. } else {
  51. callMyMessageSendingFunction(...);
  52. }
  53. });
  54. ```
  55. A synchronous method, tryRemoveTokens(), is available in both RateLimiter and TokenBucket. This will return immediately with a boolean value indicating if the token removal was successful.
  56. ```javascript
  57. var RateLimiter = require('limiter').RateLimiter;
  58. var limiter = new RateLimiter(10, 'second');
  59. if (limiter.tryRemoveTokens(5))
  60. console.log('Tokens removed');
  61. else
  62. console.log('No tokens removed');
  63. ```
  64. To get the number of remaining tokens **outside** the `removeTokens`-callback
  65. simply use the `getTokensRemaining`-method.
  66. ```javascript
  67. var RateLimiter = require('limiter').RateLimiter;
  68. var limiter = new RateLimiter(1, 250);
  69. // returns 1 since we did not remove a token and our number of tokens per interval is 1
  70. limiter.getTokensRemaining();
  71. ```
  72. Using the token bucket directly to throttle at the byte level:
  73. ```javascript
  74. var BURST_RATE = 1024 * 1024 * 150; // 150KB/sec burst rate
  75. var FILL_RATE = 1024 * 1024 * 50; // 50KB/sec sustained rate
  76. var TokenBucket = require('limiter').TokenBucket;
  77. // We could also pass a parent token bucket in as the last parameter to
  78. // create a hierarchical token bucket
  79. var bucket = new TokenBucket(BURST_RATE, FILL_RATE, 'second', null);
  80. bucket.removeTokens(myData.byteLength, function() {
  81. sendMyData(myData);
  82. });
  83. ```
  84. ## Additional Notes ##
  85. Both the token bucket and rate limiter should be used with a message queue or
  86. some way of preventing multiple simultaneous calls to removeTokens().
  87. Otherwise, earlier messages may get held up for long periods of time if more
  88. recent messages are continually draining the token bucket. This can lead to
  89. out of order messages or the appearance of "lost" messages under heavy load.
  90. ## License ##
  91. (The MIT License)
  92. Copyright (c) 2013 John Hurliman. &lt;jhurliman@jhurliman.org&gt;
  93. Permission is hereby granted, free of charge, to any person obtaining
  94. a copy of this software and associated documentation files (the
  95. 'Software'), to deal in the Software without restriction, including
  96. without limitation the rights to use, copy, modify, merge, publish,
  97. distribute, sublicense, and/or sell copies of the Software, and to
  98. permit persons to whom the Software is furnished to do so, subject to
  99. the following conditions:
  100. The above copyright notice and this permission notice shall be
  101. included in all copies or substantial portions of the Software.
  102. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  103. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  104. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  105. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  106. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  107. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  108. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.