diff --git a/README.md b/README.md index 976f688..42aa641 100644 --- a/README.md +++ b/README.md @@ -103,11 +103,13 @@ main() ### retry.operation([options]) -Creates a new `RetryOperation` object. `options` is the same as `retry.timeouts()`'s `options`, with three additions: +Creates a new `RetryOperation` object. `options` accepts all of `retry.timeouts()`'s options. Setting `forever` to `true` also makes the operation keep retrying after those timeouts run out, waiting the last (largest) entry in the generated `timeouts` array before each further attempt. -* `forever`: Whether to retry forever, defaults to `false`. -* `unref`: Whether to [unref](https://nodejs.org/api/timers.html#timers_unref) the setTimeout's, defaults to `false`. -* `maxRetryTime`: The maximum time (in milliseconds) that the retried operation is allowed to run. Default is `Infinity`. +Three additional options apply to the operation: + +* `unref`: Whether to [unref](https://nodejs.org/api/timers.html#timers_unref) retry-delay timers and the operation-timeout timers of later attempts. When `unref` is enabled and `consistentOperationTimeouts` is `true`, the first attempt's operation-timeout timer is also unreferenced. Default is `false`. +* `maxRetryTime`: An elapsed-time threshold in milliseconds, measured from when `attempt()` was called. Retries do not reset this time budget. It is checked when `retry(error)` is called; once reached, that call returns `false` instead of scheduling another attempt. The check excludes the delay it schedules, so an already scheduled retry can start after `maxRetryTime`. It does not interrupt running work. Default is `Infinity`; `0` also means no limit. +* `consistentOperationTimeouts`: Set to `true` to pass the attempt number to the first attempt's operation-timeout callback, make the `unref` option also apply to that operation-timeout timer, and pass the last timeout value directly to `setTimeout` for forever delays scheduled after the `timeouts` array has been used up. By default, the first attempt's operation-timeout callback gets no arguments, the first attempt's operation-timeout timer remains referenced even with `unref: true`, and forever delays scheduled after the `timeouts` array has been used up are passed as arrays. With numeric timeouts, Node's built-in timers use the same forever-retry delays in both modes; timer wrappers can observe the argument-type change. Later attempts already pass their attempt number and honor `unref`. Combined with `unref: true`, the process may exit before the first attempt's operation-timeout callback runs if nothing else keeps the event loop alive. The forever delay change applies even without `timeoutOps` and is visible to timer wrappers such as fake timers. Only the value `true` enables this mode; default is `false`. ### retry.timeouts([options]) @@ -121,6 +123,7 @@ milliseconds. If `options` is an array, a copy of that array is returned. * `minTimeout`: The number of milliseconds before starting the first retry. Default is `1000`. * `maxTimeout`: The maximum number of milliseconds between two retries. Default is `Infinity`. * `randomize`: Randomizes the timeouts by multiplying with a factor between `1` to `2`. Default is `false`. +* `forever`: When `true`, adds the first computed timeout if `retries` would otherwise produce none (for example `0` or `null`). This timeout is based on `minTimeout` and subject to `randomize` and `maxTimeout`, giving a forever `RetryOperation` a delay to repeat. Default is `false`. The formula used to calculate the individual timeouts is: @@ -182,18 +185,21 @@ a timeout given in milliseconds. Available options: * `forever`: Whether to retry forever, defaults to `false`. -* `unref`: Wether to [unref](https://nodejs.org/api/timers.html#timers_unref) the setTimeout's, defaults to `false`. +* `unref`: Whether to [unref](https://nodejs.org/api/timers.html#timers_unref) retry-delay timers and the operation-timeout timers of later attempts. When `unref` is enabled and `consistentOperationTimeouts` is `true`, the first attempt's operation-timeout timer is also unreferenced. Default is `false`. +* `maxRetryTime`: An elapsed-time threshold in milliseconds, measured from when `attempt()` was called. Retries do not reset this time budget. It is checked when `retry(error)` is called; once reached, that call returns `false` instead of scheduling another attempt. The check excludes the delay it schedules, so an already scheduled retry can start after `maxRetryTime`. It does not interrupt running work. Default is `Infinity`; `0` also means no limit. +* `consistentOperationTimeouts`: The same opt-in behavior described under `retry.operation()`. Default is `false`. If `forever` is true, the following changes happen: -* `RetryOperation.errors()` will only output an array of one item: the last error. -* `RetryOperation` will repeatedly use the `timeouts` array. Once all of its timeouts have been used up, it restarts with the first timeout, then uses the second and so on. +* Each retry that reuses the last timeout trims the stored errors to the most recent error. A `retry(error)` call that reaches `maxRetryTime` or occurs after `stop()` skips this trimming. +* `RetryOperation` will keep retrying with the last element of the `timeouts` array once all of the `timeouts` have been used up. `maxRetryTime` and `stop()` still end the retries. #### retryOperation.errors() -Returns an array of all errors that have been passed to `retryOperation.retry()` so far. The -returning array has the errors ordered chronologically based on when they were passed to -`retryOperation.retry()`, which means the first passed error is at index zero and the last is -at the last index. +Returns an array of the errors currently stored by the operation. Errors passed to +`retryOperation.retry()` are ordered chronologically. In forever mode, each retry that +reuses the last timeout discards earlier errors. If `maxRetryTime` is reached, the final +error is appended and a `RetryOperation timeout occurred` error is prepended without +trimming existing errors. A `retry(error)` call after `stop()` also appends without trimming. #### retryOperation.mainError() @@ -208,10 +214,12 @@ If no errors occured so far, the value is `null`. #### retryOperation.attempt(fn, timeoutOps) Defines the function `fn` that is to be retried and executes it for the first -time right away. The `fn` function can receive an optional `currentAttempt` callback that represents the number of attempts to execute `fn` so far. +time right away. The `fn` function receives the current attempt number as its first argument, starting at `1`. + +Optionally defines `timeoutOps`, an object with a `timeout` in milliseconds and a callback function `cb`. +For each attempt, if `timeout` milliseconds elapse before `retry()` or `stop()` clears the timer, `cb` is called. By default, the first attempt's callback receives no arguments; callbacks on later attempts receive the current 1-based attempt number. With `consistentOperationTimeouts: true`, the first attempt's callback also receives its attempt number. Calling `cb` is only a notification: the library does not cancel the running work or start a retry on its own. -Optionally defines `timeoutOps` which is an object having a property `timeout` in miliseconds and a property `cb` callback function. -Whenever your retry operation takes longer than `timeout` to execute, the timeout callback function `cb` is called. +Call `retry()` at most once per attempt. To retry on timeout, call `retry(error)` from `cb` and ensure the timed-out work's completion handler cannot also call `retry()` or report a result, either by cancelling the work or by ignoring its late result. Ignoring the late result leaves the work running, so cancel it if attempts must not overlap. If the late handler can still call `retry()`, duplicate attempts can run or work can restart after success has been reported. If the `retry(error)` call in `cb` returns `false`, report the final failure from `cb`. #### retryOperation.try(fn) @@ -249,6 +257,11 @@ retry is licensed under the MIT license. # Changelog +Unreleased: + +* Add `consistentOperationTimeouts: true` to opt in to consistent timeout behavior: the first operation-timeout callback receives the attempt number, `unref: true` also applies to the first attempt's operation-timeout timer, and forever retries scheduled after the `timeouts` array has been used up pass the last timeout value directly to `setTimeout` instead of an array slice (a number instead of a one-element array for generated timeouts). Existing defaults are preserved. In the opt-in mode, an unreferenced first timeout can let the process exit before its callback runs if nothing else keeps the event loop alive. With numeric timeouts, Node's built-in timers use the same forever-retry delays in both modes. +* Document `retry.timeouts()`'s `forever` option and correct the description of forever retry delays: the last array element is reused, rather than cycling through the array. + 0.10.0 Adding `stop` functionality, thanks to @maxnachlinger. 0.9.0 Adding `unref` functionality, thanks to @satazor. diff --git a/lib/retry.js b/lib/retry.js index 5e85e79..639cc72 100644 --- a/lib/retry.js +++ b/lib/retry.js @@ -5,6 +5,7 @@ exports.operation = function(options) { return new RetryOperation(timeouts, { forever: options && (options.forever || options.retries === Infinity), unref: options && options.unref, + consistentOperationTimeouts: options && options.consistentOperationTimeouts, maxRetryTime: options && options.maxRetryTime }); }; diff --git a/lib/retry_operation.js b/lib/retry_operation.js index 105ce72..2e519f8 100644 --- a/lib/retry_operation.js +++ b/lib/retry_operation.js @@ -62,7 +62,11 @@ RetryOperation.prototype.retry = function(err) { if (this._cachedTimeouts) { // retry forever, only keep last error this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); + if (this._options.consistentOperationTimeouts === true) { + timeout = this._cachedTimeouts[this._cachedTimeouts.length - 1]; + } else { + timeout = this._cachedTimeouts.slice(-1); + } } else { return false; } @@ -107,8 +111,16 @@ RetryOperation.prototype.attempt = function(fn, timeoutOps) { var self = this; if (this._operationTimeoutCb) { this._timeout = setTimeout(function() { - self._operationTimeoutCb(); + if (self._options.consistentOperationTimeouts === true) { + self._operationTimeoutCb(self._attempts); + } else { + self._operationTimeoutCb(); + } }, self._operationTimeout); + + if (this._options.unref && this._options.consistentOperationTimeouts === true) { + this._timeout.unref(); + } } this._operationStart = new Date().getTime(); diff --git a/test/integration/test-forever-timeout.js b/test/integration/test-forever-timeout.js new file mode 100644 index 0000000..dfbbaad --- /dev/null +++ b/test/integration/test-forever-timeout.js @@ -0,0 +1,50 @@ +var common = require('../common'); +var assert = common.assert; +var retry = require(common.dir.lib + '/retry'); +var RetryOperation = require(common.dir.lib + '/retry_operation'); + +function checkDelays(operation, expectedDelays) { + var originalSetTimeout = global.setTimeout; + var originalClearTimeout = global.clearTimeout; + var timers = []; + var attempts = []; + global.setTimeout = function(callback, delay) { + var timer = {callback: callback, delay: delay}; + timers.push(timer); + return timer; + }; + global.clearTimeout = function() {}; + + try { + operation.attempt(function(attempt) { attempts.push(attempt); }); + for (var i = 0; i < 4; i++) { + assert.strictEqual(operation.retry(new Error('foo')), true); + timers[i].callback(); + } + operation.stop(); + } finally { + global.setTimeout = originalSetTimeout; + global.clearTimeout = originalClearTimeout; + } + + assert.deepStrictEqual(timers.map(function(timer) { return timer.delay; }), expectedDelays); + assert.deepStrictEqual(attempts, [1, 2, 3, 4, 5]); +} + +[undefined, false, 1, 'true', true].forEach(function(mode) { + var options = {forever: true}; + if (mode !== undefined) { + options.consistentOperationTimeouts = mode; + } + var expectedDelays = mode === true ? [1, 2, 2, 2] : [1, 2, [2], [2]]; + checkDelays(new RetryOperation([1, 2], options), expectedDelays); + + options.retries = 2; + options.minTimeout = 1; + options.factor = 2; + checkDelays(retry.operation(options), expectedDelays); +}); + +(function testLegacyBooleanForeverSignature() { + checkDelays(new RetryOperation([1, 2], true), [1, 2, [2], [2]]); +})(); diff --git a/test/integration/test-operation-timeout.js b/test/integration/test-operation-timeout.js new file mode 100644 index 0000000..a8f7468 --- /dev/null +++ b/test/integration/test-operation-timeout.js @@ -0,0 +1,104 @@ +var common = require('../common'); +var assert = common.assert; +var retry = require(common.dir.lib + '/retry'); +var RetryOperation = require(common.dir.lib + '/retry_operation'); +var execFileSync = require('child_process').execFileSync; + +function withTimers(fn) { + var originalSetTimeout = global.setTimeout; + var originalClearTimeout = global.clearTimeout; + var timers = []; + + global.setTimeout = function(callback, delay) { + var timer = { + callback: callback, + delay: delay, + unrefCalls: 0, + unref: function() { this.unrefCalls++; } + }; + timers.push(timer); + return timer; + }; + global.clearTimeout = function(timer) { timer.cleared = true; }; + + try { + fn(timers); + } finally { + global.setTimeout = originalSetTimeout; + global.clearTimeout = originalClearTimeout; + } +} + +var factories = [ + function(options) { return retry.operation(options); }, + function(options) { return new RetryOperation([1], options); } +]; + +factories.forEach(function(createOperation) { + [undefined, false, 1, 'true', true].forEach(function(mode) { + [false, true].forEach(function(unref) { + withTimers(function(timers) { + var options = {retries: 1, minTimeout: 1, unref: unref}; + if (mode !== undefined) { + options.consistentOperationTimeouts = mode; + } + var operation = createOperation(options); + var attempts = []; + var timeoutArguments = []; + var timeoutReceivers = []; + var retryResults = []; + + operation.attempt(function(attempt) { + attempts.push(attempt); + }, { + timeout: 10, + cb: function() { + timeoutArguments.push(Array.prototype.slice.call(arguments)); + timeoutReceivers.push(this); + retryResults.push(operation.retry(new Error('timeout'))); + } + }); + + assert.strictEqual(timers[0].delay, 10); + timers[0].callback(); + assert.strictEqual(timers[0].cleared, true); + assert.strictEqual(timers[1].delay, 1); + timers[1].callback(); + assert.strictEqual(timers[2].delay, 10); + timers[2].callback(); + + assert.deepStrictEqual(attempts, [1, 2]); + assert.deepStrictEqual(timeoutArguments, mode === true ? [[1], [2]] : [[], [2]]); + assert.deepStrictEqual(timeoutReceivers, [operation, operation]); + assert.deepStrictEqual(retryResults, [true, false]); + assert.strictEqual(timers.length, 3); + assert.deepStrictEqual(timers.map(function(timer) { + return timer.unrefCalls; + }), unref ? [mode === true ? 1 : 0, 1, 1] : [0, 0, 0]); + }); + }); + }); +}); + +(function testFirstTimeoutProcessLifetime() { + [undefined, false, 1, 'true', true].forEach(function(mode) { + [false, true].forEach(function(unref) { + var options = {unref: unref}; + if (mode !== undefined) { + options.consistentOperationTimeouts = mode; + } + [false, true].forEach(function(directConstructor) { + var createOperation = directConstructor ? + 'new (require(' + JSON.stringify(common.dir.lib + '/retry_operation') + '))([1], ' + JSON.stringify(options) + ')' : + 'require(' + JSON.stringify(common.dir.lib + '/retry') + ').operation(' + JSON.stringify(options) + ')'; + var script = createOperation + '.attempt(function() {}, {' + + 'timeout: 20, cb: function() { console.log("timeout"); }});'; + var output = execFileSync(process.execPath, ['-e', script], { + encoding: 'utf8', + timeout: 5000 + }); + assert.strictEqual(output, mode === true && unref ? '' : 'timeout\n'); + }); + }); + }); +})();