Skip to content

Commit

Permalink
feat server: flush headers right away in streaming
Browse files Browse the repository at this point in the history
In case of response stream it makes sense to flush headers completely before starting to produce the body parts,
so a client can react to that earlier.

Tests: протестировано CI
0220c2f6b0019bb6621003e0cd9f4c759b082fb3

Pull Request resolved: userver-framework#488
  • Loading branch information
akhoroshev authored and itrofimow committed Feb 15, 2024
1 parent 3db1957 commit 0613405
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions core/src/server/http/http_response.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -358,9 +358,8 @@ std::size_t HttpResponse::SetBodyStreamed(
impl::OutputHeader(
header, USERVER_NAMESPACE::http::headers::kTransferEncoding, "chunked");

if (is_body_forbidden) {
header.append(kCrlf);
}
// headers end marker
header.append(kCrlf);

// send HTTP headers
size_t sent_bytes = socket.WriteAll(header.data(), header.size(), {});
Expand All @@ -373,19 +372,27 @@ std::size_t HttpResponse::SetBodyStreamed(

// Transmit HTTP response body
std::string body_part;
// First chunk must be sent without kCrlf
// because kCrlf was sent with headers
bool first_chunk_processed = false;
while (body_stream_->Pop(body_part)) {
if (body_part.empty()) {
LOG_DEBUG() << "Zero size body_part in http_response.cpp";
continue;
}

auto size = fmt::format("\r\n{:x}\r\n", body_part.size());
auto size = first_chunk_processed
? fmt::format("\r\n{:x}\r\n", body_part.size())
: fmt::format("{:x}\r\n", body_part.size());
sent_bytes += socket.WriteAll(
{{size.data(), size.size()}, {body_part.data(), body_part.size()}},
engine::Deadline{});

first_chunk_processed = true;
}

const constexpr std::string_view terminating_chunk{"\r\n0\r\n\r\n"};
const std::string_view terminating_chunk{
first_chunk_processed ? "\r\n0\r\n\r\n" : "0\r\n\r\n"};
sent_bytes +=
socket.WriteAll(terminating_chunk.data(), terminating_chunk.size(), {});

Expand Down

0 comments on commit 0613405

Please sign in to comment.