mirror of
https://github.com/gadgethd/ukmesh.git
synced 2026-12-06 03:14:09 +00:00
60 lines
2.4 KiB
JavaScript
60 lines
2.4 KiB
JavaScript
// The probe runs in the restored broker's isolated network namespace.
|
|
const { randomUUID } = require("node:crypto");
|
|
const fs = require("node:fs");
|
|
const mqtt = require("mqtt");
|
|
|
|
function listenerUrls(config) {
|
|
const listeners = [];
|
|
for (const line of config.split(/\r?\n/)) {
|
|
const [key, value] = line.trim().split(/\s+/);
|
|
if (key === "listener") listeners.push({ port: Number(value), protocol: "mqtt" });
|
|
if (key === "protocol" && listeners.length) listeners.at(-1).protocol = value;
|
|
}
|
|
if (!listeners.length) listeners.push({ port: 1883, protocol: "mqtt" });
|
|
return listeners.map(({ port, protocol }) => {
|
|
if (!Number.isInteger(port) || port < 1 || port > 65535 ||
|
|
!["mqtt", "websockets"].includes(protocol)) throw Error("Unsupported restored MQTT listener");
|
|
return (protocol === "websockets" ? "ws" : "mqtt") + "://127.0.0.1:" + port;
|
|
});
|
|
}
|
|
|
|
async function probe(url, username, password) {
|
|
const nonce = randomUUID();
|
|
const topic = "restore-drill/" + username;
|
|
const client = mqtt.connect(url, { username, password, protocolVersion: 5,
|
|
reconnectPeriod: 0, connectTimeout: 5000, manualConnect: true });
|
|
try {
|
|
await new Promise((resolve, reject) => {
|
|
const timeout = setTimeout(() => reject(Error("MQTT round trip timed out")), 10000);
|
|
client.once("error", reject);
|
|
client.once("connect", async () => {
|
|
try {
|
|
const [grant] = await client.subscribeAsync(topic, { qos: 1 });
|
|
if (grant?.qos !== 1) throw Error("MQTT subscription refused");
|
|
const receipt = new Promise(done => client.on("message", (receivedTopic, message) => {
|
|
if (receivedTopic === topic && message.toString() === nonce) done();
|
|
}));
|
|
await Promise.all([client.publishAsync(topic, nonce, { qos: 1 }), receipt]);
|
|
resolve();
|
|
} catch (error) {
|
|
reject(error);
|
|
}
|
|
});
|
|
client.once("end", () => clearTimeout(timeout));
|
|
client.connect();
|
|
});
|
|
} finally {
|
|
await client.endAsync(true);
|
|
}
|
|
}
|
|
|
|
if (require.main === module) {
|
|
const config = fs.readFileSync(0, "utf8");
|
|
Promise.all(listenerUrls(config).map(url => probe(url, process.env.DRILL_USERNAME, process.env.DRILL_PASSWORD)))
|
|
.catch(() => {
|
|
console.error("MQTT round trip failed on a restored listener");
|
|
process.exitCode = 1;
|
|
});
|
|
}
|
|
module.exports = { listenerUrls, probe };
|