mirror of
https://github.com/efiten/coredrive-rx.git
synced 2026-12-03 01:37:57 +00:00
fix: the queue could never commit progress on a link that keeps dropping
A field log showed 59 records buffered and not one published, with ~18 "Keepalive timeout" errors against a single successful CONNACK. Probing the broker from a fixed line ruled out the obvious causes: publishes to /packets, /rf and /regions were all PUBACKed in ~85ms with returnCode=0 and no disconnect, and a deliberate same-clientId takeover makes the victim report a bare 'close', never a keepalive error. So neither the ACL nor session contention was involved. What was: two defects that together made a flaky mobile link unrecoverable and undiagnosable. 1. drain() discarded its own progress. It collected published ids and called queue.remove ONCE after the loop, so a single rejecting publish threw and every record the broker had already acknowledged stayed queued to be sent again. Publishes are sequential, so a 59-record backlog needs ~5s of continuous link at 86ms round-trip and ~18s at 300ms - on a link that stayed up about a second at a time, the design could never commit anything at all. The loop now lives in src/drain.js with two invariants under test: a record is removed if and only if the broker acked it, and one unpublishable record can never block the records behind it. A link drop is charged to the link, not to the record, so repeated drops cannot quarantine a good reception. 2. Every Publisher ever created reported into one module-level handler writing one global brokerState, so an orphaned client's endless 4s reconnect loop overwrote a healthy connection's state and filled the log with failures nothing could attribute. Each Publisher now carries an id; events from a retired one are named once and then ignored. startPublisher no longer ADOPTS a disconnected publisher (which made connectAll print "CoreScope connected" over a looping client) - it retires it, which also stops that loop. Also: keepalive is now set explicitly and quoted in the log next to the CONNACK return code. mqtt.js arms its keepalive manager only inside _onConnect and only if one does not already exist (client.js:1101), never re-arming an existing one, so a surviving manager can report a bogus timeout on a healthy link. That error is now evidence instead of a red herring. Tests: 234 pass (+14). SW cache v36 -> v37. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
75e1145fae
commit
0dee3bd1e1
7 files changed
+369
-24
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "coredrive-rx",
|
||||
"version": "1.11.0",
|
||||
"version": "1.11.1",
|
||||
"private": false,
|
||||
"license": "GPL-3.0-or-later",
|
||||
"type": "module",
|
||||
|
||||
+1
-1
@@ -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-v36';
|
||||
const CACHE = 'coredrive-rx-v37';
|
||||
|
||||
// config.json is deliberately NEVER cached, in either direction. It is
|
||||
// per-deployment runtime config, and a stale copy is worse than none: flags added
|
||||
|
||||
+50
-14
@@ -25,7 +25,8 @@ import {
|
||||
import { shareLog } from './sharelog.js';
|
||||
import { Gps } from './gps.js';
|
||||
import { Queue } from './queue.js';
|
||||
import { Publisher } from './publisher.js';
|
||||
import { Publisher, KEEPALIVE_SECS } from './publisher.js';
|
||||
import { drainOnce } from './drain.js';
|
||||
import { loadConfig, getConfig, featureEnabled } from './config.js';
|
||||
import { buildRfLogRecord } from './capture.js';
|
||||
import { buildStatsRequest, parseStats, mergeSample, nextSampleDelay, STATS_CORE, STATS_RADIO, STATS_PACKETS } from './rfstats.js';
|
||||
@@ -53,6 +54,11 @@ const state = {
|
||||
// dbg line rolls out of the 200-line buffer within minutes, a header cannot.
|
||||
fwVer: null, uplink: 'no-config', lastUplinkLogged: null, lastRegionInertLogged: null,
|
||||
pendingCount: 0, lastConfigTryAt: null,
|
||||
// pubFailures: consecutive publish failures per queue id, so one unpublishable
|
||||
// record can be stepped over instead of blocking every record behind it forever.
|
||||
// staleReported: ids of retired publishers already called out, so an orphaned
|
||||
// client's endless reconnect loop is named once rather than flooding the log.
|
||||
pubFailures: new Map(), staleReported: new Set(),
|
||||
lastHeard: null, snrBarPct: 0, snrPeakPct: 0,
|
||||
// auto-discover
|
||||
lastHeardAt: null, lastFireAt: 0, tick: null,
|
||||
@@ -573,7 +579,15 @@ function noteRegionInert() {
|
||||
// Split out of connectAll so a config that only arrives on a LATER retry can bring
|
||||
// uploading up on its own, without the user reconnecting the companion.
|
||||
async function startPublisher() {
|
||||
if (state.publisher) return true;
|
||||
if (state.publisher) {
|
||||
if (state.publisher.connected()) return true;
|
||||
// Never ADOPT a publisher that is not connected. It has its own 4 s reconnect loop,
|
||||
// and reporting success for it made connectAll print '③ CoreScope connected ✓' over
|
||||
// a client that was in fact looping. Retiring it stops that loop and its events.
|
||||
dbg('retiring publisher #' + state.publisher.id + ' — it was not connected', 'no');
|
||||
state.publisher.end();
|
||||
state.publisher = null;
|
||||
}
|
||||
const cfg = getConfig();
|
||||
if (!cfg || !cfg.mqttUrl) return false;
|
||||
state.publisher = new Publisher({ url: cfg.mqttUrl, username: cfg.mqttUsername, password: cfg.mqttPassword, clientId: state.companionPubkey });
|
||||
@@ -729,9 +743,22 @@ function renderBroker() {
|
||||
|
||||
// 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) {
|
||||
function onBrokerStatus(s, arg, id) {
|
||||
// Only the CURRENT publisher may move the broker state. An orphaned client keeps its
|
||||
// own 4 s reconnect loop running and its failures used to overwrite brokerState, so a
|
||||
// healthy link was reported as down and the log filled with errors nobody could
|
||||
// attribute — ~18 'Keepalive timeout' lines against a single successful connect,
|
||||
// which is impossible for one client. Name each stale publisher once, then ignore it.
|
||||
const live = state.publisher ? state.publisher.id : null;
|
||||
if (id !== live) {
|
||||
if (!state.staleReported.has(id)) {
|
||||
state.staleReported.add(id);
|
||||
dbg('ignoring MQTT events from retired publisher #' + id + ' (live: ' + (live ?? 'none') + '), first was "' + s + '"', 'no');
|
||||
}
|
||||
return;
|
||||
}
|
||||
state.brokerState = s;
|
||||
if (s === 'connect') dbg('CoreScope connected', 'ok');
|
||||
if (s === 'connect') dbg('CoreScope connected (publisher #' + id + ', connack rc=' + ((arg && arg.returnCode) ?? '?') + ', keepalive ' + KEEPALIVE_SECS + 's)', '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');
|
||||
@@ -886,19 +913,28 @@ async function refreshCounters() {
|
||||
renderStatusStrip();
|
||||
}
|
||||
|
||||
// drain publishes all buffered receptions once. Returns the count published. Isolated
|
||||
// from the loop so the "Push pending now" button can call it directly.
|
||||
// drain publishes as much of the buffered queue as the link allows, once. The loop and
|
||||
// its commit rules live in src/drain.js (tested there); this is only the wiring.
|
||||
//
|
||||
// It used to collect every published id and call queue.remove ONCE after the loop, so a
|
||||
// single rejecting publish threw the progress away — and since publishes are sequential,
|
||||
// a 59-record backlog needs ~5 s of continuous link at 86 ms round-trip and ~18 s at
|
||||
// 300 ms. On a mobile link that stayed up about a second at a time, that design could
|
||||
// never commit anything at all.
|
||||
async function drain() {
|
||||
if (!(state.publisher && state.publisher.connected() && state.companionPubkey)) return 0;
|
||||
const rows = await state.queue.takeAll();
|
||||
const done = [];
|
||||
for (const r of rows) { await state.publisher.publish(state.companionPubkey, r, state.companionName); done.push(r.id); }
|
||||
if (done.length) {
|
||||
await state.queue.remove(done);
|
||||
const r = await drainOnce({
|
||||
queue: state.queue,
|
||||
publisher: state.publisher,
|
||||
pubkey: state.companionPubkey,
|
||||
name: state.companionName,
|
||||
failures: state.pubFailures,
|
||||
log: dbg,
|
||||
});
|
||||
if (r.committed) {
|
||||
state.lastUploadAt = Date.now();
|
||||
dbg('published ' + done.length + ' record(s)', 'ok');
|
||||
dbg('published ' + r.committed + ' record(s)' + (r.stopped === 'link' ? ' before the link dropped — rest kept' : ''), 'ok');
|
||||
}
|
||||
return done.length;
|
||||
return r.committed;
|
||||
}
|
||||
|
||||
// drainLoop runs forever every 5 s. A publish to a dead socket never acks, but
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
// Publishing the offline queue. Extracted from app.js because this is the one path
|
||||
// where a bug loses or duplicates field data, and it needs to be testable against a
|
||||
// link that dies mid-flush.
|
||||
//
|
||||
// The design it replaces collected every published id and removed them only after
|
||||
// the whole loop finished:
|
||||
//
|
||||
// for (const r of rows) { await publish(r); done.push(r.id); }
|
||||
// if (done.length) { await queue.remove(done); }
|
||||
//
|
||||
// One rejecting publish threw out of the loop, so `queue.remove` never ran and every
|
||||
// record the broker had ALREADY acknowledged stayed queued and was published again.
|
||||
// Worse, it made progress impossible on a flaky link: publishes are sequential, so a
|
||||
// 59-record backlog needs ~5 s of continuous connectivity at 86 ms round-trip and
|
||||
// ~18 s at 300 ms. Observed in the field on a link that stayed up for about one
|
||||
// second at a time — the queue could never commit anything at all.
|
||||
//
|
||||
// Two rules follow, and the tests below pin both:
|
||||
// 1. A record is removed if and only if the broker acknowledged it. Progress is
|
||||
// committed as it is made, so a link that dies mid-flush keeps what it earned.
|
||||
// 2. One record that cannot be published must never block the records behind it.
|
||||
|
||||
export const COMMIT_EVERY = 10; // ids per queue.remove — bounds re-publishing on a crash to <10
|
||||
export const POISON_AFTER = 3; // consecutive failures before a record is stepped over
|
||||
|
||||
// drainOnce publishes as much of the queue as the link allows, exactly once.
|
||||
//
|
||||
// deps:
|
||||
// queue { takeAll(), remove(ids) }
|
||||
// publisher { connected(), publish(pubkey, rec, name) } — publish rejects on failure
|
||||
// pubkey, name identify this observer in the payload
|
||||
// failures Map<id, count> of consecutive publish failures, owned by the caller so it
|
||||
// survives across drains (a poison record must be recognised over time)
|
||||
// log (msg, level) optional
|
||||
//
|
||||
// Returns { published, committed, skipped, stopped } where `stopped` says why the
|
||||
// pass ended: 'done' | 'link' | 'error'.
|
||||
export async function drainOnce({ queue, publisher, pubkey, name, failures, log }) {
|
||||
const note = log || (() => {});
|
||||
if (!(publisher && publisher.connected() && pubkey)) {
|
||||
return { published: 0, committed: 0, skipped: 0, stopped: 'link' };
|
||||
}
|
||||
|
||||
const rows = await queue.takeAll();
|
||||
const pending = []; // acked ids not yet removed from the queue
|
||||
let published = 0;
|
||||
let committed = 0;
|
||||
let skipped = 0;
|
||||
let stopped = 'done';
|
||||
|
||||
// commit is called as progress accumulates AND on every exit path, so an
|
||||
// acknowledged record is never left in the queue to be sent twice.
|
||||
const commit = async () => {
|
||||
if (!pending.length) return;
|
||||
const ids = pending.splice(0, pending.length);
|
||||
await queue.remove(ids);
|
||||
committed += ids.length;
|
||||
};
|
||||
|
||||
try {
|
||||
for (const r of rows) {
|
||||
// Re-check the link before every record: it is the whole point of committing
|
||||
// incrementally that a mid-flush drop keeps what was already delivered.
|
||||
if (!publisher.connected()) { stopped = 'link'; break; }
|
||||
try {
|
||||
await publisher.publish(pubkey, r, name);
|
||||
} catch (e) {
|
||||
// A publish that failed because the LINK went down says nothing about the
|
||||
// record, so it must not count as a strike against it — three drops in a row
|
||||
// would otherwise quarantine a perfectly good reception. Stop the pass and
|
||||
// retry the same record once there is a connection again.
|
||||
if (!publisher.connected()) {
|
||||
note('link dropped mid-publish (' + e.message + ') — ' + (rows.length - published - skipped) + ' record(s) still queued', 'no');
|
||||
stopped = 'link';
|
||||
break;
|
||||
}
|
||||
const n = (failures.get(r.id) ?? 0) + 1;
|
||||
failures.set(r.id, n);
|
||||
if (n < POISON_AFTER) {
|
||||
// Most failures are the link, not the record. Stop and retry this same
|
||||
// record on the next pass rather than burning an 8 s publish timeout on
|
||||
// every remaining row against a socket that is already gone.
|
||||
note('publish failed (' + e.message + ') — ' + (rows.length - published - skipped) + ' record(s) still queued', 'no');
|
||||
stopped = 'error';
|
||||
break;
|
||||
}
|
||||
// Failed POISON_AFTER times in a row: treat it as unpublishable and step
|
||||
// over it, or it blocks every record behind it forever.
|
||||
skipped++;
|
||||
note('record #' + r.id + ' failed ' + n + '× — skipping it so it cannot block the queue', 'no');
|
||||
continue;
|
||||
}
|
||||
failures.delete(r.id);
|
||||
pending.push(r.id);
|
||||
published++;
|
||||
if (pending.length >= COMMIT_EVERY) await commit();
|
||||
}
|
||||
} finally {
|
||||
await commit();
|
||||
}
|
||||
|
||||
return { published, committed, skipped, stopped };
|
||||
}
|
||||
+29
-7
@@ -5,16 +5,34 @@
|
||||
// meshcore/client/{PUBLIC_KEY}/regions (region-discovery answers).
|
||||
import mqtt from 'mqtt';
|
||||
|
||||
export class Publisher {
|
||||
// opts: { url, username, password } — EMQX WSS endpoint + per-client creds.
|
||||
constructor(opts) { this.opts = opts; this.client = null; this._onStatus = null; }
|
||||
// KEEPALIVE is set EXPLICITLY rather than inherited. mqtt.js defaults to 60 s and arms
|
||||
// its keepalive manager only inside _onConnect, and only when one does not already exist
|
||||
// (client.js:1101) — it never re-arms an existing manager. So a manager that survives a
|
||||
// connection carries its counter into the next one and can report a bogus
|
||||
// 'Keepalive timeout' on a perfectly healthy link. Stating the value here means the log
|
||||
// can quote it, which is what turns that error from a red herring into evidence.
|
||||
export const KEEPALIVE_SECS = 60;
|
||||
|
||||
// onStatus(cb): cb(state, arg) is called on connection lifecycle changes, where state
|
||||
// is 'connect' | 'reconnect' | 'offline' | 'close' | 'error' (arg = Error for 'error').
|
||||
// Every Publisher gets a monotonic id. A single module-level status handler in app.js
|
||||
// receives events from EVERY instance ever created, so without an id a stale client's
|
||||
// failures are indistinguishable from the live one's — and they overwrote the broker
|
||||
// state. Field symptom: ~18 'Keepalive timeout' errors against a single successful
|
||||
// connect, which is arithmetically impossible for one client (each timeout needs its own
|
||||
// CONNACK-armed manager, and _cleanUp destroys the manager), yet nothing in the log could
|
||||
// attribute them.
|
||||
let seq = 0;
|
||||
|
||||
export class Publisher {
|
||||
// opts: { url, username, password, clientId } — EMQX WSS endpoint + per-client creds.
|
||||
constructor(opts) { this.opts = opts; this.client = null; this._onStatus = null; this.id = ++seq; }
|
||||
|
||||
// onStatus(cb): cb(state, arg, id) is called on connection lifecycle changes, where
|
||||
// state is 'connect' | 'reconnect' | 'offline' | 'close' | 'error' (arg = the CONNACK
|
||||
// packet for 'connect', an Error for 'error') and id identifies THIS publisher.
|
||||
// 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); }
|
||||
_emit(ev, arg) { if (this._onStatus) this._onStatus(ev, arg, this.id); }
|
||||
|
||||
connect() {
|
||||
this.client = mqtt.connect(this.opts.url, {
|
||||
@@ -22,10 +40,14 @@ export class Publisher {
|
||||
password: this.opts.password,
|
||||
clientId: this.opts.clientId, // = companion pubkey; EMQX ACL can bind topics to ${clientid}
|
||||
reconnectPeriod: 4000,
|
||||
keepalive: KEEPALIVE_SECS,
|
||||
clean: true,
|
||||
});
|
||||
// 'connect' carries the CONNACK packet through, so the log can record its return
|
||||
// code instead of leaving an auth or takeover refusal indistinguishable from a
|
||||
// network failure.
|
||||
for (const ev of ['connect', 'reconnect', 'offline', 'close']) {
|
||||
this.client.on(ev, () => this._emit(ev));
|
||||
this.client.on(ev, (packet) => this._emit(ev, packet));
|
||||
}
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// Draining the offline queue. Every case here is a field failure or a near miss:
|
||||
// a mobile link that stays up for about a second at a time, and a queue that must
|
||||
// not lose or duplicate what it already delivered.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert';
|
||||
import { drainOnce, COMMIT_EVERY, POISON_AFTER } from '../src/drain.js';
|
||||
|
||||
// fakeQueue records exactly what was removed and when, which is the whole question.
|
||||
function fakeQueue(n) {
|
||||
const rows = Array.from({ length: n }, (_, i) => ({ id: i + 1, raw: 'aa' }));
|
||||
return {
|
||||
rows,
|
||||
removals: [],
|
||||
async takeAll() { return this.rows.slice(); },
|
||||
async remove(ids) { this.removals.push(ids.slice()); this.rows = this.rows.filter((r) => !ids.includes(r.id)); },
|
||||
remaining() { return this.rows.map((r) => r.id); },
|
||||
};
|
||||
}
|
||||
|
||||
// fakePublisher: `plan` decides each publish by 1-based call number —
|
||||
// 'ok' | 'reject' | 'drop' (reject AND the link goes down, as a real drop does).
|
||||
function fakePublisher(plan) {
|
||||
return {
|
||||
calls: 0,
|
||||
up: true,
|
||||
connected() { return this.up; },
|
||||
async publish() {
|
||||
this.calls++;
|
||||
const verdict = typeof plan === 'function' ? plan(this.calls) : (plan[this.calls] || 'ok');
|
||||
if (verdict === 'drop') { this.up = false; throw new Error('publish timeout'); }
|
||||
if (verdict === 'reject') throw new Error('publish timeout');
|
||||
return undefined;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const base = (queue, publisher, failures = new Map()) =>
|
||||
({ queue, publisher, pubkey: 'ab'.repeat(32), name: 'obs', failures });
|
||||
|
||||
test('a clean run publishes and removes everything', async () => {
|
||||
const q = fakeQueue(5);
|
||||
const r = await drainOnce(base(q, fakePublisher({})));
|
||||
assert.strictEqual(r.published, 5);
|
||||
assert.strictEqual(r.committed, 5);
|
||||
assert.strictEqual(r.stopped, 'done');
|
||||
assert.deepStrictEqual(q.remaining(), []);
|
||||
});
|
||||
|
||||
test('a link that dies mid-flush KEEPS the records it already delivered', async () => {
|
||||
// The bug this replaces: `queue.remove` ran only after the loop completed, so a
|
||||
// throw discarded every acknowledgement earned before it. On a link that stays up
|
||||
// for about a second, that meant the queue could never commit anything at all.
|
||||
const q = fakeQueue(20);
|
||||
const p = fakePublisher({ 4: 'drop' });
|
||||
const r = await drainOnce(base(q, p));
|
||||
assert.strictEqual(r.published, 3, 'three were acknowledged before the drop');
|
||||
assert.strictEqual(r.committed, 3, 'and all three must be committed');
|
||||
assert.deepStrictEqual(q.remaining(), [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
|
||||
});
|
||||
|
||||
test('nothing acknowledged is ever left behind to be sent twice', async () => {
|
||||
const q = fakeQueue(9);
|
||||
const p = fakePublisher({ 7: 'drop' });
|
||||
await drainOnce(base(q, p));
|
||||
const removed = q.removals.flat();
|
||||
assert.deepStrictEqual(removed, [1, 2, 3, 4, 5, 6], 'exactly the acked ids, no more, no less');
|
||||
assert.strictEqual(new Set(removed).size, removed.length, 'and never removed twice');
|
||||
});
|
||||
|
||||
test('progress is committed in batches, not only at the end', async () => {
|
||||
const q = fakeQueue(COMMIT_EVERY * 2 + 3);
|
||||
const p = fakePublisher({});
|
||||
await drainOnce(base(q, p));
|
||||
assert.ok(q.removals.length >= 3, 'expected several commits, got ' + q.removals.length);
|
||||
assert.strictEqual(q.removals[0].length, COMMIT_EVERY);
|
||||
});
|
||||
|
||||
test('a dropped link stops the pass instead of burning a timeout per remaining record', async () => {
|
||||
// 59 records × an 8 s publish timeout is eight minutes of pointless waiting
|
||||
// against a socket that is already gone.
|
||||
const q = fakeQueue(59);
|
||||
const p = fakePublisher({ 2: 'drop' });
|
||||
const r = await drainOnce(base(q, p));
|
||||
assert.strictEqual(p.calls, 2, 'must not keep publishing after the link went down');
|
||||
assert.strictEqual(r.stopped, 'link');
|
||||
});
|
||||
|
||||
test('a transient failure retries the SAME record next pass rather than skipping it', async () => {
|
||||
const q = fakeQueue(4);
|
||||
const failures = new Map();
|
||||
const r = await drainOnce(base(q, fakePublisher({ 1: 'reject' }), failures));
|
||||
assert.strictEqual(r.published, 0);
|
||||
assert.strictEqual(r.skipped, 0, 'one failure is not yet evidence the record is bad');
|
||||
assert.strictEqual(r.stopped, 'error');
|
||||
assert.deepStrictEqual(q.remaining(), [1, 2, 3, 4], 'nothing lost');
|
||||
assert.strictEqual(failures.get(1), 1);
|
||||
});
|
||||
|
||||
test('a record that keeps failing is stepped over so it cannot block the queue', async () => {
|
||||
// Otherwise one permanently unpublishable row at the head of the queue stops
|
||||
// every reception behind it, forever.
|
||||
const q = fakeQueue(3);
|
||||
const failures = new Map();
|
||||
const alwaysFailFirst = (call) => (call === 1 ? 'reject' : 'ok');
|
||||
for (let pass = 1; pass < POISON_AFTER; pass++) {
|
||||
const r = await drainOnce(base(q, fakePublisher(alwaysFailFirst), failures));
|
||||
assert.strictEqual(r.published, 0, 'pass ' + pass + ' should still be retrying record 1');
|
||||
}
|
||||
const last = await drainOnce(base(q, fakePublisher(alwaysFailFirst), failures));
|
||||
assert.strictEqual(last.skipped, 1, 'record 1 is now treated as unpublishable');
|
||||
assert.strictEqual(last.published, 2, 'and the records behind it finally go out');
|
||||
assert.deepStrictEqual(q.remaining(), [1], 'the skipped record is kept, not discarded');
|
||||
});
|
||||
|
||||
test('a record that recovers clears its failure count', async () => {
|
||||
const q = fakeQueue(2);
|
||||
const failures = new Map();
|
||||
await drainOnce(base(q, fakePublisher({ 1: 'reject' }), failures));
|
||||
assert.strictEqual(failures.get(1), 1);
|
||||
await drainOnce(base(q, fakePublisher({}), failures));
|
||||
assert.strictEqual(failures.has(1), false, 'a success must not leave a stale strike behind');
|
||||
assert.deepStrictEqual(q.remaining(), []);
|
||||
});
|
||||
|
||||
test('no publisher, no connection or no pubkey is a no-op, not an error', async () => {
|
||||
const q = fakeQueue(3);
|
||||
for (const deps of [
|
||||
{ ...base(q, null) },
|
||||
{ ...base(q, { connected: () => false, publish: async () => {} }) },
|
||||
{ ...base(q, fakePublisher({})), pubkey: '' },
|
||||
]) {
|
||||
const r = await drainOnce(deps);
|
||||
assert.strictEqual(r.published, 0);
|
||||
assert.strictEqual(r.stopped, 'link');
|
||||
}
|
||||
assert.deepStrictEqual(q.remaining(), [1, 2, 3], 'and the queue is untouched');
|
||||
});
|
||||
|
||||
test('an empty queue publishes nothing and commits nothing', async () => {
|
||||
const q = fakeQueue(0);
|
||||
const r = await drainOnce(base(q, fakePublisher({})));
|
||||
assert.deepStrictEqual(r, { published: 0, committed: 0, skipped: 0, stopped: 'done' });
|
||||
assert.strictEqual(q.removals.length, 0, 'must not call remove([]) for nothing');
|
||||
});
|
||||
|
||||
test('repeated LINK drops never quarantine an innocent record', async () => {
|
||||
// A drop is the link's fault. Counting it against the record meant three drops in
|
||||
// a row wrongly marked a good reception unpublishable and stepped over it.
|
||||
const q = fakeQueue(3);
|
||||
const failures = new Map();
|
||||
for (let pass = 0; pass <= POISON_AFTER + 1; pass++) {
|
||||
const r = await drainOnce(base(q, fakePublisher({ 1: 'drop' }), failures));
|
||||
assert.strictEqual(r.skipped, 0, 'pass ' + pass + ' must not skip anything');
|
||||
assert.strictEqual(r.stopped, 'link');
|
||||
}
|
||||
assert.strictEqual(failures.size, 0, 'no strikes may accumulate from link drops');
|
||||
assert.deepStrictEqual(q.remaining(), [1, 2, 3], 'nothing lost, nothing skipped');
|
||||
});
|
||||
+27
-1
@@ -4,7 +4,7 @@
|
||||
// Run: node --test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert';
|
||||
import { Publisher } from '../src/publisher.js';
|
||||
import { Publisher, KEEPALIVE_SECS } from '../src/publisher.js';
|
||||
|
||||
const rec = { rx_at: 't', raw: 'aa', snr: 1, rssi: -90, lat: 0, lon: 0, acc_m: 5 };
|
||||
|
||||
@@ -99,3 +99,29 @@ test('truncated is carried faithfully, true and false alike', () => {
|
||||
assert.equal(Publisher.payloadFor('aa11', { ...base, truncated: true }, 'node').truncated, true);
|
||||
assert.equal(Publisher.payloadFor('aa11', { ...base, truncated: false }, 'node').truncated, false);
|
||||
});
|
||||
|
||||
// --- publisher identity: attributing a status event to the client that raised it ---
|
||||
|
||||
test('each Publisher gets a distinct id so a stale client can be told apart', () => {
|
||||
const a = new Publisher({ url: 'wss://b/ws' });
|
||||
const b = new Publisher({ url: 'wss://b/ws' });
|
||||
assert.notStrictEqual(a.id, b.id);
|
||||
assert.ok(b.id > a.id, 'ids must be monotonic so "newer" is decidable');
|
||||
});
|
||||
|
||||
test('status events carry the publisher id', () => {
|
||||
// A single module-level handler receives events from every instance ever made.
|
||||
// Without the id, an orphaned client's failures overwrote the live one's state.
|
||||
const p = new Publisher({ url: 'wss://b/ws' });
|
||||
const seen = [];
|
||||
p.onStatus((ev, arg, id) => seen.push([ev, arg, id]));
|
||||
p._emit('error', new Error('Keepalive timeout'));
|
||||
assert.strictEqual(seen[0][0], 'error');
|
||||
assert.strictEqual(seen[0][1].message, 'Keepalive timeout');
|
||||
assert.strictEqual(seen[0][2], p.id);
|
||||
});
|
||||
|
||||
test('keepalive is stated explicitly, not inherited from mqtt.js', () => {
|
||||
assert.strictEqual(typeof KEEPALIVE_SECS, 'number');
|
||||
assert.ok(KEEPALIVE_SECS > 0);
|
||||
});
|
||||
Reference in new issue
Block a user