Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

backoff.js 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (c) 2012 Mathieu Turcotte
  2. // Licensed under the MIT license.
  3. var events = require('events');
  4. var precond = require('precond');
  5. var util = require('util');
  6. // A class to hold the state of a backoff operation. Accepts a backoff strategy
  7. // to generate the backoff delays.
  8. function Backoff(backoffStrategy) {
  9. events.EventEmitter.call(this);
  10. this.backoffStrategy_ = backoffStrategy;
  11. this.maxNumberOfRetry_ = -1;
  12. this.backoffNumber_ = 0;
  13. this.backoffDelay_ = 0;
  14. this.timeoutID_ = -1;
  15. this.handlers = {
  16. backoff: this.onBackoff_.bind(this)
  17. };
  18. }
  19. util.inherits(Backoff, events.EventEmitter);
  20. // Sets a limit, greater than 0, on the maximum number of backoffs. A 'fail'
  21. // event will be emitted when the limit is reached.
  22. Backoff.prototype.failAfter = function(maxNumberOfRetry) {
  23. precond.checkArgument(maxNumberOfRetry > 0,
  24. 'Expected a maximum number of retry greater than 0 but got %s.',
  25. maxNumberOfRetry);
  26. this.maxNumberOfRetry_ = maxNumberOfRetry;
  27. };
  28. // Starts a backoff operation. Accepts an optional parameter to let the
  29. // listeners know why the backoff operation was started.
  30. Backoff.prototype.backoff = function(err) {
  31. precond.checkState(this.timeoutID_ === -1, 'Backoff in progress.');
  32. if (this.backoffNumber_ === this.maxNumberOfRetry_) {
  33. this.emit('fail', err);
  34. this.reset();
  35. } else {
  36. this.backoffDelay_ = this.backoffStrategy_.next();
  37. this.timeoutID_ = setTimeout(this.handlers.backoff, this.backoffDelay_);
  38. this.emit('backoff', this.backoffNumber_, this.backoffDelay_, err);
  39. }
  40. };
  41. // Handles the backoff timeout completion.
  42. Backoff.prototype.onBackoff_ = function() {
  43. this.timeoutID_ = -1;
  44. this.emit('ready', this.backoffNumber_, this.backoffDelay_);
  45. this.backoffNumber_++;
  46. };
  47. // Stops any backoff operation and resets the backoff delay to its inital value.
  48. Backoff.prototype.reset = function() {
  49. this.backoffNumber_ = 0;
  50. this.backoffStrategy_.reset();
  51. clearTimeout(this.timeoutID_);
  52. this.timeoutID_ = -1;
  53. };
  54. module.exports = Backoff;