Repository navigation
Serialize outbound JSON straight into the Noise send buffer - #222
Merged
Merged
Conversation
Every outbound JSON message was serialized into a std::string that grew a byte at a time. On ESPHome, operator new only uses internal RAM and aborts under -fno-exceptions when an allocation fails, which crashed a reconnect after the internal heap ran out (#220). The format_*_message() builders now return a JsonDocument from the JSON arena, and SendspinConnection::send_json() serializes it, sized by measureJson(), into the transport's reused send buffer (NoiseTransport::stage_json()). From there it is encrypted in place (send_staged_json()) or, before the handshake, sent as a cleartext text frame. client/time is formatted into the same buffer, and the re-handshake msg2 is staged there before send_msg2_and_swap(). client/init still goes out from the text the handshake keeps for its prologue. A document that overflowed its allocator, or one longer than one frame, is refused with NO_MEM instead of sent truncated or fragmented; outbound JSON no longer fragments. A refused or failed send wipes the staged text, replacing the caller-side wipe of the pair-finalize string. send_text_message() takes (const char*, size_t), and build_client_hello() returns the hello fields so the public header needs no ArduinoJson.
clang-tidy's clang-analyzer-core.StackAddressEscape flagged every function returning a JsonDocument by value: ArduinoJson's pool list points into its own inline storage, which the analyzer reads as a stack address escaping, though the move constructor re-points it. The build_*_message() builders now fill a document the caller makes with make_json_document(), the output-parameter shape the process_*() parsers already use, and a re-handshake result carries msg2's Noise bytes for the connection to wrap (build_noise_handshake_message()).
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
The pairing failure path exceeds the JSON arena and forces an unnecessary heap allocation, while later-fragment failure coverage is missing and stack-analysis mappings remain stale.
3 open issues
What changed in this PR
This PR addresses #220 by serializing outbound JSON directly into the reusable Noise send buffer, avoiding temporary heap strings that could abort ESP32 reconnects under memory pressure.
Changes:
- Converts message formatters into builders that fill caller-owned JSON documents.
- Centralizes JSON staging and sending, rejects overflowed or oversized documents, and wipes staged plaintext on encrypted-send failures.
- Updates transport interfaces, tests, and documentation for the new send path.
| File | Description |
|---|---|
| tests/test_util.h | Adds helpers for testing document builders. |
| tests/test_protocol.cpp | Migrates message-format tests to builders. |
| tests/test_player_role.cpp | Updates the fake text-send signature. |
| tests/test_pairing_state_machine.cpp | Adapts pairing fixtures and hello inspection. |
| tests/test_noise_transport.cpp | Tests staged sends, rejection, and plaintext wiping. |
| tests/test_noise_rehandshake.cpp | Consumes raw msg2 bytes in handshake tests. |
| tests/test_message_trace.cpp | Uses builders for secret-redaction fixtures. |
| tests/test_json_arena.cpp | Adapts arena-lifetime tests to caller-owned documents. |
| tests/test_encrypted_lifecycle.cpp | Updates send fakes and arena tests. |
| tests/test_dynamic_pairing_code.cpp | Migrates pairing-message tests to builders. |
| tests/test_client_lifecycle.cpp | Updates lifecycle send fakes. |
| tests/test_artwork_role.cpp | Builds the hello document for assertions. |
| tests/loopback_connection.h | Adapts shared transport and handshake helpers. |
| tests/lifecycle_test_fixtures.h | Updates a send-path comment. |
| tests/CMakeLists.txt | Documents private access used by wipe tests. |
| src/source_role.cpp | Sends stream lifecycle messages through documents. |
| src/protocol.cpp | Replaces string formatters with document builders. |
| src/protocol_messages.h | Declares builders and their ownership contract. |
| src/pairing_offers.h | Updates the hello-builder reference in comments. |
| src/noise_transport.h | Declares JSON staging and staged-send interfaces. |
| src/noise_transport.cpp | Stages and encrypts JSON in the reusable buffer. |
| src/noise_handshake.h | Updates handshake callbacks and result types. |
| src/noise_handshake.cpp | Builds msg2 documents and reuses retained init text. |
| src/host/server_connection.h | Declares pointer-and-length text sends. |
| src/host/server_connection.cpp | Implements pointer-and-length text sends. |
| src/host/client_connection.h | Declares pointer-and-length text sends. |
| src/host/client_connection.cpp | Implements pointer-and-length text sends. |
| src/esp/server_connection.h | Updates the asynchronous text-send declaration. |
| src/esp/server_connection.cpp | Queues text from pointer-and-length inputs. |
| src/esp/client_connection.h | Updates the synchronous text-send declaration. |
| src/esp/client_connection.cpp | Passes text buffers directly to WebSocket sends. |
| src/connection.h | Defines the document-send and staging contracts. |
| src/connection.cpp | Routes JSON, time messages, and msg2 through staging. |
| src/connection_manager.cpp | Uses document builders for management messages. |
| src/connection_manager_pairing.cpp | Migrates pairing sends to caller-owned documents. |
| src/client.cpp | Returns hello fields and builds state documents. |
| src/client_dispatch.cpp | Builds command documents and clarifies arena lifetime. |
| include/sendspin/config.h | Documents outbound send-buffer placement. |
| include/sendspin/client.h | Updates the private hello-builder declaration. |
| docs/playback-sync.md | Documents the staged time-message write hook. |
| docs/internals.md | Describes direct serialization and JSON size limits. |
| docs/integration-guide.md | Clarifies send-buffer memory placement. |
Review effort: Balanced
The static-code client/pair-init document stayed alive through start_pake_round(), whose CPace failure path builds a pair/abort, so two documents shared the arena. It is now released before CPace starts, as in the Pairing-PSK flow. edges.json still keyed the connection's virtual sends on the removed send_app_json(const char*), and sent the handshake callback straight to the text transports. send_json() now carries those edges, including the cleartext send_text_message() targets, and the handshake callback reaches its std::function invoker. Re-measured at -Os and -Og: the protocol task's reachable chain is 5,936 / 6,368 bytes, so the default stays 7,168.
Every message the client sends now fits one Noise frame: JSON through stage_json(), and binary through send_binary_lent(), both refusing anything longer. That left NoiseTransport::send_binary() with no production caller and fragment_and_send(), its only user and the one allocation of a ~64 KB frame buffer, unreachable. Both are gone, with the tests that drove only them; inbound reassembly stays, since servers still fragment large messages. Docs, the noise_buffer_location comments and the stack-analysis edges no longer mention the fragmentation buffer.
Contributor
There was a problem hiding this comment.
🔵 Needs a closer look
Target-device validation is needed because the ESP32 heap-exhaustion reconnect and allocation failure while staging re-handshake msg2 remain untested, leaving low-memory recoverability unverified.
No open issues 🎉
3 resolved since last review
Review effort: Balanced
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
Fixes #220. Every outbound JSON message was serialized into a
std::stringthat grew a byte at a time. On ESPHomeoperator newonly uses internal RAM and aborts under-fno-exceptions, so a reconnect right after the internal heap ran out crashed informat_client_hello_message(). Outbound JSON now goes straight into the transport's existing send buffer (PSRAM-preferring, kept across messages), with no heap string on the way.Changes
format_*_message()->build_*_message(), filling a caller-ownedJsonDocumentmade from the JSON arena (the output-parameter shape theprocess_*()parsers use; returning documents by value trips clang-analyzer's StackAddressEscape on ArduinoJson's self-referencing pool list).SendspinConnection::send_json(doc)is the one send path: it serializes the document, sized bymeasureJson(), into the send buffer (NoiseTransport::stage_json()), then encrypts it in place (send_staged_json()) or, before the handshake, sends it from there as a cleartext text frame.client/timeformats into the same buffer; the re-handshake msg2 is staged there beforesend_msg2_and_swap().client/initstill goes out from the text the handshake keeps for its prologue.NO_MEM, instead of sent truncated or fragmented; the hello path already drops the connection on any error.NoiseTransport::send_binary()had no production caller, so it andfragment_and_send(), the only allocation of a ~64 KB frame buffer, are gone. Inbound reassembly stays, since servers still fragment large messages.send_text_message()takes(const char*, size_t)on every transport.build_client_hello()returns the hello fields, soclient.hneeds no ArduinoJson.Testing
tools/stack_usage:edges.jsonre-keyed from the removedsend_app_jsontosend_json(), whose stale entry had dropped the cleartext send edges. Re-measured: the protocol task's bound is 6,560 / 6,624 B (-Os / -Og, was 6,560 / 6,832) and its reachable chain 5,936 / 6,368 B (was 6,352 / 6,576), so the 7,168 default stays; README updated.Not covered: the reporter's reproduction under heap exhaustion; a failed msg2 staging during a re-handshake. The hello struct's own strings and the handshake's base64 strings still allocate internally.