diff --git a/.mocharc.js b/.mocharc.js new file mode 100644 index 0000000..b1e2bd6 --- /dev/null +++ b/.mocharc.js @@ -0,0 +1 @@ +process.env.NODE_ENV = 'test' diff --git a/lib/agent.js b/lib/agent.js index b63cb0f..7d6d361 100644 --- a/lib/agent.js +++ b/lib/agent.js @@ -1,5 +1,6 @@ const { IntervalJitter } = require('./IntervalJitter') const { existsSync } = require('fs') +const { randomInt } = require('crypto') const fs = require('fs/promises') const path = require('path') const httpClient = require('./http') @@ -8,6 +9,7 @@ const Launcher = require('./launcher.js') const { info, warn, debug } = require('./logging/log') const utils = require('./utils.js') const { States, isTargetState, isValidState } = require('./states') +const MQTT_CONNECT_DELAY_MAX = process.env.NODE_ENV === 'test' ? 25 : 5000 const PROJECT_FILE = 'flowforge-project.json' @@ -135,6 +137,8 @@ class Agent { } // We have been provided a broker URL to use this.mqttClient = mqttClient.newMQTTClient(this, this.config) + // Wait a short random delay to reduce stress on broker when large numbers of devices come on-line + await new Promise(_resolve => setTimeout(_resolve, randomInt(20, MQTT_CONNECT_DELAY_MAX))) this.mqttClient.start() this.mqttClient.setApplication(this.currentApplication) this.mqttClient.setProject(this.currentProject) diff --git a/lib/mqtt.js b/lib/mqtt.js index 22151dd..540ad28 100644 --- a/lib/mqtt.js +++ b/lib/mqtt.js @@ -4,6 +4,7 @@ const { IntervalJitter } = require('./IntervalJitter') const url = require('url') const EditorTunnel = require('./editor/tunnel') const { getWSProxyAgent } = require('./utils') +const { randomInt } = require('crypto') class MQTTClient { /** @@ -42,7 +43,7 @@ class MQTTClient { clientId: config.brokerUsername, username: config.brokerUsername, password: config.brokerPassword, - reconnectPeriod: 15000, + reconnectPeriod: randomInt(13000, 25000), queueQoSZero: false } setMQTT(this)