mirror of
https://github.com/gadgethd/ukmesh.git
synced 2026-12-06 11:14:26 +00:00
Prioritize durable MQTT acknowledgements and expose broker backlog
This commit is contained in:
1 parent
408f1810ab
commit
22aa187bee
12 files changed
+138
-19
No files matched your search
@@ -69,6 +69,8 @@ MQTT_CLIENT_ID=meshcore-analytics-ingest
|
||||
# Optional independent control prefix; blank keeps the first business prefix.
|
||||
# A separate prefix requires publish/subscribe ACLs for its exact probe topic.
|
||||
MQTT_DELIVERY_PROBE_TOPIC_PREFIX=
|
||||
# Optional exact Mosquitto system-topic metrics. Full local DEV enables this.
|
||||
MQTT_BROKER_BACKLOG_MONITOR=false
|
||||
MESHCORE_SITE_ID=ukmesh
|
||||
|
||||
# Site-to-site owner packet sharing is available to every authenticated owner.
|
||||
|
||||
@@ -13,15 +13,8 @@ import { isPermanentPersistenceError } from '../platform/persistenceErrors.js';
|
||||
import { observationIdentityKey } from './observationIdentity.js';
|
||||
|
||||
const MAX_BATCH_SIZE = 50;
|
||||
/**
|
||||
* How long a batch may wait for company before flushing. The historical fixed
|
||||
* 50ms wait taxed every singleton batch, and a strictly serial ingest loop
|
||||
* produces nothing else. 0 flushes as soon as an entry is enqueued.
|
||||
*/
|
||||
// Durable MQTT delivery is serial: the 2k local replay measured singleton
|
||||
// batches at both settings. Immediate flush removes idle wait without changing
|
||||
// the transaction, retry, queue or acknowledgement boundaries. Operators may
|
||||
// still select a collection interval for concurrent producers.
|
||||
// MQTT intake serializes each topic through commit, so a collection timer
|
||||
// cannot add the next delivery from a busy topic to the current batch.
|
||||
const FLUSH_INTERVAL_MS = boundedEnvInteger('MQTT_INGEST_FLUSH_MS', 0, 0, 1_000);
|
||||
/**
|
||||
* Upper bound on entries waiting to be persisted. Reaching it refuses new
|
||||
|
||||
@@ -8,6 +8,20 @@ export const mqttMessagesTotal = new Counter({
|
||||
registers: [metricsRegistry],
|
||||
});
|
||||
|
||||
export const mqttIntakeDeliveriesTotal = new Counter({
|
||||
name: 'meshcore_mqtt_intake_deliveries_total',
|
||||
help: 'MQTT deliveries admitted by transport QoS, including the reserved control topics.',
|
||||
labelNames: ['qos'] as const,
|
||||
registers: [metricsRegistry],
|
||||
});
|
||||
|
||||
export const mqttBrokerStore = new Gauge({
|
||||
name: 'meshcore_mqtt_broker_store',
|
||||
help: 'Broker-wide stored messages, stored bytes, and cumulative drops from Mosquitto system topics.',
|
||||
labelNames: ['kind'] as const,
|
||||
registers: [metricsRegistry],
|
||||
});
|
||||
|
||||
export const mqttDeliveryProbeHealthy = new Gauge({
|
||||
name: 'meshcore_mqtt_delivery_probe_healthy',
|
||||
help: 'Whether the ingest session has successfully received its QoS 1 delivery probe.',
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { MqttClient } from 'mqtt';
|
||||
import { mqttBrokerStore } from '../metrics/ingest.js';
|
||||
|
||||
const storeTopics = new Map([
|
||||
['$SYS/broker/store/messages/count', 'messages'],
|
||||
['$SYS/broker/store/messages/bytes', 'bytes'],
|
||||
['$SYS/broker/publish/messages/dropped', 'dropped'],
|
||||
]);
|
||||
|
||||
/** Optional telemetry uses a separate subscription and never gates intake readiness. */
|
||||
export function createBrokerBacklogMonitor(client: Pick<MqttClient, 'subscribe'>) {
|
||||
return {
|
||||
subscribe() {
|
||||
client.subscribe([...storeTopics.keys()], { qos: 0 }, (error, granted) => {
|
||||
if (error || granted?.length !== storeTopics.size || granted.some(item => item.qos === 128)) {
|
||||
console.warn('[mqtt] broker backlog metrics unavailable');
|
||||
}
|
||||
});
|
||||
},
|
||||
accept(packet: { topic: string; payload: Buffer | string; qos?: number }): boolean {
|
||||
const kind = storeTopics.get(packet.topic);
|
||||
if (!kind) return false;
|
||||
const payload = packet.payload.toString();
|
||||
const value = Number(payload);
|
||||
if (packet.qos === 0 && /^\d+$/.test(payload) && Number.isSafeInteger(value)) {
|
||||
mqttBrokerStore.set({ kind }, value);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -8,10 +8,11 @@ import { initSpamDetector } from './spamDetector.js';
|
||||
import { installDurableMqttIntake } from './durableIntake.js';
|
||||
import { createDeliveryProbe, type DeliveryHealth } from './deliveryProbe.js';
|
||||
import { deliveryProbeTopics } from './deliveryProbeTopics.js';
|
||||
import { createBrokerBacklogMonitor } from './brokerBacklog.js';
|
||||
import { connectPersistentMqtt, subscribePersistentTopics } from './persistentClient.js';
|
||||
import { assertSupportedIngestConnections, loadMqttIntakeConfig } from './ingestConfig.js';
|
||||
import { waitForShutdownStep } from './shutdownDeadline.js';
|
||||
import { mqttIntakeQueueWait, mqttWireAckDuration, mqttIngestQueueDepth, mqttIngestOutcomesTotal, mqttDeliveryProbeEnabled, mqttDeliveryProbeHealthy, mqttDeliveryProbeLastSuccess, mqttDeliveryProbeRecoveries } from '../metrics/ingest.js';
|
||||
import { mqttIntakeDeliveriesTotal, mqttIntakeQueueWait, mqttWireAckDuration, mqttIngestQueueDepth, mqttIngestOutcomesTotal, mqttDeliveryProbeEnabled, mqttDeliveryProbeHealthy, mqttDeliveryProbeLastSuccess, mqttDeliveryProbeRecoveries } from '../metrics/ingest.js';
|
||||
|
||||
export type MqttRuntimeStatus = {
|
||||
state: 'starting' | 'connected' | 'disconnected' | 'reconnecting' | 'error';
|
||||
@@ -121,6 +122,9 @@ export function createMqttRuntime(deps: { events: IngestEvents; committedFollowU
|
||||
mqttDeliveryProbeEnabled.set(1);
|
||||
let previousRecoveries = 0;
|
||||
const probeTopic = probeTopics.topic;
|
||||
const brokerBacklog = process.env['MQTT_BROKER_BACKLOG_MONITOR'] === 'true'
|
||||
? createBrokerBacklogMonitor(client)
|
||||
: undefined;
|
||||
const probe = createDeliveryProbe({
|
||||
topic: probeTopic,
|
||||
publish: (nonce) => {
|
||||
@@ -146,13 +150,17 @@ export function createMqttRuntime(deps: { events: IngestEvents; committedFollowU
|
||||
probeTimer.unref();
|
||||
deliveryProbes.push({ probe, timer: probeTimer });
|
||||
durableIntakes.push(installDurableMqttIntake(client,
|
||||
(packet) => probe.accept(packet) ? Promise.resolve() : processor.process(packet),
|
||||
(packet) => probe.accept(packet) || brokerBacklog?.accept(packet) ? Promise.resolve() : processor.process(packet),
|
||||
(error) => reportMqttIngestFailure(client, error),
|
||||
{
|
||||
...MQTT_INTAKE_CONFIG,
|
||||
depth: (count) => mqttIngestQueueDepth.set(count),
|
||||
observeQueueWait: (seconds) => mqttIntakeQueueWait.observe(seconds),
|
||||
observeWireAck: (seconds) => mqttWireAckDuration.observe(seconds),
|
||||
observeAdmission: qos => mqttIntakeDeliveriesTotal.inc({ qos }),
|
||||
observeWireAck: (seconds, packet) => {
|
||||
mqttWireAckDuration.observe(seconds);
|
||||
if (packet.topic !== probeTopic) probe.noteDelivery();
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
@@ -169,7 +177,10 @@ export function createMqttRuntime(deps: { events: IngestEvents; committedFollowU
|
||||
});
|
||||
if (probeTopics.subscription) topicFilters.push(probeTopics.subscription);
|
||||
subscribePersistentTopics(client, topicFilters, {
|
||||
ready: probe.connect,
|
||||
ready: () => {
|
||||
probe.connect();
|
||||
brokerBacklog?.subscribe();
|
||||
},
|
||||
failed: error => reportMqttIngestFailure(client, error),
|
||||
subscribed: topic => console.log(`[mqtt] subscribed to ${topic}${connectionLabel}`),
|
||||
});
|
||||
|
||||
@@ -46,6 +46,30 @@ test('flowing QoS 0 cannot hide a stalled QoS 1 session; recovery preserves the
|
||||
assert.equal(published.length, 4, 'healthy sessions continue being probed');
|
||||
});
|
||||
|
||||
test('QoS 1 completions defer probe recovery while the session is making progress', () => {
|
||||
let time = 0;
|
||||
let reconnects = 0;
|
||||
const probe = createDeliveryProbe({
|
||||
topic: 'owned/probe',
|
||||
now: () => time,
|
||||
nonce: () => 'nonce',
|
||||
publish: () => {},
|
||||
reconnect: () => { reconnects++; },
|
||||
changed: () => {},
|
||||
});
|
||||
probe.connect();
|
||||
time = 45_000;
|
||||
probe.noteDelivery();
|
||||
time = 60_000;
|
||||
probe.tick();
|
||||
assert.equal(reconnects, 0);
|
||||
assert.equal(probe.status().lastSuccessAt, null, 'ordinary deliveries cannot certify the reserved nonce');
|
||||
time = 105_000;
|
||||
probe.tick();
|
||||
assert.equal(reconnects, 1);
|
||||
assert.equal(probe.status().state, 'stalled');
|
||||
});
|
||||
|
||||
test('a stalled delivery path overrides a healthy cached overview and clears on recovery', () => {
|
||||
const overview = { status: 'healthy', incidents: [], components: { ingest: { status: 'ok' } } };
|
||||
const health = { state: 'stalled' as const, lastSuccessAt: null, recoveries: 1 };
|
||||
|
||||
@@ -20,7 +20,7 @@ export function createDeliveryProbe(options: {
|
||||
}) {
|
||||
const now = options.now ?? Date.now;
|
||||
let connected = false;
|
||||
let pending: { nonce: string; deadline: number } | null = null;
|
||||
let pending: { nonce: string; progressAt: number } | null = null;
|
||||
let nextProbeAt = 0;
|
||||
let nextRecoveryAt = 0;
|
||||
let health: DeliveryHealth = { state: 'starting', lastSuccessAt: null, recoveries: 0 };
|
||||
@@ -31,7 +31,7 @@ export function createDeliveryProbe(options: {
|
||||
const tick = () => {
|
||||
if (!connected) return;
|
||||
const time = now();
|
||||
if (pending && time >= pending.deadline) {
|
||||
if (pending && time - pending.progressAt >= (options.timeoutMs ?? 60_000)) {
|
||||
change('stalled');
|
||||
if (time >= nextRecoveryAt) {
|
||||
nextRecoveryAt = time + (options.recoveryCooldownMs ?? 300_000);
|
||||
@@ -42,7 +42,7 @@ export function createDeliveryProbe(options: {
|
||||
return;
|
||||
}
|
||||
if (!pending && time >= nextProbeAt) {
|
||||
pending = { nonce: (options.nonce ?? randomUUID)(), deadline: time + (options.timeoutMs ?? 60_000) };
|
||||
pending = { nonce: (options.nonce ?? randomUUID)(), progressAt: time };
|
||||
nextProbeAt = time + (options.intervalMs ?? 30_000);
|
||||
options.publish(pending.nonce);
|
||||
}
|
||||
@@ -51,6 +51,11 @@ export function createDeliveryProbe(options: {
|
||||
connect() { connected = true; pending = null; nextProbeAt = 0; tick(); },
|
||||
disconnect() { connected = false; pending = null; },
|
||||
tick,
|
||||
// Real QoS 1 completions establish transport progress while the probe
|
||||
// waits behind queued deliveries. Only its own nonce certifies the probe.
|
||||
noteDelivery() {
|
||||
if (connected && pending) pending.progressAt = now();
|
||||
},
|
||||
accept(packet: { topic: string; payload: Buffer | string; qos?: number; retain?: boolean }) {
|
||||
if (packet.topic !== options.topic) return false;
|
||||
// Retained, forged, or late probes cannot certify the current session.
|
||||
|
||||
@@ -21,7 +21,8 @@ export function installDurableMqttIntake(
|
||||
options: {
|
||||
maxItems?: number; maxBytes?: number; concurrency?: number; depth?: (count: number) => void;
|
||||
observeQueueWait?: (seconds: number) => void;
|
||||
observeWireAck?: (seconds: number) => void;
|
||||
observeAdmission?: (qos: 0 | 1) => void;
|
||||
observeWireAck?: (seconds: number, packet: Packet) => void;
|
||||
} = {},
|
||||
) {
|
||||
const wire = client as unknown as { _sendPacket: Send };
|
||||
@@ -64,7 +65,9 @@ export function installDurableMqttIntake(
|
||||
if (!job.ack) throw new Error('MQTT_DURABLE_ACK_MISSING');
|
||||
originalSend(job.ack, (error) => {
|
||||
if (error) fail(job, error);
|
||||
else options.observeWireAck?.(Number(process.hrtime.bigint() - job.admittedAt) / 1e9);
|
||||
else if (client.stream === job.stream) {
|
||||
options.observeWireAck?.(Number(process.hrtime.bigint() - job.admittedAt) / 1e9, job.packet);
|
||||
}
|
||||
});
|
||||
}
|
||||
}).catch((cause: unknown) => fail(job, cause)).finally(() => {
|
||||
@@ -108,6 +111,7 @@ export function installDurableMqttIntake(
|
||||
pending.push(job);
|
||||
count += 1;
|
||||
bytes += size;
|
||||
options.observeAdmission?.(incoming.qos);
|
||||
update();
|
||||
callback();
|
||||
pump();
|
||||
|
||||
+2
-1
@@ -164,7 +164,8 @@ services:
|
||||
MQTT_MAX_PAYLOAD_BYTES: ${MQTT_MAX_PAYLOAD_BYTES:-65536}
|
||||
MQTT_INGEST_CONNECTIONS: ${MQTT_INGEST_CONNECTIONS:-1}
|
||||
MQTT_INGEST_SHARE_GROUP: ${MQTT_INGEST_SHARE_GROUP:-meshcore-ingest}
|
||||
MQTT_INGEST_FLUSH_MS: ${MQTT_INGEST_FLUSH_MS:-10}
|
||||
MQTT_INGEST_FLUSH_MS:
|
||||
MQTT_BROKER_BACKLOG_MONITOR: ${MQTT_BROKER_BACKLOG_MONITOR:-false}
|
||||
# The 30s lifecycle deadline reserves 25s for MQTT disconnect and queue drain.
|
||||
MQTT_INGEST_QUEUE_MAX: ${MQTT_INGEST_QUEUE_MAX:-1000}
|
||||
MQTT_INGEST_MODE: ${MQTT_INGEST_MODE:-durable}
|
||||
|
||||
@@ -763,6 +763,20 @@ Normal packet/content retention, compression, signed backups and the host disk
|
||||
exhaustion forecast continue to apply. Compression reduces retained metadata;
|
||||
it does not make an infinite exact identity history occupy bounded disk.
|
||||
|
||||
### MqttBrokerBacklog
|
||||
|
||||
Full local DEV subscribes to the three exact Mosquitto system topics for
|
||||
stored messages, stored bytes, and dropped publications. An external broker
|
||||
can opt in with `MQTT_BROKER_BACKLOG_MONITOR=true` and read grants for those
|
||||
topics. Backlog metrics are broker-wide and include retained messages.
|
||||
|
||||
The warning uses half of the local 10,000-message or 16 MiB per-session
|
||||
capacity as an early indicator. A rise in dropped publications is critical.
|
||||
Check the subscriber's commit and PUBACK rates, the active stored message
|
||||
count, and the broker log before retrying a session. Keep the persistent
|
||||
session and its storage intact. Confirm any suspected gap against committed
|
||||
observations. A publisher's PUBACK measures broker acceptance.
|
||||
|
||||
### MqttDeliveryStalled
|
||||
|
||||
The ingest connection publishes a non-retained QoS 1 nonce every 30 seconds on
|
||||
|
||||
@@ -107,6 +107,25 @@ groups:
|
||||
- name: meshcore-queues-and-workers
|
||||
interval: 15s
|
||||
rules:
|
||||
- alert: MqttBrokerBacklog
|
||||
expr: (meshcore_mqtt_broker_store{kind="messages"} > 5000) or (meshcore_mqtt_broker_store{kind="bytes"} > 8388608)
|
||||
for: 20s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: MQTT broker storage exceeds half of the smallest qualified queue budget
|
||||
owner: meshcore-operations
|
||||
runbook_url: https://github.com/gadgethd/ukmesh/blob/main/docs/operations.md#mqttbrokerbacklog
|
||||
|
||||
- alert: MqttBrokerDroppedDeliveries
|
||||
expr: increase(meshcore_mqtt_broker_store{kind="dropped"}[5m]) > 0
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: MQTT broker reported dropped deliveries
|
||||
owner: meshcore-operations
|
||||
runbook_url: https://github.com/gadgethd/ukmesh/blob/main/docs/operations.md#mqttbrokerbacklog
|
||||
|
||||
- alert: MqttIngestQueueDepthHigh
|
||||
expr: meshcore_mqtt_ingest_queue_depth > 800
|
||||
for: 5m
|
||||
|
||||
@@ -47,6 +47,7 @@ services:
|
||||
MQTT_PASSWORD: !reset null
|
||||
# Keep local delivery controls outside the companions' business namespace.
|
||||
MQTT_DELIVERY_PROBE_TOPIC_PREFIX: ukmesh-local-control
|
||||
MQTT_BROKER_BACKLOG_MONITOR: "true"
|
||||
REDIS_PASSWORD: ""
|
||||
ALLOWED_ORIGINS: http://127.0.0.1:5173,http://localhost:5173,http://127.0.0.1:3003,http://localhost:3003,http://127.0.0.1:3005,http://localhost:3005,http://127.0.0.1:8923,http://localhost:8923,http://127.0.0.1:8924,http://localhost:8924
|
||||
OWNER_ACL_MODE: shadow
|
||||
|
||||
Reference in new issue
Block a user