Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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);
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'));
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);
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();
}
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();
};
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);
}
});
}
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);
}
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.
/**
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.
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
}));