Refactor EventsHandler to stream responses via chunked encoding

This commit is contained in:
Johannes Schmidt 2025-07-23 09:44:13 +02:00
parent 3832bb4296
commit d32f04a863

View File

@ -102,33 +102,27 @@ bool EventsHandler::HandleRequest(
EventsSubscriber subscriber (std::move(eventTypes), HttpUtility::GetLastParameter(params, "filter"), l_ApiQuery);
server.StartDetectClientSideShutdown();
IoBoundWorkSlot dontLockTheIoThread (yc);
response.result(http::status::ok);
response.set(http::field::content_type, "application/json");
response.StartStreaming(true);
// Send response headers before waiting for the first event.
response.Flush(yc);
IoBoundWorkSlot dontLockTheIoThread (yc);
http::async_write(stream, response, yc);
stream.async_flush(yc);
asio::const_buffer newLine ("\n", 1);
auto encoder = response.GetJsonEncoder();
for (;;) {
auto event (subscriber.GetInbox()->Shift(yc));
if (event) {
String body = JsonEncode(event);
boost::algorithm::replace_all(body, "\n", "");
asio::const_buffer payload (body.CStr(), body.GetLength());
asio::async_write(stream, payload, yc);
asio::async_write(stream, newLine, yc);
stream.async_flush(yc);
} else if (server.Disconnected()) {
if (response.IsClientDisconnected()) {
return true;
}
if (event) {
encoder.Encode(event);
response.body() << '\n';
response.Flush(yc);
}
}
}