Net: add duplex HTTP response streaming (closes #37)

This commit is contained in:
faumaray committed 2026-12-03 16:03:31 +03:00
1 parent 7cfd30e550
commit a6dd7fd927
3 files changed
+1609 -3

No files matched your search

+756 -3
View File
@@ -867,6 +867,588 @@ namespace Void::Net
return written_total;
}
struct ResponseWriter::State {
int fd{-1};
const std::atomic<bool>* stopping{nullptr};
std::atomic<bool> cancel_requested{false};
std::atomic<bool> head_attempted{false};
std::atomic<bool> begun{false};
std::atomic<bool> finished{false};
std::atomic<bool> invalid{false};
std::atomic<bool> chunked{false};
std::atomic<bool> bodyless{false};
std::atomic<bool> fixed_length{false};
std::atomic<bool> close_delimited{false};
std::atomic<bool> has_content_length{false};
std::atomic<bool> keep_alive{true};
std::atomic<std::uint64_t> content_length{0};
std::atomic<std::uint64_t> accepted{0};
std::atomic<std::uint64_t> sent{0};
std::atomic<std::size_t> pending_bytes{0};
std::atomic<std::chrono::milliseconds::rep> write_timeout_ms{
std::chrono::seconds{30}.count()};
std::mutex io_mutex{};
std::string pending{};
std::size_t max_pending{64ULL * 1024};
bool head_request{false};
bool http10{false};
std::stop_source stop_source{};
[[nodiscard]] bool stopped() const noexcept
{
return cancel_requested.load(std::memory_order_acquire) ||
(stopping != nullptr &&
stopping->load(std::memory_order_acquire));
}
void request_stop() noexcept
{
(void)stop_source.request_stop();
}
};
namespace
{
[[nodiscard]] Void::Result::Result<void>
writer_send_all(ResponseWriter::State& state,
std::span<const std::byte> data)
{
const auto timeout = std::chrono::milliseconds{
state.write_timeout_ms.load(std::memory_order_acquire)};
const auto deadline = std::chrono::steady_clock::now() + timeout;
std::size_t off = 0;
while (off < data.size()) {
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
const auto now = std::chrono::steady_clock::now();
if (timeout > std::chrono::milliseconds::zero() &&
now >= deadline) {
return std::unexpected{make_net_error(
NetErrorCode::timeout,
"Net::ResponseWriter: write timeout")};
}
int wait_ms = 100;
if (timeout > std::chrono::milliseconds::zero()) {
const auto rem = std::chrono::duration_cast<
std::chrono::milliseconds>(deadline - now)
.count();
wait_ms = static_cast<int>(std::clamp<long long>(rem, 1, 100));
}
struct pollfd pfd{};
pfd.fd = state.fd;
pfd.events = POLLOUT;
const int pr = ::poll(&pfd, 1, wait_ms);
if (pr < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net::ResponseWriter: poll failed")};
}
if (pr == 0) {
continue;
}
const ssize_t n = ::send(
state.fd,
reinterpret_cast<const char*>(data.data()) + off,
data.size() - off, MSG_NOSIGNAL);
if (n < 0) {
if (errno == EINTR || errno == EAGAIN ||
errno == EWOULDBLOCK) {
continue;
}
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::ResponseWriter: send failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
if (n == 0) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net::ResponseWriter: peer closed connection")};
}
off += static_cast<std::size_t>(n);
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
writer_flush(ResponseWriter::State& state)
{
if (state.pending.empty()) {
return {};
}
auto res = writer_send_all(
state, std::as_bytes(std::span{state.pending.data(),
state.pending.size()}));
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
state.pending.clear();
state.pending_bytes.store(0, std::memory_order_release);
state.sent.store(state.accepted.load(std::memory_order_acquire),
std::memory_order_release);
return {};
}
[[nodiscard]] Void::Result::Result<void>
writer_require_active(const std::shared_ptr<ResponseWriter::State>& s)
{
if (!s || s->invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
return {};
}
} // namespace
bool ResponseWriter::valid() const noexcept
{
return m_state != nullptr &&
!m_state->invalid.load(std::memory_order_acquire);
}
bool ResponseWriter::begun() const noexcept
{
return m_state != nullptr &&
m_state->begun.load(std::memory_order_acquire);
}
bool ResponseWriter::finished() const noexcept
{
return m_state != nullptr &&
m_state->finished.load(std::memory_order_acquire);
}
bool ResponseWriter::cancelled() const noexcept
{
return m_state == nullptr ||
m_state->cancel_requested.load(std::memory_order_acquire) ||
(m_state->stopping != nullptr &&
m_state->stopping->load(std::memory_order_acquire));
}
bool ResponseWriter::chunked() const noexcept
{
return m_state != nullptr &&
m_state->chunked.load(std::memory_order_acquire);
}
std::optional<std::uint64_t> ResponseWriter::content_length() const noexcept
{
if (m_state == nullptr ||
!m_state->has_content_length.load(std::memory_order_acquire)) {
return std::nullopt;
}
return m_state->content_length.load(std::memory_order_acquire);
}
std::uint64_t ResponseWriter::bytes_accepted() const noexcept
{
return m_state != nullptr
? m_state->accepted.load(std::memory_order_acquire)
: 0;
}
std::uint64_t ResponseWriter::bytes_sent() const noexcept
{
return m_state != nullptr
? m_state->sent.load(std::memory_order_acquire)
: 0;
}
std::size_t ResponseWriter::buffered_bytes() const noexcept
{
return m_state != nullptr
? m_state->pending_bytes.load(std::memory_order_acquire)
: 0;
}
std::stop_token ResponseWriter::stop_token() const noexcept
{
return m_state != nullptr ? m_state->stop_source.get_token()
: std::stop_token{};
}
void ResponseWriter::cancel() noexcept
{
if (m_state) {
m_state->cancel_requested.store(true, std::memory_order_release);
m_state->request_stop();
}
}
void ResponseWriter::set_write_timeout(
std::chrono::milliseconds timeout) noexcept
{
if (m_state) {
m_state->write_timeout_ms.store(timeout.count(),
std::memory_order_release);
}
}
std::chrono::milliseconds ResponseWriter::write_timeout() const noexcept
{
return std::chrono::milliseconds{
m_state != nullptr
? m_state->write_timeout_ms.load(std::memory_order_acquire)
: std::chrono::seconds{30}.count()};
}
Void::Result::Result<void>
ResponseWriter::begin(std::uint16_t status, std::vector<Header> headers)
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return active;
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already started")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
if (status < 100 || status > 599) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid status code")};
}
const bool bodyless = state.head_request ||
(status >= 100 && status < 200) || status == 204 ||
status == 304;
std::optional<std::uint64_t> content_length;
std::optional<std::string> transfer_encoding;
bool connection_close = false;
std::string extra_headers;
for (const auto& header : headers) {
if (!is_valid_token(header.name) ||
has_crlf_or_nul(header.name) ||
has_crlf_or_nul(header.value)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid response header")};
}
if (equal_ascii_ci(header.name, "Content-Length")) {
std::uint64_t parsed = 0;
if (!parse_u64_decimal(trim_ows(header.value), parsed)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid Content-Length")};
}
if (content_length.has_value() &&
*content_length != parsed) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: conflicting Content-Length")};
}
content_length = parsed;
continue;
}
if (equal_ascii_ci(header.name, "Transfer-Encoding")) {
if (transfer_encoding.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: duplicate Transfer-Encoding")};
}
transfer_encoding = header.value;
continue;
}
if (equal_ascii_ci(header.name, "Connection")) {
if (contains_ascii_ci(header.value, "close")) {
connection_close = true;
}
continue;
}
extra_headers += header.name;
extra_headers += ": ";
extra_headers += header.value;
extra_headers += "\r\n";
}
if (transfer_encoding.has_value() &&
!equal_ascii_ci(trim_ows(*transfer_encoding), "chunked")) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: unsupported Transfer-Encoding")};
}
if (transfer_encoding.has_value() && content_length.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: ambiguous response framing")};
}
if (bodyless && transfer_encoding.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response with "
"Transfer-Encoding")};
}
if (bodyless && content_length.has_value() && !state.head_request &&
status != 304) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response with "
"Content-Length")};
}
bool chunked = false;
bool fixed = false;
bool close_delimited = false;
if (!bodyless) {
if (transfer_encoding.has_value()) {
chunked = true;
} else if (content_length.has_value()) {
fixed = true;
} else if (state.http10) {
close_delimited = true;
} else {
chunked = true;
}
}
bool keep = state.keep_alive.load(std::memory_order_acquire) &&
!close_delimited;
if (connection_close) {
keep = false;
}
std::string head =
std::format("HTTP/1.1 {} {}\r\n", status, reason_phrase(status));
head += extra_headers;
if (bodyless) {
if (content_length.has_value()) {
head += std::format("Content-Length: {}\r\n",
*content_length);
}
} else if (fixed) {
head += std::format("Content-Length: {}\r\n", *content_length);
} else if (chunked) {
head += "Transfer-Encoding: chunked\r\n";
}
head += std::format("Connection: {}\r\n\r\n",
keep ? "keep-alive" : "close");
state.head_attempted.store(true, std::memory_order_release);
auto sent_head = writer_send_all(
state, std::as_bytes(std::span{head.data(), head.size()}));
if (!sent_head.has_value()) {
return std::unexpected{std::move(sent_head.error())};
}
state.bodyless.store(bodyless, std::memory_order_release);
state.chunked.store(chunked, std::memory_order_release);
state.fixed_length.store(fixed, std::memory_order_release);
state.close_delimited.store(close_delimited,
std::memory_order_release);
state.keep_alive.store(keep, std::memory_order_release);
if (content_length.has_value()) {
state.content_length.store(*content_length,
std::memory_order_release);
state.has_content_length.store(true,
std::memory_order_release);
}
state.begun.store(true, std::memory_order_release);
return {};
}
Void::Result::Result<std::size_t>
ResponseWriter::write_some(std::span<const std::byte> bytes)
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return std::unexpected{std::move(active.error())};
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (!state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response not started")};
}
if (state.finished.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already finished")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
if (bytes.empty()) {
return std::size_t{0};
}
if (state.bodyless.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response cannot carry a body")};
}
auto flushed = writer_flush(state);
if (!flushed.has_value()) {
return std::unexpected{std::move(flushed.error())};
}
const std::size_t max_pending = state.max_pending;
std::size_t capacity = max_pending;
if (state.chunked.load(std::memory_order_acquire)) {
// Leave room for the chunk size line and trailing CRLF.
capacity = max_pending > 32 ? max_pending - 32 : 1;
}
std::size_t accepted = std::min(bytes.size(), capacity);
if (accepted == 0) {
return std::size_t{0};
}
if (state.fixed_length.load(std::memory_order_acquire)) {
const std::uint64_t total =
state.content_length.load(std::memory_order_acquire);
const std::uint64_t written =
state.accepted.load(std::memory_order_acquire);
const std::uint64_t remaining =
total > written ? total - written : 0;
if (accepted > remaining) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: fixed-length body overflow")};
}
}
if (state.chunked.load(std::memory_order_acquire)) {
state.pending += std::format("{:x}\r\n", accepted);
state.pending.append(
reinterpret_cast<const char*>(bytes.data()), accepted);
state.pending += "\r\n";
} else {
state.pending.append(
reinterpret_cast<const char*>(bytes.data()), accepted);
}
state.pending_bytes.store(state.pending.size(),
std::memory_order_release);
state.accepted.fetch_add(accepted, std::memory_order_acq_rel);
auto after = writer_flush(state);
if (!after.has_value()) {
return std::unexpected{std::move(after.error())};
}
return accepted;
}
Void::Result::Result<void> ResponseWriter::finish()
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return active;
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (!state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response not started")};
}
if (state.finished.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already finished")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
auto flushed = writer_flush(state);
if (!flushed.has_value()) {
return std::unexpected{std::move(flushed.error())};
}
if (state.chunked.load(std::memory_order_acquire)) {
const std::string_view terminal = "0\r\n\r\n";
auto res = writer_send_all(
state, std::as_bytes(std::span{terminal.data(),
terminal.size()}));
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
} else if (state.fixed_length.load(std::memory_order_acquire)) {
const std::uint64_t total =
state.content_length.load(std::memory_order_acquire);
const std::uint64_t written =
state.accepted.load(std::memory_order_acquire);
if (written != total) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::ResponseWriter: fixed-length body incomplete")};
}
}
state.finished.store(true, std::memory_order_release);
state.request_stop();
return {};
}
struct ResponseWriterAccess {
static ResponseWriter
make(std::shared_ptr<ResponseWriter::State> state)
{
return ResponseWriter{std::move(state)};
}
};
namespace
{
struct StreamingRoute {
@@ -876,6 +1458,13 @@ namespace Void::Net
StreamingRouteHandler handler;
};
struct DuplexRoute {
Method method;
std::string pattern;
std::vector<std::string> segments;
DuplexRouteHandler handler;
};
struct WorkerEntry {
std::uint64_t id{0};
std::atomic<int> client_fd{-1};
@@ -1023,6 +1612,7 @@ namespace Void::Net
mutable std::shared_mutex stream_mutex{};
std::vector<StreamingRoute> streaming_routes{};
std::vector<DuplexRoute> duplex_routes{};
std::vector<WebSocketRoute> ws_routes{};
std::atomic<std::uint64_t> next_ws_id{1};
@@ -1092,6 +1682,35 @@ namespace Void::Net
best->handler, std::move(best_params)};
}
[[nodiscard]] std::optional<
std::pair<DuplexRouteHandler, RouteParameters>>
match_duplex(Method m, std::string_view path_view) const
{
const auto segments = split_path(path_view);
std::shared_lock lock{stream_mutex};
const DuplexRoute* best = nullptr;
RouteParameters best_params;
for (const auto& r : duplex_routes) {
if (r.method != m) {
continue;
}
auto matched = match_segments(r.segments, segments);
if (!matched.has_value()) {
continue;
}
if (best == nullptr ||
more_specific_route(r.segments, best->segments)) {
best = &r;
best_params = std::move(*matched);
}
}
if (best == nullptr) {
return std::nullopt;
}
return std::pair<DuplexRouteHandler, RouteParameters>{
best->handler, std::move(best_params)};
}
[[nodiscard]] std::optional<WebSocketRoute>
match_websocket(std::string_view path_view) const
{
@@ -1257,6 +1876,13 @@ namespace Void::Net
methods.push_back(r.method);
}
}
for (const auto& r : duplex_routes) {
if (match_segments(r.segments, segments).has_value() &&
std::ranges::find(methods, r.method) ==
methods.end()) {
methods.push_back(r.method);
}
}
}
return methods;
}
@@ -1594,10 +2220,13 @@ namespace Void::Net
break;
}
// 4. Check streaming route vs buffered Router.
// 4. Check duplex/streaming routes vs buffered Router.
auto duplex_match = match_duplex(*method_opt, raw_path);
auto streaming_match =
match_streaming(*method_opt, raw_path);
if (!streaming_match.has_value()) {
const bool live_route = duplex_match.has_value() ||
streaming_match.has_value();
if (!live_route) {
// Enforce buffered max_body_bytes before reading body.
if (!chunked && content_length.has_value() &&
*content_length > options.max_body_bytes) {
@@ -1644,6 +2273,99 @@ namespace Void::Net
}
}
if (duplex_match.has_value()) {
ServerRequest req;
req.method = *method_opt;
req.path = std::string{raw_path};
req.headers = std::move(headers);
req.parameters = std::move(duplex_match->second);
req.query = std::string{raw_query};
auto writer_state =
std::make_shared<ResponseWriter::State>();
writer_state->fd = fd_guard.get();
writer_state->stopping = &stopping;
writer_state->write_timeout_ms.store(
options.write_timeout.count(),
std::memory_order_release);
writer_state->max_pending =
options.duplex_write_buffer_bytes;
writer_state->head_request =
(*method_opt == Method::Head);
writer_state->http10 = (version == "HTTP/1.0");
writer_state->keep_alive.store(
keep_alive, std::memory_order_release);
ResponseWriter writer =
ResponseWriterAccess::make(writer_state);
auto route_res = duplex_match->first(
req, body_reader, writer);
const bool committed = writer_state->begun.load(
std::memory_order_acquire);
const bool head_attempted =
writer_state->head_attempted.load(
std::memory_order_acquire);
if (!route_res.has_value()) {
if (!committed && !head_attempted &&
!stopping.load(std::memory_order_acquire)) {
if (route_res.error().kind() ==
Void::Result::ErrorKind::exhausted) {
send_error_close(fd_guard.get(), 413,
"Payload Too Large");
} else if (
route_res.error().kind() ==
Void::Result::ErrorKind::timeout ||
route_res.error().kind() ==
Void::Result::ErrorKind::cancelled) {
send_error_close(fd_guard.get(), 408,
"Request Timeout");
} else {
send_error_close(
fd_guard.get(), 500,
"Internal Server Error");
}
}
// After headers the stream is simply terminated
// without a successful terminal chunk.
} else if (!committed) {
if (!head_attempted) {
send_error_close(fd_guard.get(), 500,
"Internal Server Error");
}
} else if (!writer_state->finished.load(
std::memory_order_acquire)) {
auto fin = writer.finish();
if (!fin.has_value()) {
// Framing could not be completed; close.
}
}
const bool completed = writer_state->finished.load(
std::memory_order_acquire);
const bool exchange_keep_alive =
keep_alive &&
writer_state->keep_alive.load(
std::memory_order_acquire) &&
reader_state.eof;
{
// Wait for any writer still inside an
// operation, then permanently invalidate the
// shared state. Retained writers stay memory-safe
// but can no longer touch this connection.
std::lock_guard lock{writer_state->io_mutex};
writer_state->invalid.store(
true, std::memory_order_release);
writer_state->fd = -1;
writer_state->stopping = nullptr;
}
writer_state->request_stop();
if (!exchange_keep_alive || !completed) {
break;
}
continue;
}
if (streaming_match.has_value()) {
ServerRequest req;
req.method = *method_opt;
@@ -1986,6 +2708,36 @@ namespace Void::Net
return {};
}
Void::Result::Result<void>
HttpServer::add_duplex_route(Method method, std::string pattern,
DuplexRouteHandler handler)
{
if (!handler) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplex route handler is empty")};
}
auto compiled = compile_route_pattern(pattern);
if (!compiled.has_value()) {
return std::unexpected{std::move(compiled.error())};
}
std::unique_lock lock{m_impl->stream_mutex};
const auto dup = std::ranges::find_if(
m_impl->duplex_routes, [&](const DuplexRoute& r) {
return r.method == method &&
same_route_shape(r.segments, *compiled);
});
if (dup != m_impl->duplex_routes.end()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplicate duplex route")};
}
m_impl->duplex_routes.push_back(DuplexRoute{
method, std::move(pattern), std::move(*compiled),
std::move(handler)});
return {};
}
Void::Result::Result<void>
HttpServer::add_websocket_route(std::string pattern,
WebSocketSessions& sessions,
@@ -2020,7 +2772,8 @@ namespace Void::Net
}
if (m_impl->options.max_concurrent_connections == 0 ||
m_impl->options.max_header_bytes == 0 ||
m_impl->options.max_headers == 0) {
m_impl->options.max_headers == 0 ||
m_impl->options.duplex_write_buffer_bytes == 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer::start: limits must be positive")};