Skip to content

Commit

Permalink
Merge pull request #306 from FlowFuse/latest-mqtt
Browse files Browse the repository at this point in the history
Upgrade to latest MQTT.js
  • Loading branch information
hardillb authored Sep 16, 2024
2 parents ff11231 + 0d5349b commit eba7e17
Show file tree
Hide file tree
Showing 4 changed files with 380 additions and 211 deletions.
21 changes: 8 additions & 13 deletions lib/mqtt.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const mqtt = require('mqtt')
const { info, warn, debug, setMQTT, getBufferedMessages } = require('./logging/log')
const { IntervalJitter } = require('./IntervalJitter')
const url = require('url')
const EditorTunnel = require('./editor/tunnel')
const { getWSProxyAgent } = require('./utils')
const { randomInt } = require('crypto')
Expand Down Expand Up @@ -50,24 +49,20 @@ class MQTTClient {
}

start () {
// PROBLEM: ipv6 ws addresses cannot connect
// INFO: Calling mqtt.connect('http://[::1]:8883') fails with error ERR_INVALID_URL
// INFO: Calling mqtt.connect(new URL('http://[::1]:8883')) fails because `connect` only accepts a `string` or `url.parse` object
// INFO: Calling mqtt.connect(url.parse('http://[::1]:8883') fails because unlike new URL, url.parse drops the square brackets off hostname
// (mqtt.js disassembles and reassembles the url using hostname + port so `ws://[::1]:8883` becomes `ws://::1:8883`)
// INFO: WS src code uses `new URL` so when `mqtt.js` passes the reassembled IP `http://::1:8883`, it fails with error ERR_INVALID_URL
// SEE: https://github.com/mqttjs/MQTT.js/issues/1569
// eslint-disable-next-line n/no-deprecated-api
const brokerURL = url.parse(this.config.brokerURL)
const _url = new URL(this.config.brokerURL)
brokerURL.hostname = _url.hostname
const brokerURL = new URL(this.config.brokerURL)

if (process.env.all_proxy || process.env.http_proxy || process.env.https_proxy) {
this.brokerConfig.wsOptions = {
agent: getWSProxyAgent(this.config.brokerURL)
}
}
this.client = mqtt.connect(brokerURL, this.brokerConfig)
const connectOpts = {
protocol: brokerURL.protocol.replace(/:$/, ''),
host: brokerURL.hostname,
port: brokerURL.port
}
const opts = Object.assign({}, connectOpts, this.brokerConfig)
this.client = mqtt.connect(opts)

this.client.on('connect', () => {
info('MQTT connected')
Expand Down
Loading

0 comments on commit eba7e17

Please sign in to comment.