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.

README.md 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # Backoff for Node.js
  2. [![Build Status](https://secure.travis-ci.org/MathieuTurcotte/node-backoff.png?branch=master)](http://travis-ci.org/MathieuTurcotte/node-backoff)
  3. [![NPM version](https://badge.fury.io/js/backoff.png)](http://badge.fury.io/js/backoff)
  4. Fibonacci and exponential backoffs for Node.js.
  5. ## Installation
  6. ```
  7. npm install backoff
  8. ```
  9. ## Unit tests
  10. ```
  11. npm test
  12. ```
  13. ## Usage
  14. ### Object Oriented
  15. The usual way to instantiate a new `Backoff` object is to use one predefined
  16. factory method: `backoff.fibonacci([options])`, `backoff.exponential([options])`.
  17. `Backoff` inherits from `EventEmitter`. When a backoff starts, a `backoff`
  18. event is emitted and, when a backoff ends, a `ready` event is emitted.
  19. Handlers for these two events are called with the current backoff number and
  20. delay.
  21. ``` js
  22. var backoff = require('backoff');
  23. var fibonacciBackoff = backoff.fibonacci({
  24. randomisationFactor: 0,
  25. initialDelay: 10,
  26. maxDelay: 300
  27. });
  28. fibonacciBackoff.failAfter(10);
  29. fibonacciBackoff.on('backoff', function(number, delay) {
  30. // Do something when backoff starts, e.g. show to the
  31. // user the delay before next reconnection attempt.
  32. console.log(number + ' ' + delay + 'ms');
  33. });
  34. fibonacciBackoff.on('ready', function(number, delay) {
  35. // Do something when backoff ends, e.g. retry a failed
  36. // operation (DNS lookup, API call, etc.). If it fails
  37. // again then backoff, otherwise reset the backoff
  38. // instance.
  39. fibonacciBackoff.backoff();
  40. });
  41. fibonacciBackoff.on('fail', function() {
  42. // Do something when the maximum number of backoffs is
  43. // reached, e.g. ask the user to check its connection.
  44. console.log('fail');
  45. });
  46. fibonacciBackoff.backoff();
  47. ```
  48. The previous example would print the following.
  49. ```
  50. 0 10ms
  51. 1 10ms
  52. 2 20ms
  53. 3 30ms
  54. 4 50ms
  55. 5 80ms
  56. 6 130ms
  57. 7 210ms
  58. 8 300ms
  59. 9 300ms
  60. fail
  61. ```
  62. Note that `Backoff` objects are meant to be instantiated once and reused
  63. several times by calling `reset` after a successful "retry".
  64. ### Functional
  65. It's also possible to avoid some boilerplate code when invoking an asynchronous
  66. function in a backoff loop by using `backoff.call(fn, [args, ...], callback)`.
  67. Typical usage looks like the following.
  68. ``` js
  69. var call = backoff.call(get, 'https://duplika.ca/', function(err, res) {
  70. console.log('Num retries: ' + call.getNumRetries());
  71. if (err) {
  72. console.log('Error: ' + err.message);
  73. } else {
  74. console.log('Status: ' + res.statusCode);
  75. }
  76. });
  77. call.retryIf(function(err) { return err.status == 503; });
  78. call.setStrategy(new backoff.ExponentialStrategy());
  79. call.failAfter(10);
  80. call.start();
  81. ```
  82. ## API
  83. ### backoff.fibonacci([options])
  84. Constructs a Fibonacci backoff (10, 10, 20, 30, 50, etc.).
  85. The options are the following.
  86. - randomisationFactor: defaults to 0, must be between 0 and 1
  87. - initialDelay: defaults to 100 ms
  88. - maxDelay: defaults to 10000 ms
  89. With these values, the backoff delay will increase from 100 ms to 10000 ms. The
  90. randomisation factor controls the range of randomness and must be between 0
  91. and 1. By default, no randomisation is applied on the backoff delay.
  92. ### backoff.exponential([options])
  93. Constructs an exponential backoff (10, 20, 40, 80, etc.).
  94. The options are the following.
  95. - randomisationFactor: defaults to 0, must be between 0 and 1
  96. - initialDelay: defaults to 100 ms
  97. - maxDelay: defaults to 10000 ms
  98. - factor: defaults to 2, must be greater than 1
  99. With these values, the backoff delay will increase from 100 ms to 10000 ms. The
  100. randomisation factor controls the range of randomness and must be between 0
  101. and 1. By default, no randomisation is applied on the backoff delay.
  102. ### backoff.call(fn, [args, ...], callback)
  103. - fn: function to call in a backoff handler, i.e. the wrapped function
  104. - args: function's arguments
  105. - callback: function's callback accepting an error as its first argument
  106. Constructs a `FunctionCall` instance for the given function. The wrapped
  107. function will get retried until it succeds or reaches the maximum number
  108. of backoffs. In both cases, the callback function will be invoked with the
  109. last result returned by the wrapped function.
  110. It is the caller's responsability to initiate the call by invoking the
  111. `start` method on the returned `FunctionCall` instance.
  112. ### Class Backoff
  113. #### new Backoff(strategy)
  114. - strategy: the backoff strategy to use
  115. Constructs a new backoff object from a specific backoff strategy. The backoff
  116. strategy must implement the `BackoffStrategy`interface defined bellow.
  117. #### backoff.failAfter(numberOfBackoffs)
  118. - numberOfBackoffs: maximum number of backoffs before the fail event gets
  119. emitted, must be greater than 0
  120. Sets a limit on the maximum number of backoffs that can be performed before
  121. a fail event gets emitted and the backoff instance is reset. By default, there
  122. is no limit on the number of backoffs that can be performed.
  123. #### backoff.backoff([err])
  124. Starts a backoff operation. If provided, the error parameter will be emitted
  125. as the last argument of the `backoff` and `fail` events to let the listeners
  126. know why the backoff operation was attempted.
  127. An error will be thrown if a backoff operation is already in progress.
  128. In practice, this method should be called after a failed attempt to perform a
  129. sensitive operation (connecting to a database, downloading a resource over the
  130. network, etc.).
  131. #### backoff.reset()
  132. Resets the backoff delay to the initial backoff delay and stop any backoff
  133. operation in progress. After reset, a backoff instance can and should be
  134. reused.
  135. In practice, this method should be called after having successfully completed
  136. the sensitive operation guarded by the backoff instance or if the client code
  137. request to stop any reconnection attempt.
  138. #### Event: 'backoff'
  139. - number: number of backoffs since last reset, starting at 0
  140. - delay: backoff delay in milliseconds
  141. - err: optional error parameter passed to `backoff.backoff([err])`
  142. Emitted when a backoff operation is started. Signals to the client how long
  143. the next backoff delay will be.
  144. #### Event: 'ready'
  145. - number: number of backoffs since last reset, starting at 0
  146. - delay: backoff delay in milliseconds
  147. Emitted when a backoff operation is done. Signals that the failing operation
  148. should be retried.
  149. #### Event: 'fail'
  150. - err: optional error parameter passed to `backoff.backoff([err])`
  151. Emitted when the maximum number of backoffs is reached. This event will only
  152. be emitted if the client has set a limit on the number of backoffs by calling
  153. `backoff.failAfter(numberOfBackoffs)`. The backoff instance is automatically
  154. reset after this event is emitted.
  155. ### Interface BackoffStrategy
  156. A backoff strategy must provide the following methods.
  157. #### strategy.next()
  158. Computes and returns the next backoff delay.
  159. #### strategy.reset()
  160. Resets the backoff delay to its initial value.
  161. ### Class ExponentialStrategy
  162. Exponential (10, 20, 40, 80, etc.) backoff strategy implementation.
  163. #### new ExponentialStrategy([options])
  164. The options are the following.
  165. - randomisationFactor: defaults to 0, must be between 0 and 1
  166. - initialDelay: defaults to 100 ms
  167. - maxDelay: defaults to 10000 ms
  168. - factor: defaults to 2, must be greater than 1
  169. ### Class FibonacciStrategy
  170. Fibonnaci (10, 10, 20, 30, 50, etc.) backoff strategy implementation.
  171. #### new FibonacciStrategy([options])
  172. The options are the following.
  173. - randomisationFactor: defaults to 0, must be between 0 and 1
  174. - initialDelay: defaults to 100 ms
  175. - maxDelay: defaults to 10000 ms
  176. ### Class FunctionCall
  177. This class manages the calling of an asynchronous function within a backoff
  178. loop.
  179. This class should rarely be instantiated directly since the factory method
  180. `backoff.call(fn, [args, ...], callback)` offers a more convenient and safer
  181. way to create `FunctionCall` instances.
  182. #### new FunctionCall(fn, args, callback)
  183. - fn: asynchronous function to call
  184. - args: an array containing fn's args
  185. - callback: fn's callback
  186. Constructs a function handler for the given asynchronous function.
  187. #### call.isPending()
  188. Returns whether the call is pending, i.e. hasn't been started.
  189. #### call.isRunning()
  190. Returns whether the call is in progress.
  191. #### call.isCompleted()
  192. Returns whether the call is completed.
  193. #### call.isAborted()
  194. Returns whether the call is aborted.
  195. #### call.setStrategy(strategy)
  196. - strategy: strategy instance to use, defaults to `FibonacciStrategy`.
  197. Sets the backoff strategy to use. This method should be called before
  198. `call.start()` otherwise an exception will be thrown.
  199. #### call.failAfter(maxNumberOfBackoffs)
  200. - maxNumberOfBackoffs: maximum number of backoffs before the call is aborted
  201. Sets the maximum number of backoffs before the call is aborted. By default,
  202. there is no limit on the number of backoffs that can be performed.
  203. This method should be called before `call.start()` otherwise an exception will
  204. be thrown..
  205. #### call.retryIf(predicate)
  206. - predicate: a function which takes in as its argument the error returned
  207. by the wrapped function and determines whether it is retriable.
  208. Sets the predicate which will be invoked to determine whether a given error
  209. should be retried or not, e.g. a network error would be retriable while a type
  210. error would stop the function call. By default, all errors are considered to be
  211. retriable.
  212. This method should be called before `call.start()` otherwise an exception will
  213. be thrown.
  214. #### call.getLastResult()
  215. Returns an array containing the last arguments passed to the completion callback
  216. of the wrapped function. For example, to get the error code returned by the last
  217. call, one would do the following.
  218. ``` js
  219. var results = call.getLastResult();
  220. // The error code is the first parameter of the callback.
  221. var error = results[0];
  222. ```
  223. Note that if the call was aborted, it will contain the abort error and not the
  224. last error returned by the wrapped function.
  225. #### call.getNumRetries()
  226. Returns the number of times the wrapped function call was retried. For a
  227. wrapped function that succeeded immediately, this would return 0. This
  228. method can be called at any point in time during the call life cycle, i.e.
  229. before, during and after the wrapped function invocation.
  230. #### call.start()
  231. Initiates the call the wrapped function. This method should only be called
  232. once otherwise an exception will be thrown.
  233. #### call.abort()
  234. Aborts the call and causes the completion callback to be invoked with an abort
  235. error if the call was pending or running; does nothing otherwise. This method
  236. can safely be called mutliple times.
  237. #### Event: 'call'
  238. - args: wrapped function's arguments
  239. Emitted each time the wrapped function is called.
  240. #### Event: 'callback'
  241. - results: wrapped function's return values
  242. Emitted each time the wrapped function invokes its callback.
  243. #### Event: 'backoff'
  244. - number: backoff number, starts at 0
  245. - delay: backoff delay in milliseconds
  246. - err: the error that triggered the backoff operation
  247. Emitted each time a backoff operation is started.
  248. #### Event: 'abort'
  249. Emitted when a call is aborted.
  250. ## Annotated source code
  251. The annotated source code can be found at [mathieuturcotte.github.io/node-backoff/docs](http://mathieuturcotte.github.io/node-backoff/docs/).
  252. ## License
  253. This code is free to use under the terms of the [MIT license](http://mturcotte.mit-license.org/).