Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. var Ioredis = require('ioredis');
  2. var redis = new Ioredis();
  3.  
  4. // Rolling window rate limiter
  5. //
  6. // key is a unique identifier for the process or function call being limited
  7. // exp is the expiry in milliseconds
  8. // maxnum is the number of function calls allowed before expiry
  9. var redis_limiter_rolling = function(key, maxnum, exp, next) {
  10. redis.multi([
  11. ['incr', 'limiter:num:' + key],
  12. ['time']
  13. ]).exec(function(err, results) {
  14. if (err) {
  15. next(err);
  16. } else {
  17. // unique incremented list number for this key
  18. var listnum = results[0][1];
  19. // current time
  20. var tcur = (parseInt(results[1][1][0], 10) * 1000) + Math.floor(parseInt(results[1][1][1], 10) / 1000);
  21. // absolute time of expiry
  22. var texpiry = tcur - exp;
  23. // get number of transacation in the last expiry time
  24. var listkey = 'limiter:list:' + key;
  25. redis.multi([
  26. ['zadd', listkey, tcur.toString(), listnum],
  27. ['zremrangebyscore', listkey, '-inf', texpiry.toString()],
  28. ['zcard', listkey]
  29. ]).exec(function(err, results) {
  30. if (err) {
  31. next(err);
  32. } else {
  33. // num is the number of calls in the last expiry time window
  34. var num = parseInt(results[2][1], 10);
  35. if (num <= maxnum) {
  36. // does not reach limit
  37. next(null, false, num, exp);
  38. } else {
  39. // limit surpassed
  40. next(null, true, num, exp);
  41. }
  42. }
  43. });
  44. }
  45. });
  46. };
  47.  
  48. // Lockout window rate limiter
  49. //
  50. // key is a unique identifier for the process or function call being limited
  51. // exp is the expiry in milliseconds
  52. // maxnum is the number of function calls allowed within expiry time
  53. var util_limiter_lockout = function(key, maxnum, exp, next) {
  54. // lockout rate limiter
  55. var idkey = 'limiter:lock:' + key;
  56. redis.incr(idkey, function(err, result) {
  57. if (err) {
  58. next(err);
  59. } else {
  60. if (result <= maxnum) {
  61. // still within number of allowable calls
  62. // - reset expiry and allow next function call
  63. redis.expire(idkey, exp, function(err) {
  64. if (err) {
  65. next(err);
  66. } else {
  67. next(null, false, result);
  68. }
  69. });
  70. } else {
  71. // too many calls, user must wait for expiry of idkey
  72. next(null, true, result);
  73. }
  74. }
  75. });
  76. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement