How to use backoff - 10 common examples

To help you get started, we’ve selected a few backoff examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github layr-team / Layr / audit / client / node.js View on Github external
serverConnection.on('data', (data) => {
    let receivedData = JSON.parse(data);

    if (receivedData.messageType === "CLI_UPLOAD_FILE") {
      let filePath = receivedData.filePath;

      batnode3.uploadFile(filePath);
    } else if (receivedData.messageType === "CLI_DOWNLOAD_FILE") {
      let filePath = receivedData.filePath;

      batnode3.retrieveFile(filePath);
    } else if (receivedData.messageType === "CLI_AUDIT_FILE") {
      let filePath = receivedData.filePath;
      let fibonacciBackoff = backoff.exponential({
          randomisationFactor: 0,
          initialDelay: 20,
          maxDelay: 2000
      });
      console.log("received path: ", filePath);
      batnode3.auditFile(filePath);

      // post audit cleanup
      serverConnection.on('close', () => {
        batnode3._audit.ready = false;
        batnode3._audit.data = null;
        batnode3._audit.passed = false;
      });

      fibonacciBackoff.failAfter(10);
github mtth / avsc / packages / services / lib / channel.js View on Github external
constructor(provider, opts) {
    super();
    opts = opts || {};
    const refreshBackoff = opts.refreshBackoff || backoff.fibonacci();

    this._channelProvider = provider;
    this._activeChannel = null; // Activated below.
    this._refreshAttempts = 0;
    this._refreshBackoff = refreshBackoff
      .on('backoff', (num, delay) => {
        d('Scheduling refresh in %sms.', delay);
        this._refreshAttempts++;
      })
      .on('ready', () => {
        d('Starting refresh attempt #%s...', this._refreshAttempts);
        this._refreshChannel();
      })
      .on('fail', () => {
        d('Exhausted refresh attempts, giving up.');
        this.emit('error', new Error('exhausted refresh attempts'));
github frandallfarmer / neohabitat / db / populateModels.js View on Github external
fs.readFile(objectPath, 'utf8', function (err, data) {
          if (err) {
            console.error('Could not read file:', objectPath);
            return console.error(err);
          }
          var templatedJSON = '';
          try {
            // Templates and attempts to parse the object's JSON.
            templatedJSON = templateHabitatObject(data);
            var habitatObject = JSON.parse(templatedJSON);

            // Figures out how we're going to write the object to Mongo.
            var updateWithRetries = null;
            if (habitatObject instanceof Array) {
              updateWithRetries = backoff.call(
                eupdateArray, db, habitatObject, habitatObjectUpdateFinished);
            } else {
              updateWithRetries = backoff.call(
                eupdateOne, db, habitatObject, habitatObjectUpdateFinished);
            }

            // Sets retry parameters.
            updateWithRetries.retryIf(function(err) { return err != null; });
            updateWithRetries.setStrategy(new backoff.ExponentialStrategy());
            updateWithRetries.failAfter(10);

            // Starts the Habitat object update process.
            updatesInFlight++;
            updateWithRetries.start();
          } catch (e) {
            console.error('Failed to parse file:', objectPath);
github node-opcua / node-opcua / packages / node-opcua-secure-channel / source / client / client_secure_channel_layer.ts View on Github external
this.__call.on("backoff", onBackoffFunc);

        this.__call.on("abort", () => {
            debugLog(chalk.bgWhite.cyan(` abort #   after ${this.__call.getNumRetries()} retries.`));
            // Do something when backoff starts, e.g. show to the
            // user the delay before next reconnection attempt.
            /**
             * @event backoff
             */
            this.emit("abort");
            setImmediate(() => {
                this._backoff_completion(undefined, new Error("Connection abandoned"), transport, callback);
            });
        });

        this.__call.setStrategy(new backoff.ExponentialStrategy(this.connectionStrategy));
        this.__call.start();
    }
github node-opcua / node-opcua / packages / node-opcua-secure-channel / src / client / client_secure_channel_layer.js View on Github external
self.__call.on("abort", function () {
            debugLog(" abort #".bgWhite.cyan, " after ", self.__call.getNumRetries(), " retries");
            // Do something when backoff starts, e.g. show to the
            // user the delay before next reconnection attempt.
            /**
             * @event backoff
             */
            self.emit("abort");

            setImmediate(function () {
                _backoff_completion(null, new Error("Connection abandoned"));
            });

        });

        self.__call.setStrategy(new backoff.ExponentialStrategy(self.connectionStrategy));
        self.__call.start();

    };
github frandallfarmer / neohabitat / db / populateModels.js View on Github external
templatedJSON = templateHabitatObject(data);
            var habitatObject = JSON.parse(templatedJSON);

            // Figures out how we're going to write the object to Mongo.
            var updateWithRetries = null;
            if (habitatObject instanceof Array) {
              updateWithRetries = backoff.call(
                eupdateArray, db, habitatObject, habitatObjectUpdateFinished);
            } else {
              updateWithRetries = backoff.call(
                eupdateOne, db, habitatObject, habitatObjectUpdateFinished);
            }

            // Sets retry parameters.
            updateWithRetries.retryIf(function(err) { return err != null; });
            updateWithRetries.setStrategy(new backoff.ExponentialStrategy());
            updateWithRetries.failAfter(10);

            // Starts the Habitat object update process.
            updatesInFlight++;
            updateWithRetries.start();
          } catch (e) {
            console.error('Failed to parse file:', objectPath);
            console.error(templatedJSON);
            return console.error(e);
          }
        });
      }
github grover / homebridge-dacp / src / DacpAccessory.js View on Github external
this.api = api;
    Characteristic = this.api.hap.Characteristic;
    Service = this.api.hap.Service;

    this.log = log;
    this.name = config.name;
    this.serviceName = config.serviceName;

    this.config = config;

    this._isAnnounced = false;
    this._isReachable = false;
    this._playStatusUpdateListeners = [];

    // Maximum backoff is 15mins when a device/program is visible
    this._backoff = backoff.exponential({
      initialDelay: 100,
      maxDelay: 900000
    }).on('backoff', (number, delay) => this._onBackoffStarted(delay))
      .on('ready', () => this._connectToDacpDevice());

    this._dacpClient = new DacpClient(log)
      .on('failed', e => this._onDacpFailure(e));

    this._services = this.createServices(this.api.hap);
  }
github node-opcua / node-opcua / packages / node-opcua-secure-channel / source / client / client_secure_channel_layer.ts View on Github external
this.lastError = undefined;

        if (this.connectionStrategy.maxRetry === 0) {
            debugLog(chalk.cyan("max Retry === 0 =>  No backoff required -> call the _connect function directly"));
            this.__call = 0;
            return this._connect(transport, endpointUrl, callback);
        }

        const connectFunc = (callback2: ErrorCallback) => {
            return this._connect(transport, endpointUrl, callback2);
        };
        const completionFunc = (err?: Error) => {
            return this._backoff_completion(err, this.lastError, transport, callback);
        };

        this.__call = backoff.call(connectFunc, completionFunc);

        if (this.connectionStrategy.maxRetry >= 0) {
            const maxRetry = Math.max(this.connectionStrategy.maxRetry, 1);
            debugLog(chalk.cyan("backoff will failed after "), maxRetry);
            this.__call.failAfter(maxRetry);
        } else {
            // retry will be infinite
            debugLog(chalk.cyan("backoff => starting a infinite retry"));
        }

        const onBackoffFunc = (retryCount: number, delay: number) => {
            debugLog(chalk.bgWhite.cyan(" Backoff #"), retryCount, "delay = ", delay,
                " ms", " maxRetry ", this.connectionStrategy.maxRetry);
            // Do something when backoff starts, e.g. show to the
            // user the delay before next reconnection attempt.
            /**
github node-opcua / node-opcua / packages / node-opcua-secure-channel / src / client / client_secure_channel_layer.js View on Github external
if (self.__call) {
                // console log =
                transport.numberOfRetry = transport.numberOfRetry || 0;
                transport.numberOfRetry += self.__call.getNumRetries();
                self.__call.removeAllListeners();
                self.__call = null;

                if (err) {
                    callback(last_err|| err);
                } else {
                    callback();
                }
            }
        }

        self.__call = backoff.call(_connect, _backoff_completion);

        if ( self.connectionStrategy.maxRetry >= 0){
            const maxRetry = Math.max(self.connectionStrategy.maxRetry, 1);
            self.__call.failAfter(maxRetry);
            debugLog("backoff will failed after ".cyan, maxRetry);
        } else {
            // retry will be infinite
            debugLog("backoff => starting a infinite retry".cyan, self.connectionStrategy.initialDelay);
        }


        self.__call.on("backoff", function (number, delay) {

            debugLog(" Backoff #".bgWhite.cyan, number, "delay = ", delay, self.connectionStrategy.maxRetry);
            // Do something when backoff starts, e.g. show to the
            // user the delay before next reconnection attempt.
github mcavage / node-fast / lib / client.js View on Github external
Client.prototype.connect = function connect() {
    if (this._fast_retry)
        throw new Error('already connecting');

    var self = this;
    this.closed = false;
    var max = Infinity;
    var opts = this._options;
    var retry = backoff.call(this._createSocket.bind(this), {},
    function (err, conn) {
        // Starting with backoff 2.5.0, the backoff callback is called when the
        // backoff instance is aborted. In this case, the _onConnection callback
        // should not be called, since its purpose is to handle the result of
        // the bind call that is being backed off, not events in the backoff
        // process itself.
        if (!retry.isAborted()) {
            self._onConnection(err, conn);
        }
    });

    retry.on('backoff', this.emit.bind(this, 'connectAttempt'));
    retry.setStrategy(new backoff.ExponentialStrategy({
        initialDelay: opts.retry.minTimeout || 1000,
        maxDelay: opts.retry.maxTimeout || Infinity
    }));

backoff

Fibonacci and exponential backoffs.

MIT
Latest version published 9 years ago

Package Health Score

65 / 100
Full package analysis