fix(MQTTTransport): reply with error instead of silently dropping malformed input (F-063)
Invalid JSON or a missing 'cmd' field on control/command previously logged
a WARNING on serial and returned with no reply at all — a client waiting
on control/ack had no way to tell "malformed request" apart from "message
never arrived" or "device offline," all three looking identical until its
own timeout fired.
Both onMessage() drop paths now publish an ERROR to control/ack before
returning: { "status": "ERROR", "type": "parse_error", "message": "..." }.
Unparseable JSON necessarily has no req_id (nothing to read it from); a
valid-but-cmd-less message echoes req_id if one was present. The heap-guard
drop above these two (hasHeapForPublish() check) is untouched — that one's
silence is deliberate, protecting against allocation under critical heap
pressure (see F-055), not something this fix should touch.
Bumped to v2.2.1. Verified: pio run -e vesper-std-v1 -e agnus-v1 both build clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -75,6 +75,7 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne
|
||||
| F-060 | `system.set_identity` — sysadmin override of factory-set device identity (serial/hw_family/hw_revision) | v2.1.0 | Stable |
|
||||
| F-061 | Fix: `LegacyResponseAdapter` — v1 tablets saw device as "unavailable" while playing, due to `system.status` reply schema mismatch | v2.1.1 | Stable (temporary migration scaffolding) |
|
||||
| F-062 | MQTT topic spec v2 — restructured topics (`control/command`/`control/ack`/`control/reports`/`status/playback`/`system/*`), LWT, `req_id` correlation, per-topic ON/OFF switches (`mqtt.set_topics`) | v2.2.0 | Stable |
|
||||
| F-063 | Fix: malformed `control/command` input (bad JSON, missing `cmd`) now gets an `ERROR` reply on `control/ack` instead of being silently dropped | v2.2.1 | Stable |
|
||||
|
||||
---
|
||||
|
||||
@@ -1120,3 +1121,29 @@ Verified: `pio run -e vesper-std-v1` and `pio run -e agnus-v1` both build clean
|
||||
paths both touched).
|
||||
|
||||
Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.hpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp`, `src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp`, `src/Communication/Handlers/MQTTHandler/MQTTHandler.cpp`, `src/Communication/CommandBus/CommandEnvelope.hpp`, `src/Communication/CommandBus/CommandResult.hpp`, `src/Communication/CommandBus/CommandBus.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.hpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/ConfigManager/ConfigManager.hpp`, `src/ConfigManager/ConfigManager.cpp`, `src/Player/Player.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-063 — Fix: malformed `control/command` input silently dropped
|
||||
|
||||
Found during manual QA of F-062: sending invalid JSON (e.g. a missing comma or bracket) to
|
||||
`control/command` logged `[WARN][MQTTTransport] JSON parse error: IncompleteInput — dropping message`
|
||||
on serial, but published nothing to `control/ack`. A caller had no way to distinguish "malformed
|
||||
request" from "message never arrived" or "device offline" — all three looked identical from the
|
||||
client's side: silence until its own timeout fired.
|
||||
|
||||
**Fix.** Both silent-drop paths in `MQTTTransport::onMessage()` now reply with an `ERROR` on
|
||||
`control/ack` before returning, instead of just logging and returning:
|
||||
- Unparseable JSON → `{ "status": "ERROR", "type": "parse_error", "message": "Invalid JSON: <reason>" }`.
|
||||
No `req_id` on this reply — one can't be read out of input that failed to parse.
|
||||
- Valid JSON but missing `cmd` → same shape, `"message": "Missing required field: cmd"`. Echoes
|
||||
`req_id` if the JSON was otherwise valid and included one.
|
||||
|
||||
The pre-existing heap-guard drop (`MQTTDriver::hasHeapForPublish()` check, top of `onMessage()`) is
|
||||
deliberately **not** changed — that guard exists specifically to avoid allocating under critical heap
|
||||
pressure (see F-055), and a parse-error reply is cheap enough not to need the same protection, but the
|
||||
guard itself must stay silent by design.
|
||||
|
||||
Verified: `pio run -e vesper-std-v1` builds clean.
|
||||
|
||||
Subsystem: `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp`
|
||||
|
||||
@@ -296,6 +296,15 @@ Structured telemetry for fleet-health graphing — not consumed by the phone app
|
||||
|
||||
`req_id` only appears in the reply if the request included one. Bus-wide unsolicited broadcasts (`CommandBus::broadcast()`) also publish here, with the same envelope shape and no `req_id` — but purpose-specific events (playback, alerts, reports, metrics) never use this path; they publish directly to their own topics instead.
|
||||
|
||||
### Malformed input
|
||||
|
||||
Invalid JSON or a missing `cmd` field gets an `ERROR` reply on `control/ack` (`type: "parse_error"`) instead of being silently dropped:
|
||||
|
||||
```json
|
||||
{ "status": "ERROR", "type": "parse_error", "message": "Invalid JSON: IncompleteInput" }
|
||||
{ "status": "ERROR", "type": "parse_error", "message": "Missing required field: cmd" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Server subscription pattern
|
||||
|
||||
@@ -9,7 +9,7 @@ and [MQTTTransport](../../src/Communication/Transport/MQTTTransport/README.md) (
|
||||
| Topic | Purpose | QoS | Retain | Switch | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| `vesper/{device_id}/control/command` | Inbound commands (play, stop, ping, etc.) | 1 | No | `command` | **Read-only from the board's perspective — the board only receives here, never publishes.** Includes optional `req_id` for correlation. `v`, `cmd`, `contents` as before. |
|
||||
| `vesper/{device_id}/control/ack` | Replies to commands, including `pong` | 1 | No | `command` | **Strictly replies only — every message here answers a specific request, and every reply goes here. Nothing unsolicited is ever published to this topic.** Echoes `req_id` from the originating command when one was sent. `status: SUCCESS/ERROR/INFO`, `type`, optional `message`/`data`. |
|
||||
| `vesper/{device_id}/control/ack` | Replies to commands, including `pong` | 1 | No | `command` | **Strictly replies only — every message here answers a specific request, and every reply goes here. Nothing unsolicited is ever published to this topic.** Echoes `req_id` from the originating command when one was sent. `status: SUCCESS/ERROR/INFO`, `type`, optional `message`/`data`. Malformed input (invalid JSON, missing `cmd`) also gets an `ERROR` reply here (`type: "parse_error"`) rather than being silently dropped — see [Malformed input](#malformed-input) below. |
|
||||
| `vesper/{device_id}/control/reports` | Critical, time-sensitive board-initiated events (e.g. bell overload) | 1 | No | `reports` | The opposite of `control/command` — unsolicited data the board sends because it needs to be read *now*. Not a reply to anything, no `req_id`. Not retained — an event stream, not a status snapshot. |
|
||||
| `vesper/{device_id}/status/heartbeat` | Periodic health/state summary, every 30s | 1 | **Yes** | `heartbeat` | Also carries LWT (see below). Fields: `device_id`, `state` (`idle`/`playing`/`paused`/`error`/`booting`), `ok` (bool), `fw_version`, `uptime_ms`, `uptime_human`, `ip_address`, `gateway`, `rssi`, `free_heap` — `state`/`ok` independently derived, never mirrored from `status/playback` or `system/alerts`. |
|
||||
| `vesper/{device_id}/status/playback` | Playback state transitions only | 1 | **Yes** | `playback` | `action`: `playing`/`paused`/`idle`, plus `time_elapsed`, `projected_run_time`. Published on transition, not polled. |
|
||||
@@ -50,6 +50,17 @@ This lets a device "breathe" — a fleet-monitoring-only install with no phone a
|
||||
- **Bus-wide, not MQTT-only.** `req_id` lives on `CommandEnvelope`/`CommandResult` in the shared `CommandBus` core (see [CommandBus](../../src/Communication/CommandBus/README.md)), not bolted onto MQTT alone — the intent is that any transport where multiple logical senders share one channel (multiple devices on one broker; a future multiplexed transport) can use the same mechanism to route replies.
|
||||
- **No access control yet.** Any caller can set any `req_id` today. If needed later, safeguards (e.g. restricting who may set one, or validating format) can be added without a wire-format change.
|
||||
|
||||
## Malformed Input
|
||||
|
||||
`control/command` messages that fail to parse, or parse but have no `cmd` field, get an `ERROR` reply on `control/ack` instead of being silently dropped:
|
||||
|
||||
```json
|
||||
{ "status": "ERROR", "type": "parse_error", "message": "Invalid JSON: IncompleteInput" }
|
||||
{ "status": "ERROR", "type": "parse_error", "message": "Missing required field: cmd" }
|
||||
```
|
||||
|
||||
A reply to unparseable JSON necessarily has no `req_id` — it couldn't be read out of input that failed to parse. A reply to a parseable-but-`cmd`-less message echoes `req_id` if one was present. This exists so a caller waiting on a timeout gets an immediate, actionable "malformed" instead of silence indistinguishable from a lost network message — the same reasoning the heap guard's silent drop (see [MQTTTransport's README](../../src/Communication/Transport/MQTTTransport/README.md)) deliberately does *not* apply here, since that guard exists specifically to avoid allocating under critical heap pressure, whereas a parse error is cheap to report.
|
||||
|
||||
## Cross-Cutting Notes
|
||||
|
||||
- **LWT (Last Will and Testament)**: on connect, register Last Will → publishes to `status/heartbeat` with `{"device_id": "...", "state": "offline", "ok": false}` (retained), fired by the broker only on an *unclean* disconnect. Re-registered automatically on every reconnect (AsyncMqttClient resends the Will on every CONNECT).
|
||||
|
||||
@@ -64,7 +64,18 @@ void MQTTTransport::onMessage(const String& topic, const String& payload) {
|
||||
JsonDocument doc;
|
||||
DeserializationError err = deserializeJson(doc, payload);
|
||||
if (err) {
|
||||
LOG_WARNING(TAG, "JSON parse error: %s — dropping message", err.c_str());
|
||||
LOG_WARNING(TAG, "JSON parse error: %s — replying with error", err.c_str());
|
||||
// Can't recover a req_id from unparseable JSON — the reply necessarily
|
||||
// has none. Still worth an ack: a caller waiting on a timeout gets an
|
||||
// immediate, actionable "malformed" instead of silence indistinguishable
|
||||
// from a lost network message.
|
||||
JsonDocument resp;
|
||||
resp["status"] = "ERROR";
|
||||
resp["type"] = "parse_error";
|
||||
resp["message"] = String("Invalid JSON: ") + err.c_str();
|
||||
String out;
|
||||
serializeJson(resp, out);
|
||||
_mqtt.publishAck(out);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -87,7 +98,17 @@ void MQTTTransport::onMessage(const String& topic, const String& payload) {
|
||||
}
|
||||
|
||||
if (envelope.command.isEmpty()) {
|
||||
LOG_WARNING(TAG, "MQTT message missing 'cmd' field — dropping");
|
||||
LOG_WARNING(TAG, "MQTT message missing 'cmd' field — replying with error");
|
||||
JsonDocument resp;
|
||||
resp["status"] = "ERROR";
|
||||
resp["type"] = "parse_error";
|
||||
resp["message"] = "Missing required field: cmd";
|
||||
if (!envelope.reqId.isEmpty()) {
|
||||
resp["req_id"] = envelope.reqId;
|
||||
}
|
||||
String out;
|
||||
serializeJson(resp, out);
|
||||
_mqtt.publishAck(out);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,5 +62,5 @@ Responses are published to `control/ack`:
|
||||
- **Broker connection is deferred.** `begin()` does not connect. The connection is triggered by `onNetworkConnected()`, which starts a 2-second non-blocking stabilisation timer in `MQTTDriver`.
|
||||
- **MQTT must be enabled in config, and the `command` topic switch must be on.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle the master switch with `mqtt.enable` / `mqtt.disable`. Independently, the `command` topic switch (via `mqtt.set_topics`) gates the `control/command` subscription and `control/ack` replies — turning it off while MQTT stays connected silently stops all command traffic.
|
||||
- **No per-message QoS.** Command replies and broadcasts are published at QoS 1 (matching the topic table). Heartbeats use QoS 1 with `retain = true`.
|
||||
- **JSON parse errors drop the message silently** (with a `LOG_WARNING`). The client receives no error response.
|
||||
- **JSON parse errors and missing `cmd` get an `ERROR` reply on `control/ack`** (`type: "parse_error"`), not a silent drop — a `LOG_WARNING` is still emitted too. A parse-error reply necessarily has no `req_id` (it can't be read from input that failed to parse); a missing-`cmd` reply echoes `req_id` if the JSON was otherwise valid and included one.
|
||||
- **Incoming commands are dropped under critical heap pressure.** `onMessage()` checks `MQTTDriver::hasHeapForPublish()` (free heap ≥ 20KB) before even constructing the `JsonDocument` used to deserialize the incoming payload. Below that threshold, the message is dropped with no reply and no error response — indistinguishable from a lost network message to the caller. This exists because a rapid burst of commands (each involving deserialize + dispatch + reply, all allocation-heavy, all running inline on AsyncTCP's own task) previously fragmented the heap enough to crash the device with an unrecoverable `abort()` — see `docs/features/feature-catalog.md` F-055. A full fix (queueing incoming commands to a dedicated task, so this work never runs on AsyncTCP's task at all) is a scoped future improvement, not yet implemented.
|
||||
|
||||
+3
-1
@@ -19,8 +19,10 @@
|
||||
// v2.1.1 - Adds LegacyResponseAdapter for v1 tablet compatibility
|
||||
// v2.2.0 - MQTT topic spec v2: control/command+ack+reports, status/playback,
|
||||
// system/alerts+info+logs+metrics, LWT, req_id correlation, per-topic switches
|
||||
// v2.2.1 - Fixes malformed control/command input (bad JSON, missing cmd) being
|
||||
// silently dropped instead of replying with an ERROR on control/ack
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
#define FW_VERSION "2.2.0"
|
||||
#define FW_VERSION "2.2.1"
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// SemVer — lightweight 3-part version struct
|
||||
|
||||
Reference in New Issue
Block a user