ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
event_source.cpp
Go to the documentation of this file.
1#include "event_source.h"
2#if defined(USE_WEBSERVER) && (defined(USE_ESP32) || defined(USE_ARDUINO))
3
4#include <algorithm>
5#include <cstring>
6
8#include "esphome/core/hal.h"
10#include "esphome/core/log.h"
11#include "web_server.h"
12
14
15ESPHOME_LOG_TAG(TAG, "web_server");
16
17// Only prepare_json_() may hold the JSON arena: every other frame in this file is capped below one
18// arena. Measured at -Os on GCC 14; newer toolchains stay checked on purpose, older ones skip it.
19#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
20#pragma GCC diagnostic error "-Wstack-usage=2048"
21#endif
22
23void AsyncEventSource::handle_request(AsyncWebServerRequest *request, WebServer *ws) {
24 // Network context: start the stream and park the session; the main loop does the rest. On an HTTPS server the
25 // ESP-IDF begin() answers 501 and the session is freed unattached.
26 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,clang-analyzer-cplusplus.NewDeleteLeaks)
27 auto *rsp = new AsyncEventSourceResponse(ws);
29 this->push_pending_(rsp);
30}
31
33 // Read first: once published, the main loop may free the session
34 WebServer *ws = rsp->web_server_;
35 {
37 rsp->next_ = this->pending_sessions_.load(std::memory_order_relaxed);
38 this->pending_sessions_.store(rsp, std::memory_order_release);
39 }
41}
42
43// clang-analyzer traces a false-positive leak path from loop() through
44// adopt_pending_sessions_main_loop_() into start_session_main_loop_() and
45// finally ArduinoJson. Suppress along the entire in-our-code call chain.
46// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks)
48 // Fast path: one atomic load per tick. Slow path is out-of-line on connect.
49 if (this->pending_sessions_.load(std::memory_order_acquire) != nullptr) {
50 this->adopt_pending_sessions_main_loop_();
51 }
52
53 // The network side only marks a session dead; the main loop frees it, so nothing races the free
54 for (AsyncEventSourceResponse **link = &this->sessions_; *link != nullptr;) {
55 auto *ses = *link;
56 if (ses->safe_to_delete()) {
57 *link = ses->next_;
58 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
59 } else {
60 ses->loop();
61 link = &ses->next_;
62 }
63 }
64 // A session still waiting for its connection keeps the loop alive too
65 return this->sessions_ != nullptr || this->pending_sessions_.load(std::memory_order_acquire) != nullptr;
66}
67
68void AsyncEventSource::adopt_pending_sessions_main_loop_() {
70 {
72 // Plain load and store under the guard: RP2040 has no atomic read-modify-write
73 incoming = this->pending_sessions_.load(std::memory_order_acquire);
74 this->pending_sessions_.store(nullptr, std::memory_order_relaxed);
75 }
76 while (incoming != nullptr) {
77 auto *rsp = incoming;
78 incoming = rsp->next_;
79 // Already disconnected? Drop it; skip session start on a dead session.
80 if (rsp->safe_to_delete()) {
81 delete rsp; // NOLINT(cppcoreguidelines-owning-memory)
82 continue;
83 }
84 // The server attaches a stream after the creating handler returns (or frees it), so it stays pending until then
85 if (!rsp->is_attached()) {
87 rsp->next_ = this->pending_sessions_.load(std::memory_order_relaxed);
88 this->pending_sessions_.store(rsp, std::memory_order_release);
89 continue;
90 }
91 rsp->next_ = this->sessions_;
92 this->sessions_ = rsp;
94 }
95}
96// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
97
98void AsyncEventSource::try_send_nodefer(const char *message, size_t message_len, const char *event, uint32_t id,
99 uint32_t reconnect) {
100 for (auto *ses = this->sessions_; ses != nullptr; ses = ses->next_) {
101 if (ses->is_connected()) {
102 ses->try_send_nodefer(message, message_len, event, id, reconnect);
103 }
104 }
105}
106
107void AsyncEventSource::deferrable_send_state(void *source, message_generator_t *message_generator) {
108 for (auto *ses = this->sessions_; ses != nullptr; ses = ses->next_) {
109 if (ses->is_connected()) {
110 ses->deferrable_send_state(source, false, message_generator);
111 }
112 }
113}
114
115// Network context only. start_session_main_loop_() sends the greeting and starts the iterator.
116AsyncEventSourceResponse::AsyncEventSourceResponse(WebServer *ws) : web_server_(ws), entities_iterator_(this) {}
117static_assert(web_server_base::stream_head_iov_count(SSE_HEADERS_COUNT + WEB_SERVER_DEFAULT_HEADERS_COUNT) <=
118 web_server_base::STREAM_HEAD_MAX_IOV,
119 "the event stream head must go out in one write");
120
121// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
123 auto *ws = this->web_server_;
124
125 // The tcp send buffer is empty on connect. A refusal is a closing session or a failed tail
126 // allocation; nothing retries the greeting, so close and let the client reconnect.
127 auto message = ws->get_config_json();
128 if (!this->try_send_nodefer(message.c_str(), message.size(), "ping", millis(), 30000)) {
129 // A stream already closing (its head did not go out whole) is not a failed greeting
130 if (!this->is_closing()) {
131 ESP_LOGW(TAG, "Config not sent to stream %d", this->log_id());
132 }
133 this->close();
134 return;
135 }
136
137#ifdef USE_WEBSERVER_SORTING
138 for (const auto &group : SORTING_GROUPS) {
139 json::JsonBuilder builder;
140 JsonObject root = builder.root();
141 root[ESPHOME_F("name")] = json::linked(group.name);
142 root[ESPHOME_F("sorting_weight")] = group.weight;
143 message = builder.serialize();
144
145 // Groups the socket does not take yet queue in the tail behind the ping. A refusal means the
146 // tail is full or the stream is closing; the remaining groups are not sent. The session stays
147 // up on purpose: partial grouping beats a reconnect loop on a slow link.
148 if (!this->try_send_nodefer(message.c_str(), message.size(), "sorting_group")) {
149 // A stream closing mid-greeting is not a failed send
150 if (!this->is_closing()) {
151 ESP_LOGW(TAG, "Sorting groups not sent to stream %d", this->log_id());
152 }
153 break;
154 }
155 }
156#endif
157
158 this->entities_iterator_.begin(ws->include_internal_);
159}
160// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
161
162// helper for allowing only unique entries in the queue
164 DeferredEvent item(source, message_generator);
165
166 // Use range-based for loop instead of std::find_if to reduce template instantiation overhead and binary size
167 for (auto &event : this->deferred_queue_) {
168 if (event == item) {
169 return; // Already in queue, no need to update since items are equal
170 }
171 }
172 this->deferred_queue_.push_back(item);
173}
174
176 if (this->is_closing()) {
177 return;
178 }
179 while (!deferred_queue_.empty()) {
180 DeferredEvent &de = deferred_queue_.front();
181 if (this->send_json_(de.source_, de.message_generator_)) {
182 if (this->is_closing() || deferred_queue_.empty()) {
183 return;
184 }
185 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
186 deferred_queue_.erase(deferred_queue_.begin());
187 } else {
188 break;
189 }
190 }
191}
192
194 std::vector<DeferredEvent>().swap(this->deferred_queue_);
195 this->tail_.reset();
196 this->tail_cap_ = 0;
197 this->tail_len_ = 0;
198 this->tail_sent_ = 0;
199}
200
202 if (this->sending_ || this->is_closing() || this->tail_len_ == 0) {
203 return;
204 }
205 SendGuard guard{*this};
206
207 const size_t remaining = this->tail_len_ - this->tail_sent_;
208 const ssize_t sent = this->write(this->tail_.get() + this->tail_sent_, remaining);
209 if (sent <= 0) {
210 return; // write() owns the stall clock and the close
211 }
212 this->no_memory_logged_ = false;
213 this->tail_sent_ += sent;
215 ESP_LOGV(TAG, "Partial send: %zd/%zu bytes (total: %u/%u)", sent, remaining, this->tail_sent_, this->tail_len_);
216 return;
217 }
218 // Fully sent; the storage stays for the next stall
219 this->tail_len_ = 0;
220}
221
223 if (this->tail_cap_ >= len) {
224 return true;
225 }
226 if (len > TAIL_MAX_SIZE) {
227 return false;
228 }
229 // Nothing is pending while the tail grows, so free the old block first. PREFER_INTERNAL keeps
230 // the tail where plain new put it.
231 this->tail_.reset();
233 this->tail_cap_ = this->tail_ ? len : 0;
234 return this->tail_cap_ != 0;
235}
236
237bool AsyncEventSourceResponse::stash_chunk_(const char *prefix, size_t prefix_len, const char *message,
238 size_t message_len, size_t total, size_t sent) {
239 // A log event of nothing but line breaks is the largest chunk; reserve_tail_() must never
240 // refuse it for size, only for memory
242 "the log cut in web_server.h must keep a worst case log event inside the tail ceiling");
243 if (!this->reserve_tail_(total)) {
244 if (sent != 0) {
245 // Part of the chunk is on the wire, so the stream is broken and the client has to go
246 ESP_LOGW(TAG, "Cannot buffer a %zu byte chunk, closing", total);
247 this->close();
248 } else {
249 this->tail_alloc_failed_(total); // nothing on the wire, the caller retries on the stall clock
250 }
251 return false;
252 }
253 copy_chunk(this->tail_.get(), prefix, prefix_len, message, message_len);
254 this->tail_len_ = total;
255 this->tail_sent_ = sent;
256 return true;
257}
258
259bool AsyncEventSourceResponse::append_chunk_(const char *prefix, size_t prefix_len, const char *message,
260 size_t message_len, size_t total) {
261 const size_t cap = tail_queue_cap(this->tail_len_ - this->tail_sent_ + total, this->tail_cap_, TAIL_QUEUE_SIZE);
262 if (cap == 0) {
263 return false;
264 }
265 uint8_t *src = this->tail_.get();
267 if (cap != this->tail_cap_) {
268 // Kept once grown, so a burst does not allocate per event
270 if (!grown) {
271 return false;
272 }
273 }
274 uint8_t *dst = grown ? grown.get() : src;
275 this->tail_len_ = queue_chunk(dst, src, this->tail_len_, this->tail_sent_, prefix, prefix_len, message, message_len);
276 this->tail_sent_ = 0;
277 if (grown) {
278 this->tail_ = std::move(grown);
279 this->tail_cap_ = cap;
280 }
281 return true;
282}
283
285 AsyncStreamResponse::loop();
286 // A client that left may wait for httpd's queued work before it can be freed; stop filling it meanwhile
287 if (this->is_closing() || !this->is_connected()) {
288 if (this->tail_cap_ != 0 || this->deferred_queue_.capacity() != 0) {
289 this->release_buffers_();
290 }
291 return;
292 }
293 drain_tail_();
295 if (this->is_closing())
296 return;
297 // One step per loop; refusals retry next pass
299}
300
301#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
302#pragma GCC diagnostic push
303#pragma GCC diagnostic ignored "-Wstack-usage=" // the one frame that holds the JSON arena
304#endif
305AsyncEventSourceResponse::JsonPrepareResult AsyncEventSourceResponse::prepare_json_(void *source,
306 message_generator_t *generator,
307 char *buffer, size_t *size_out) {
308 // Log lines emitted while the generator runs are dropped for this session: on the large path they would fill
309 // tail_ before it is overwritten, and on the small path they would go out ahead of the event being built.
310 SendGuard guard{*this};
311#ifdef USE_JSON_ARENA
313 json::JsonBuilder builder(&arena);
314#else
315 json::JsonBuilder builder;
316#endif
317 generator(this->web_server_, source, builder);
319 if (*size_out < JSON_BUF_SIZE) {
321 }
322
323 char prefix[PREFIX_BUF_SIZE];
324 const size_t prefix_len = build_chunk_prefix(prefix, sizeof(prefix), "state", 0, 0, true);
325
326 // Nothing reaches the wire until the complete document and its framing are owned by the caller.
327 size_t json_len = 0;
328 size_t cap = std::max<size_t>(JSON_BUF_SIZE * 2, this->tail_cap_);
329 for (;;) {
330 if (!this->reserve_tail_(cap)) {
331 *size_out = cap;
333 }
334 const size_t room = cap - prefix_len - SSE_SUFFIX_LEN;
335 json_len = builder.serialize_to(reinterpret_cast<char *>(this->tail_.get()) + prefix_len, room);
336 if (json_len < room) {
337 break;
338 }
339 if (cap >= TAIL_MAX_SIZE) {
340 *size_out = room;
342 }
343 cap = std::min<size_t>(cap * 2, TAIL_MAX_SIZE);
344 }
345
346 const size_t total = prefix_len + json_len + SSE_SUFFIX_LEN;
347 write_chunk_header(prefix, total - CHUNK_HDR_LEN - CHUNK_END_LEN);
348 uint8_t *dst = this->tail_.get();
349 std::memcpy(dst, prefix, prefix_len);
350 progmem_memcpy(dst + prefix_len + json_len, SSE_SUFFIX, SSE_SUFFIX_LEN);
351 this->tail_len_ = total;
352 this->tail_sent_ = 0;
354}
355#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
356#pragma GCC diagnostic pop
357#endif
358
360 if (!this->drain_if_idle_() || this->tail_len_ != 0) {
361 return false;
362 }
363 char buffer[JSON_BUF_SIZE];
364 size_t size;
365 const auto result = this->prepare_json_(source, generator, buffer, &size);
366 switch (result) {
368 return this->try_send_nodefer(buffer, size, "state");
370 this->drain_tail_();
371 return true;
373 SendGuard guard{*this};
374 this->tail_alloc_failed_(size);
375 return false;
376 }
378 SendGuard guard{*this};
379 ESP_LOGW(TAG, "State event does not fit %zu bytes, dropped", size);
380 this->tail_.reset();
381 this->tail_cap_ = 0;
382 this->stall_.clear();
383 this->no_memory_logged_ = false;
384 return true;
385 }
386 }
387 return false;
388}
389
391 // Same stall clock as a socket that stops draining, so a session cannot retry forever. A refused write may
392 // already have started it, so the warning keeps its own flag.
393 if (!this->no_memory_logged_) {
394 this->no_memory_logged_ = true;
395 ESP_LOGW(TAG, "No memory for a %zu byte chunk", cap);
396 }
397 this->stall_or_close_(LOG_STR("without memory"));
398}
399
401 if (this->sending_ || !this->is_connected() || this->is_closing()) {
402 return false;
403 }
404 drain_tail_();
405 return !this->is_closing();
406}
407
408bool AsyncEventSourceResponse::try_send_nodefer(const char *message, size_t message_len, const char *event, uint32_t id,
409 uint32_t reconnect) {
410 if (!this->drain_if_idle_()) {
411 return false;
412 }
413 SendGuard guard{*this};
414
415 // Everything after the prefix goes out straight from the caller's buffer
416 char prefix[PREFIX_BUF_SIZE];
417 const size_t prefix_len = build_chunk_prefix(prefix, sizeof(prefix), event, id, reconnect, message != nullptr);
418 if (message == nullptr && prefix_len == CHUNK_HDR_LEN) {
419 return true; // Match ESPAsyncWebServer: nothing to send
420 }
421 if (prefix_len >= PREFIX_BUF_SIZE - 1) {
422 // The appenders truncate silently, which would put a malformed event on the wire
423 ESP_LOGW(TAG, "Event name too long, dropped");
424 return true;
425 }
426
427 // Gather list: the prefix, then the data lines and their separators from the message
428 struct Gather {
429 web_server_base::StreamIovec iov[MAX_SEND_IOV]; // left uninitialized on purpose
430 int iovcnt{1};
431 size_t total{0};
432 bool fits{true};
433 } g;
434 g.total = prefix_len;
436 message, message_len,
437 [](void *ctx, const char *piece, size_t len) {
438 auto &g = *static_cast<Gather *>(ctx);
439 g.total += len;
440 if (len == 0) {
441 return;
442 }
443 if (g.iovcnt == MAX_SEND_IOV) {
444 g.fits = false;
445 return;
446 }
447 g.iov[g.iovcnt++] = {const_cast<char *>(piece), len};
448 },
449 &g);
450 // The header and the terminator are not part of the chunk length
451 write_chunk_header(prefix, g.total - CHUNK_HDR_LEN - CHUNK_END_LEN);
452 g.iov[0] = {prefix, prefix_len};
453
454 if (this->tail_len_ != 0) {
455 // Behind an unsent chunk (on ESP8266, one waiting for its ACK): queue it rather than drop it
456 return this->append_chunk_(prefix, prefix_len, message, message_len, g.total);
457 }
458 // A message with more lines than the list holds skips straight to the tail
459 const ssize_t sent = g.fits ? this->write(g.iov, g.iovcnt) : 0;
460 if (sent < 0) {
461 return false;
462 }
463 if (sent > 0) {
464 this->no_memory_logged_ = false;
465 }
466 if (static_cast<size_t>(sent) == g.total) {
467 return true;
468 }
469 // The caller's buffers do not outlive this call, so keep the chunk and continue from loop()
470 return this->stash_chunk_(prefix, prefix_len, message, message_len, g.total, sent);
471}
472
473void AsyncEventSourceResponse::deferrable_send_state(void *source, bool detail_all,
474 message_generator_t *message_generator) {
475 // Let the detail_all listing finish before bare state events, so the web UI never shows unnamed entries and
476 // initial connect sends less
477 if (!detail_all && !this->entities_iterator_.completed())
478 return;
479
480 drain_tail_();
482
483 if (this->is_closing()) {
484 return;
485 }
486
487 if (this->tail_len_ != 0 || !deferred_queue_.empty()) {
488 // outgoing event buffer or deferred queue still not empty which means downstream tcp send buffer full, no point
489 // trying to send first
490 deq_push_back_with_dedup_(source, message_generator);
491 } else {
492 // A send error closes the session and clears the queue; nothing is queued after that
493 if (!this->send_json_(source, message_generator) && !this->is_closing()) {
494 deq_push_back_with_dedup_(source, message_generator);
495 }
496 }
497}
498
499} // namespace esphome::web_server
500
501#endif // USE_WEBSERVER && (USE_ESP32 || USE_ARDUINO)
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void begin(bool include_internal=false)
ESPHOME_ALWAYS_INLINE void try_advance(size_t max_steps)
Run up to max_steps iteration steps; stops early when iteration completes or a callback refuses (that...
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2670
RAMUniquePtr< T[]> make_unique_array_for_overwrite(size_t n)
n elements left uninitialized, as std::make_unique_for_overwrite does; empty on exhaustion,...
Definition helpers.h:2743
Bump allocator over a fixed buffer for a document built and serialized in one scope.
Definition json_util.h:224
Builder class for creating JSON documents without lambdas.
Definition json_util.h:286
size_t serialize_to(char *buf, size_t cap)
Serialize into a caller owned buffer.
Definition json_util.cpp:80
SerializationBuffer serialize()
Serialize the JSON document to a SerializationBuffer (stack-first allocation) Uses 512-byte stack buf...
Definition json_util.cpp:96
void handle_request(AsyncWebServerRequest *request, WebServer *ws)
void push_pending_(AsyncEventSourceResponse *rsp)
std::atomic< AsyncEventSourceResponse * > pending_sessions_
AsyncEventSourceResponse * sessions_
bool loop()
Returns true if there are sessions remaining (including pending cleanup).
void deferrable_send_state(void *source, message_generator_t *message_generator)
void try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
std::vector< DeferredEvent > deferred_queue_
bool try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
JsonPrepareResult message_generator_t * generator
void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator)
bool append_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total)
JsonPrepareResult message_generator_t char * buffer
void deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator)
bool stash_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total, size_t sent)
JsonPrepareResult message_generator_t char size_t * size_out
bool send_json_(void *source, message_generator_t *generator)
This class allows users to create a web server with their ESP nodes.
Definition web_server.h:121
json::SerializationBuffer get_config_json()
Return the webserver configuration as JSON.
void close()
Main loop. Closes the connection; safe to call more than once.
ssize_t write(StreamIovec *iov, int iovcnt)
Main loop.
bool is_connected() const
The client is still connected.
int log_id() const
An id for log lines only.
const LogString * message
Definition component.cpp:35
uint32_t buffer
Definition gif.cpp:50
__int64 ssize_t
Definition httplib.h:178
JsonString linked(const char *s)
Definition json_util.h:26
constexpr size_t stream_head_iov_count(size_t header_count)
Pieces in a head: 4 for the status line and Content-Type, 4 per header, the blank line and the body.
Definition stream_head.h:64
size_t queue_chunk(uint8_t *dst, const uint8_t *src, size_t len, size_t sent, const char *prefix, size_t prefix_len, const char *message, size_t message_len)
const web_server_base::HttpHeader SSE_HEADERS[SSE_HEADERS_COUNT]
Definition sse_chunk.cpp:24
const char SSE_STATUS[]
Definition sse_chunk.cpp:14
void for_each_chunk_piece(const char *message, size_t message_len, ChunkPieceSink sink, void *ctx)
Definition sse_chunk.cpp:30
size_t copy_chunk(uint8_t *dst, const char *prefix, size_t prefix_len, const char *message, size_t message_len)
Definition sse_chunk.cpp:77
constexpr size_t SSE_SEP_LEN
Definition sse_chunk.h:25
ESPHOME_LOG_TAG(TAG, "web_server")
const std::array< SortingGroup, WEBSERVER_SORTING_GROUP_COUNT > SORTING_GROUPS
size_t tail_queue_cap(size_t need, size_t cap, size_t max)
Definition sse_chunk.cpp:92
const char SSE_CONTENT_TYPE[]
Definition sse_chunk.cpp:15
constexpr size_t LOG_EVENT_MAX_LEN
Definition web_server.h:45
const char SSE_SUFFIX[]
Definition sse_chunk.cpp:13
constexpr size_t SSE_HEADERS_COUNT
Definition sse_chunk.h:34
void(WebServer *, void *, json::JsonBuilder &) message_generator_t
const char SSE_FIRST_CHUNK[]
Definition sse_chunk.cpp:16
size_t build_chunk_prefix(char *buf, size_t size, const char *event, uint32_t id, uint32_t reconnect, bool with_data)
Definition sse_chunk.cpp:58
constexpr size_t SSE_SUFFIX_LEN
Definition sse_chunk.h:28
std::unique_ptr< T, RAMDeleter< T > > RAMUniquePtr
unique_ptr over RAMAllocator storage
Definition helpers.h:2659
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:44
const void * src
Definition hal.h:68
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
message_generator_t * message_generator_
One entry of the gather list AsyncStreamResponse::write() takes; the TCP libraries take plain buffers...
esp_err_t result