feat: defer observer broker connects without internal-heap headroom

A second TLS client started on a fragmented internal heap aborts a non-PSRAM
ESP32. Gate connect() on free/largest internal-heap bytes (secure slots need
much more than plaintext), deferring and retrying every 30 s instead of
crashing. The decision is a pure policy function so the host suite covers it;
the deferral is never a terminal state, so a broker missed during a heap
squeeze is still retried after a long outage.
This commit is contained in:
Jason Huebert committed 2026-10-16 21:01:06 -05:00
1 parent 3587db48cf
commit e99d19dedf
5 files changed
+61 -4

No files matched your search

+7
View File
@@ -197,6 +197,13 @@ no connected broker. No packet event, queue entry, or offline history is written
to flash or replayed after reboot. Waiting for valid time also expires queued
events, and a flush starts a fresh expiry window for newly captured events.
Publish work, TLS, NTP, and reconnects run outside the receive and forwarding path.
Before opening a broker connection the worker checks internal-heap headroom
(free and largest contiguous block); a secure slot needs considerably more than
a plaintext one. When the heap is too fragmented to start a client the connect
is deferred and retried every 30 seconds, so a second TLS slot on a low-memory
board waits for room instead of aborting the device. This check is never
terminal: a broker that could not be reached during a heap squeeze is retried
indefinitely, including after a long outage.
Both connected slots are offered each queued event. Following the reference
observer's queue policy, the event is considered delivered when any connected
+19 -4
View File
@@ -6,6 +6,7 @@
#include "../simple_repeater/CliUtil.h"
#include <WiFi.h>
#include <esp_wifi.h>
#include <esp_heap_caps.h>
#include <mbedtls/base64.h>
#include <mbedtls/platform.h>
#if defined(BOARD_HAS_PSRAM)
@@ -206,6 +207,12 @@ bool MQTTObserver::ready(const MQTTObserverConfig& config, size_t slot) const {
MQTTObserverConfigCodec::valid(config);
}
bool MQTTObserver::hasConnectHeadroom(bool secure) const {
return MQTTObserverConnectionPolicy::hasConnectHeadroom(
secure, heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL));
}
bool MQTTObserver::readRecord(File& file, MQTTObserverConfig& config) {
if (file.size() != MQTTObserverRecord::kRecordSize) return false;
if (file.read(_load_record, sizeof(_load_record)) != sizeof(_load_record)) return false;
@@ -643,10 +650,18 @@ void MQTTObserver::worker() {
runtime.state.store(STATE_RETRY, std::memory_order_relaxed);
}
if (!runtime.client_started && static_cast<int32_t>(now - runtime.next_connect_ms) >= 0) {
runtime.client->connect();
runtime.client_started = true;
runtime.attempt_started = now;
runtime.state.store(STATE_CONNECTING, std::memory_order_relaxed);
if (hasConnectHeadroom(secureUri(runtime.server_uri))) {
runtime.client->connect();
runtime.client_started = true;
runtime.attempt_started = now;
runtime.state.store(STATE_CONNECTING, std::memory_order_relaxed);
} else {
// A second TLS client started without a contiguous internal-heap
// allocation can abort the device. Defer and retry indefinitely
// (never a terminal state) until the heap recovers.
runtime.next_connect_ms = now + 30000;
runtime.state.store(STATE_RETRY, std::memory_order_relaxed);
}
}
State state = runtime.state.load(std::memory_order_relaxed);
any_connecting = any_connecting || state == STATE_CONNECTING || state == STATE_RETRY;
+1
View File
@@ -98,6 +98,7 @@ class MQTTObserver {
void worker();
void copyConfig(MQTTObserverConfig& config);
bool ready(const MQTTObserverConfig& config, size_t slot) const;
bool hasConnectHeadroom(bool secure) const;
bool configureClient(size_t slot, const MQTTObserverBrokerConfig& config);
bool createJwt(size_t slot, const MQTTObserverBrokerConfig& config, uint32_t& expires_at);
bool publishEvent(const Event& event, const MQTTObserverConfig& config);
@@ -47,6 +47,23 @@ inline bool jwtNeedsRenewal(int64_t epoch, uint32_t expiry) {
return expiry != 0 && epoch + 300 >= expiry;
}
// A TLS client needs a contiguous mbedTLS allocation on the internal heap;
// starting one without headroom aborts a non-PSRAM device, so connect() waits
// for the heap to recover instead of crashing. The secure thresholds follow
// the reference observers (roughly 60 KB free and one ~17 KB TLS record);
// plaintext brokers need far less. Keeping the decision pure lets the host
// suite cover it.
static const size_t kSecureFreeInternalBytes = 64u * 1024u;
static const size_t kSecureLargestInternalBytes = 18u * 1024u;
static const size_t kPlainFreeInternalBytes = 24u * 1024u;
static const size_t kPlainLargestInternalBytes = 8u * 1024u;
inline bool hasConnectHeadroom(bool secure, size_t free_internal, size_t largest_internal) {
const size_t free_needed = secure ? kSecureFreeInternalBytes : kPlainFreeInternalBytes;
const size_t block_needed = secure ? kSecureLargestInternalBytes : kPlainLargestInternalBytes;
return free_internal >= free_needed && largest_internal >= block_needed;
}
} // namespace MQTTObserverConnectionPolicy
namespace MQTTObserverQueuePolicy {
@@ -199,6 +199,23 @@ TEST(MQTTObserverConnectionPolicy, RenewsBeforeReconnectAsWellAsWhileConnected)
EXPECT_TRUE(MQTTObserverConnectionPolicy::jwtNeedsRenewal(2000, 1300));
}
TEST(MQTTObserverConnectionPolicy, RequiresInternalHeapHeadroomToConnect) {
using namespace MQTTObserverConnectionPolicy;
// Exactly at both secure thresholds is allowed.
EXPECT_TRUE(hasConnectHeadroom(true, kSecureFreeInternalBytes, kSecureLargestInternalBytes));
// One byte short of either secure threshold defers the connect.
EXPECT_FALSE(hasConnectHeadroom(true, kSecureFreeInternalBytes - 1, kSecureLargestInternalBytes));
EXPECT_FALSE(hasConnectHeadroom(true, kSecureFreeInternalBytes, kSecureLargestInternalBytes - 1));
// Plaintext brokers need less: the secure floor clears the plain thresholds.
EXPECT_TRUE(hasConnectHeadroom(false, kSecureFreeInternalBytes, kSecureLargestInternalBytes));
EXPECT_TRUE(hasConnectHeadroom(false, kPlainFreeInternalBytes, kPlainLargestInternalBytes));
EXPECT_FALSE(hasConnectHeadroom(false, kPlainFreeInternalBytes - 1, kPlainLargestInternalBytes));
EXPECT_FALSE(hasConnectHeadroom(false, kPlainFreeInternalBytes, kPlainLargestInternalBytes - 1));
// An empty heap never admits a client.
EXPECT_FALSE(hasConnectHeadroom(true, 0, 0));
EXPECT_FALSE(hasConnectHeadroom(false, 0, 0));
}
TEST(MQTTObserverQueuePolicy, RestartsStaleWindowAfterFlushAndHandlesWrap) {
uint32_t since = 0;
EXPECT_FALSE(MQTTObserverQueuePolicy::trackDisconnected(100, false, since));