fix: MQTT connection wedged after one drop, leaving all receptions pending (v1.3.2)

Field report: CoreScope showed disconnected and every reception stayed pending,
starting with today's v1.3.x update. Broker is healthy (auth/ACL/listener all OK),
so the regression is client-side.

Root cause: today's diff lowered MQTT keepalive 60→20 s, which exercises the
reconnect path far more often — and the pre-existing `client.once('error', reject)`
left NO error listener after the first error. mqtt.js is an EventEmitter, so a later
'error' (during a transient reconnect) throws unhandled and wedges the auto-reconnect
loop: the client never reconnects, drain never runs, the queue grows unbounded.

- Revert keepalive to the mqtt.js default (restores v1.2.0 connection behaviour).
- Attach a PERSISTENT 'error' listener; the initial-connect promise removes its own
  listeners once settled so a later error is always handled, never thrown.
- Log every broker transition (connect/reconnect/offline/close/error + reason) to the
  debug log — these were previously invisible, so the drop couldn't be diagnosed.
- "Push pending now" forces a reconnect when the link is down (manual recovery).
- Home upload dot turns red (not idle-grey) on a real disconnect.

SW cache v9→v10.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
efitenandClaude Opus 4.8 committed 2026-06-20 18:57:52 +02:00
1 parent 15aa6a42d7
commit bccedfbb84
5 files changed
+73 -19

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "coredrive-rx",
"version": "1.3.1",
"version": "1.3.2",
"private": false,
"license": "GPL-3.0-or-later",
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
// Minimal service worker: makes the app installable and lets the shell load
// offline. Network-first (always fresh online), cache fallback (offline).
// Only the static app assets go through fetch; MQTT runs over WSS (not cached).
const CACHE = 'coredrive-rx-v9';
const CACHE = 'coredrive-rx-v10';
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (e) => e.waitUntil((async () => {
+27 -9
View File
@@ -203,7 +203,10 @@ async function renderStatusStrip() {
els('sPending').textContent = (await state.queue.count()) + ' pending';
els('sRate').textContent = state.rxTimes.length + ' pkt/min';
const dot = els('uDot');
const color = state.brokerState === 'connect' ? '#2ecc71' : state.brokerState === 'reconnect' ? '#e6a23c' : '#9aa4b2';
const color = !state.publisher ? '#9aa4b2'
: state.brokerState === 'connect' ? '#2ecc71'
: state.brokerState === 'reconnect' ? '#e6a23c'
: '#e74c3c'; // offline / close / error → red so a dead link is obvious, not idle-grey
dot.style.background = color;
els('sUpload').lastChild.textContent = state.lastUploadAt ? 'upload ' + agoText(state.lastUploadAt, now) : 'upload —';
}
@@ -233,10 +236,24 @@ function noteSnr(snr) {
// --- Settings renderers ---
function renderBroker() {
const m = { connect: 'connected', reconnect: 'reconnecting…', offline: 'offline', close: 'disconnected' };
const m = { connect: 'connected', reconnect: 'reconnecting…', offline: 'offline', close: 'disconnected', error: 'error' };
els('brokerStatus').textContent = state.publisher ? (m[state.brokerState] || state.brokerState) : '— not connected —';
}
// onBrokerStatus logs every MQTT lifecycle change to the debug log (previously invisible,
// so a field disconnect couldn't be diagnosed) and flushes the backlog on (re)connect.
function onBrokerStatus(s, arg) {
state.brokerState = s;
if (s === 'connect') dbg('CoreScope connected', 'ok');
else if (s === 'reconnect') dbg('CoreScope reconnecting…', 'st');
else if (s === 'offline') dbg('CoreScope offline (no network?)', 'no');
else if (s === 'close') dbg('CoreScope connection closed', 'no');
else if (s === 'error') dbg('CoreScope error: ' + ((arg && arg.message) || arg), 'no');
renderBroker();
renderStatusStrip();
if (s === 'connect') drain().then(refreshCounters).catch(() => {}); // flush backlog on (re)connect
}
function setButton() {
const b = els('btnConnect');
b.textContent = state.connected ? 'Disconnect' : 'Connect companion (BLE)';
@@ -339,11 +356,17 @@ async function drainLoop() {
}
}
// pushNow is the Settings button: force one drain attempt and report the outcome.
// pushNow is the Settings button: force a drain, or force a reconnect first if the link
// is down — so a stuck disconnected client with a full queue has a manual way to recover.
async function pushNow() {
const b = els('btnPush');
b.disabled = true;
try {
if (state.publisher && !state.publisher.connected()) {
dbg('CoreScope not connected — forcing reconnect…', 'st');
state.publisher.reconnect(); // drain fires automatically on the 'connect' event
return;
}
const n = await drain();
dbg(n ? 'pushed ' + n + ' record(s)' : 'nothing pending / not connected', n ? 'ok' : 'st');
} catch (e) {
@@ -405,12 +428,7 @@ async function connectAll() {
const cfg = getConfig();
if (cfg && cfg.mqttUrl) {
state.publisher = new Publisher({ url: cfg.mqttUrl, username: cfg.mqttUsername, password: cfg.mqttPassword, clientId: state.companionPubkey });
state.publisher.onStatus((s) => {
state.brokerState = s;
renderBroker();
renderStatusStrip();
if (s === 'connect') drain().then(refreshCounters).catch(() => {}); // flush backlog on (re)connect
});
state.publisher.onStatus(onBrokerStatus);
await state.publisher.connect();
state.brokerState = 'connect';
renderBroker();
+22 -8
View File
@@ -7,32 +7,46 @@ export class Publisher {
// opts: { url, username, password } — EMQX WSS endpoint + per-client creds.
constructor(opts) { this.opts = opts; this.client = null; this._onStatus = null; }
// onStatus(cb): cb(state) is called on connection lifecycle changes, where state is
// 'connect' | 'reconnect' | 'offline' | 'close'. Drives the Home upload indicator and
// a drain kick on reconnect. A network handoff (cellular→WiFi) silently kills the
// socket; a short keepalive makes MQTT.js notice and reconnect quickly.
// onStatus(cb): cb(state, arg) is called on connection lifecycle changes, where state
// is 'connect' | 'reconnect' | 'offline' | 'close' | 'error' (arg = Error for 'error').
// Drives the Home upload indicator, the debug log, and a drain kick on reconnect.
onStatus(cb) { this._onStatus = cb; }
_emit(ev, arg) { if (this._onStatus) this._onStatus(ev, arg); }
connect() {
this.client = mqtt.connect(this.opts.url, {
username: this.opts.username,
password: this.opts.password,
clientId: this.opts.clientId, // = companion pubkey; EMQX ACL can bind topics to ${clientid}
reconnectPeriod: 4000,
keepalive: 20, // detect a dead socket fast (default 60 s is too slow after a handoff)
clean: true,
});
for (const ev of ['connect', 'reconnect', 'offline', 'close']) {
this.client.on(ev, () => { if (this._onStatus) this._onStatus(ev); });
this.client.on(ev, () => this._emit(ev));
}
// PERSISTENT error listener. mqtt.js is an EventEmitter: an 'error' with no listener
// throws and can wedge the auto-reconnect loop — which left the client permanently
// disconnected (every reception stuck pending) after one transient drop. Always
// listen and surface the reason instead.
this.client.on('error', (e) => this._emit('error', e));
// Resolve/reject the INITIAL connect only. Listeners are removed once settled so the
// persistent 'error' handler above is the sole long-lived one afterwards.
return new Promise((resolve, reject) => {
this.client.once('connect', resolve);
this.client.once('error', reject);
const onConn = () => { cleanup(); resolve(); };
const onErr = (e) => { cleanup(); reject(e); };
const cleanup = () => { this.client.removeListener('connect', onConn); this.client.removeListener('error', onErr); };
this.client.on('connect', onConn);
this.client.on('error', onErr);
});
}
connected() { return !!(this.client && this.client.connected); }
// reconnect forces a fresh connection attempt — used by "Push pending now" when the
// client is disconnected, so the user isn't stuck with a dead link and a full queue.
reconnect() { try { if (this.client) this.client.reconnect(); } catch (e) {} }
end() { try { if (this.client) this.client.end(true); } catch (e) {} this.client = null; }
// buildPayload assembles one reception in the ingestor's expected shape.
+22
View File
@@ -25,3 +25,25 @@ test('publish rejects on a broker error', async () => {
p.client = { publish(_t, _pl, _o, cb) { cb(new Error('nope')); } };
await assert.rejects(p.publish('pk', rec, 'name', 1000), /nope/);
});
test('reconnect() asks the client to reconnect (manual recovery)', () => {
const p = new Publisher({ url: 'x' });
let called = false;
p.client = { reconnect() { called = true; } };
p.reconnect();
assert.strictEqual(called, true);
});
test('reconnect() is a no-op when there is no client', () => {
const p = new Publisher({ url: 'x' });
assert.doesNotThrow(() => p.reconnect());
});
test('onStatus receives the event and its arg (e.g. error reason)', () => {
const p = new Publisher({ url: 'x' });
const seen = [];
p.onStatus((ev, arg) => seen.push([ev, arg && arg.message]));
p._emit('reconnect');
p._emit('error', new Error('boom'));
assert.deepStrictEqual(seen, [['reconnect', undefined], ['error', 'boom']]);
});