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

+87
View File
@@ -13,7 +13,9 @@
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <vector>
namespace Void::Net
{
@@ -27,6 +29,10 @@ namespace Void::Net
std::size_t max_concurrent_connections{64};
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
/// Bounded per-exchange output buffer used by duplex response
/// writers. Producers block (or observe a short accepted count)
/// once this much framed data is pending.
std::size_t duplex_write_buffer_bytes{64ULL * 1024};
int listen_backlog{128};
};
@@ -64,6 +70,83 @@ namespace Void::Net
using StreamingRouteHandler =
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
/// Scoped, move-only writer for a live duplex HTTP exchange.
///
/// Exactly one writer may be active at a time (`begin`, `write_some` and
/// `finish` fail with `overloaded` if another thread is inside the
/// writer). `write_some` returns how many payload bytes it accepted; the
/// writer applies bounded buffering and downstream backpressure. Fixed
/// length, chunked and bodyless responses are selected by `begin`.
///
/// After the exchange returns the writer is invalidated. A moved-from or
/// retained writer observes `valid() == false` and every operation fails
/// with `invalid_argument` instead of touching the connection.
class ResponseWriter
{
public:
struct State;
ResponseWriter() noexcept = default;
~ResponseWriter() = default;
ResponseWriter(const ResponseWriter&) = delete;
ResponseWriter& operator=(const ResponseWriter&) = delete;
ResponseWriter(ResponseWriter&&) noexcept = default;
ResponseWriter& operator=(ResponseWriter&&) noexcept = default;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool begun() const noexcept;
[[nodiscard]] bool finished() const noexcept;
[[nodiscard]] bool cancelled() const noexcept;
[[nodiscard]] bool chunked() const noexcept;
[[nodiscard]] std::optional<std::uint64_t>
content_length() const noexcept;
[[nodiscard]] std::uint64_t bytes_accepted() const noexcept;
[[nodiscard]] std::uint64_t bytes_sent() const noexcept;
[[nodiscard]] std::size_t buffered_bytes() const noexcept;
/// Token cancelled by `cancel()`, peer disconnect, server shutdown
/// or the end of the exchange.
[[nodiscard]] std::stop_token stop_token() const noexcept;
void cancel() noexcept;
void set_write_timeout(std::chrono::milliseconds timeout) noexcept;
[[nodiscard]] std::chrono::milliseconds
write_timeout() const noexcept;
/// Send the response head. Chooses fixed length when a
/// `Content-Length` header is supplied, chunked otherwise (HTTP/1.1),
/// and a bodyless frame for HEAD, 1xx, 204 and 304 responses.
[[nodiscard]] Void::Result::Result<void>
begin(std::uint16_t status, std::vector<Header> headers = {});
/// Accept up to `bytes.size()` payload bytes, bounded by the
/// configured write buffer. Returns the accepted count.
[[nodiscard]] Void::Result::Result<std::size_t>
write_some(std::span<const std::byte> bytes);
/// Terminate the framed response. Fails if a fixed-length body was
/// not fully written.
[[nodiscard]] Void::Result::Result<void> finish();
private:
friend struct ResponseWriterAccess;
explicit ResponseWriter(std::shared_ptr<State> state) noexcept
: m_state{std::move(state)}
{
}
std::shared_ptr<State> m_state;
};
/// Handler for a duplex route: the request body can be read while the
/// response is produced. Returning an error before `begin` lets the server
/// emit an error response; after `begin` the stream is terminated without
/// reporting success.
using DuplexRouteHandler = std::function<Void::Result::Result<void>(
const ServerRequest&, BodyReader&, ResponseWriter&)>;
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
/// `Void::Net::Router` and streaming routes via `BodyReader`.
class HttpServer
@@ -90,6 +173,10 @@ namespace Void::Net
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
[[nodiscard]] Void::Result::Result<void>
add_duplex_route(Method method, std::string pattern,
DuplexRouteHandler handler);
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
/// `sessions` (caller must keep `sessions` alive until after
/// `shutdown()`).
+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")};
+766
View File
@@ -0,0 +1,766 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
using namespace std::chrono_literals;
using Void::Net::BodyReader;
using Void::Net::DuplexRouteHandler;
using Void::Net::Header;
using Void::Net::HttpServer;
using Void::Net::HttpServerOptions;
using Void::Net::Method;
using Void::Net::ResponseWriter;
using Void::Net::ServerRequest;
using Void::Result::ErrorKind;
using Void::Result::Result;
int connect_loopback(std::uint16_t port)
{
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
Void::Testing::require(fd >= 0);
timeval tv{};
tv.tv_sec = 3;
tv.tv_usec = 0;
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
Void::Testing::require(
::connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) ==
0);
return fd;
}
void send_bytes(int fd, std::string_view bytes)
{
std::size_t off = 0;
while (off < bytes.size()) {
const ssize_t n =
::send(fd, bytes.data() + off, bytes.size() - off, MSG_NOSIGNAL);
Void::Testing::require(n > 0);
off += static_cast<std::size_t>(n);
}
}
std::string recv_exact(int fd, std::size_t count)
{
std::string out;
out.reserve(count);
std::array<char, 4096> buf{};
while (out.size() < count) {
const std::size_t want = std::min(buf.size(), count - out.size());
const ssize_t n = ::recv(fd, buf.data(), want, 0);
if (n <= 0) {
break;
}
out.append(buf.data(), static_cast<std::size_t>(n));
}
return out;
}
std::string recv_until(int fd, std::string_view marker)
{
std::string out;
std::array<char, 1024> buf{};
while (out.find(marker) == std::string::npos) {
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
if (n <= 0) {
break;
}
out.append(buf.data(), static_cast<std::size_t>(n));
if (out.size() > 64 * 1024) {
break;
}
}
return out;
}
std::string recv_to_eof(int fd)
{
std::string out;
std::array<char, 4096> buf{};
for (;;) {
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
if (n <= 0) {
break;
}
out.append(buf.data(), static_cast<std::size_t>(n));
}
return out;
}
std::string get_request(std::string_view path, bool head = false,
std::string_view extra_headers = {})
{
std::string req = head ? "HEAD " : "GET ";
req += path;
req += " HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n";
req += extra_headers;
req += "\r\n";
return req;
}
bool wait_flag(const std::atomic<bool>& flag,
std::chrono::milliseconds timeout = 5s)
{
const auto deadline = std::chrono::steady_clock::now() + timeout;
while (!flag.load(std::memory_order_acquire)) {
if (std::chrono::steady_clock::now() >= deadline) {
return false;
}
std::this_thread::sleep_for(1ms);
}
return true;
}
std::size_t count_occurrences(std::string_view haystack,
std::string_view needle)
{
std::size_t count = 0;
std::size_t pos = 0;
while ((pos = haystack.find(needle, pos)) != std::string_view::npos) {
++count;
pos += needle.size();
}
return count;
}
} // namespace
Void::Testing::Test http_duplex_upload_while_reading_fixed_response()
{
HttpServerOptions opts;
opts.write_timeout = 2s;
opts.read_timeout = 2s;
opts.duplex_write_buffer_bytes = 4 * 1024;
HttpServer server{opts};
Void::Testing::require(
server
.add_duplex_route(
Method::Post, "/echo-fixed",
[](const ServerRequest&, BodyReader& body,
ResponseWriter& writer) -> Result<void> {
const std::uint64_t total = body.content_length().value_or(0);
auto began = writer.begin(
200, {Header{"Content-Length", std::to_string(total)}});
if (!began.has_value()) {
return began;
}
std::array<std::byte, 8> buf{};
for (;;) {
auto n = body.read_some(buf);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
if (*n == 0) {
break;
}
std::size_t off = 0;
while (off < *n) {
auto accepted = writer.write_some(
std::span<const std::byte>{buf.data() + off,
*n - off});
if (!accepted.has_value()) {
return std::unexpected{
std::move(accepted.error())};
}
off += *accepted;
}
}
return writer.finish();
})
.has_value());
Void::Testing::require(server.start().has_value());
const int fd = connect_loopback(server.bound_port());
const std::string head =
"POST /echo-fixed HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Content-Length: 12\r\n"
"Connection: close\r\n\r\n";
send_bytes(fd, head);
// Upload the first half, then read the echoed half before uploading the
// rest: the server must be reading and writing the same exchange.
send_bytes(fd, "abcd");
const std::string resp_head = recv_until(fd, "\r\n\r\n");
Void::Testing::require(resp_head.find("HTTP/1.1 200") != std::string::npos);
Void::Testing::require(resp_head.find("Content-Length: 12") !=
std::string::npos);
Void::Testing::expect_eq(recv_exact(fd, 4), std::string{"abcd"});
send_bytes(fd, "efghijkl");
Void::Testing::expect_eq(recv_exact(fd, 8), std::string{"efghijkl"});
(void)::close(fd);
server.shutdown();
}
Void::Testing::Test http_duplex_chunked_bodyless_and_head_framing()
{
HttpServer server;
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/chunked",
[](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(200);
if (!began.has_value()) {
return began;
}
const std::string_view text = "hello";
auto accepted = writer.write_some(std::as_bytes(
std::span{text.data(), text.size()}));
if (!accepted.has_value()) {
return std::unexpected{std::move(accepted.error())};
}
Void::Testing::expect_eq(*accepted, std::size_t{5});
return writer.finish();
})
.has_value());
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/bodyless",
[](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(204);
if (!began.has_value()) {
return began;
}
std::array<std::byte, 1> one{std::byte{'x'}};
auto rejected = writer.write_some(one);
Void::Testing::expect(!rejected.has_value());
Void::Testing::expect(rejected.error().kind() ==
ErrorKind::invalid_argument);
return writer.finish();
})
.has_value());
Void::Testing::require(
server
.add_duplex_route(
Method::Head, "/head",
[](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began =
writer.begin(200, {Header{"Content-Length", "123"}});
if (!began.has_value()) {
return began;
}
std::array<std::byte, 1> one{std::byte{'x'}};
Void::Testing::expect(!writer.write_some(one).has_value());
return writer.finish();
})
.has_value());
Void::Testing::require(server.start().has_value());
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/chunked"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 200"));
Void::Testing::expect(raw.find("Transfer-Encoding: chunked") !=
std::string::npos);
Void::Testing::expect(raw.find("5\r\nhello\r\n0\r\n\r\n") !=
std::string::npos);
}
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/bodyless"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 204"));
Void::Testing::expect(raw.find("Transfer-Encoding") ==
std::string::npos);
Void::Testing::expect(raw.ends_with("\r\n\r\n"));
}
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/head", true));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 200"));
Void::Testing::expect(raw.find("Content-Length: 123") !=
std::string::npos);
Void::Testing::expect(raw.ends_with("\r\n\r\n"));
}
server.shutdown();
}
Void::Testing::Test http_duplex_disconnect_cancellation_and_retained_writer()
{
HttpServerOptions opts;
opts.write_timeout = 300ms;
HttpServer server{opts};
std::atomic<bool> disconnect_done{false};
std::atomic<int> disconnect_kind{-1};
std::atomic<bool> cancel_done{false};
std::atomic<int> cancel_kind{-1};
std::atomic<int> cancel_write_kind{-1};
std::mutex retained_mutex;
std::shared_ptr<ResponseWriter> retained;
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/disconnect",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(200);
if (!began.has_value()) {
return began;
}
std::vector<std::byte> chunk(4096, std::byte{'d'});
for (;;) {
auto accepted = writer.write_some(chunk);
if (!accepted.has_value()) {
disconnect_kind.store(
static_cast<int>(accepted.error().kind()),
std::memory_order_release);
break;
}
}
disconnect_done.store(true, std::memory_order_release);
return std::unexpected{Void::Net::make_net_error(
Void::Net::NetErrorCode::io_error, "disconnected")};
})
.has_value());
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/cancel",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(200);
if (!began.has_value()) {
return began;
}
const std::string_view text = "abc";
(void)writer.write_some(std::as_bytes(
std::span{text.data(), text.size()}));
writer.cancel();
Void::Testing::expect(writer.cancelled());
std::array<std::byte, 1> one{std::byte{'z'}};
auto rejected = writer.write_some(one);
cancel_write_kind.store(
rejected.has_value()
? -1
: static_cast<int>(rejected.error().kind()),
std::memory_order_release);
auto fin = writer.finish();
cancel_kind.store(
fin.has_value()
? -1
: static_cast<int>(fin.error().kind()),
std::memory_order_release);
cancel_done.store(true, std::memory_order_release);
return std::unexpected{Void::Net::make_net_error(
Void::Net::NetErrorCode::cancelled, "cancelled")};
})
.has_value());
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/retain",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(
200, {Header{"Content-Length", "2"}});
if (!began.has_value()) {
return began;
}
const std::string_view text = "ok";
(void)writer.write_some(std::as_bytes(
std::span{text.data(), text.size()}));
auto fin = writer.finish();
if (!fin.has_value()) {
return fin;
}
std::lock_guard lock{retained_mutex};
retained =
std::make_shared<ResponseWriter>(std::move(writer));
return {};
})
.has_value());
Void::Testing::require(server.start().has_value());
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/disconnect"));
(void)recv_until(fd, "\r\n\r\n");
(void)recv_exact(fd, 128);
(void)::close(fd);
}
Void::Testing::require(wait_flag(disconnect_done));
Void::Testing::expect(
disconnect_kind.load() == static_cast<int>(ErrorKind::io) ||
disconnect_kind.load() == static_cast<int>(ErrorKind::cancelled));
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/cancel"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 200"));
Void::Testing::expect(raw.find("abc") != std::string::npos);
Void::Testing::expect(raw.find("0\r\n\r\n") == std::string::npos);
}
Void::Testing::require(wait_flag(cancel_done));
Void::Testing::expect(cancel_write_kind.load() ==
static_cast<int>(ErrorKind::cancelled));
Void::Testing::expect(cancel_kind.load() ==
static_cast<int>(ErrorKind::cancelled));
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/retain"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.find("ok") != std::string::npos);
}
std::shared_ptr<ResponseWriter> kept;
{
std::lock_guard lock{retained_mutex};
kept = retained;
}
Void::Testing::require(kept != nullptr);
const auto deadline = std::chrono::steady_clock::now() + 2s;
while (kept->valid() && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(1ms);
}
Void::Testing::expect(!kept->valid());
std::array<std::byte, 1> one{std::byte{'q'}};
auto after = kept->write_some(one);
Void::Testing::expect(!after.has_value());
Void::Testing::expect(after.error().kind() ==
ErrorKind::invalid_argument);
server.shutdown();
}
Void::Testing::Test http_duplex_stalled_consumer_bounded_memory()
{
HttpServerOptions opts;
opts.write_timeout = 150ms;
opts.duplex_write_buffer_bytes = 4 * 1024;
HttpServer server{opts};
std::atomic<bool> done{false};
std::atomic<int> kind{-1};
std::atomic<std::uint64_t> accepted_total{0};
std::atomic<std::size_t> max_buffered{0};
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/stall",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
writer.set_write_timeout(150ms);
auto began = writer.begin(200);
if (!began.has_value()) {
return began;
}
std::vector<std::byte> chunk(4096, std::byte{'s'});
for (;;) {
auto accepted = writer.write_some(chunk);
max_buffered.store(
std::max(max_buffered.load(),
writer.buffered_bytes()),
std::memory_order_release);
if (!accepted.has_value()) {
kind.store(
static_cast<int>(accepted.error().kind()),
std::memory_order_release);
break;
}
accepted_total.fetch_add(*accepted,
std::memory_order_acq_rel);
}
done.store(true, std::memory_order_release);
return std::unexpected{Void::Net::make_net_error(
Void::Net::NetErrorCode::timeout, "stalled")};
})
.has_value());
Void::Testing::require(server.start().has_value());
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/stall"));
// Deliberately never read the response.
std::this_thread::sleep_for(400ms);
(void)::close(fd);
Void::Testing::require(wait_flag(done, 5s));
Void::Testing::expect(kind.load() == static_cast<int>(ErrorKind::timeout) ||
kind.load() == static_cast<int>(ErrorKind::io) ||
kind.load() ==
static_cast<int>(ErrorKind::cancelled));
Void::Testing::expect(max_buffered.load() <= opts.duplex_write_buffer_bytes);
Void::Testing::expect(accepted_total.load() < 64ULL * 1024 * 1024);
server.shutdown();
}
Void::Testing::Test http_duplex_concurrent_writers_are_rejected()
{
HttpServerOptions opts;
opts.write_timeout = 500ms;
opts.duplex_write_buffer_bytes = 4 * 1024;
HttpServer server{opts};
std::atomic<bool> done{false};
std::atomic<int> overloaded{0};
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/concurrent",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
writer.set_write_timeout(500ms);
auto began = writer.begin(200);
if (!began.has_value()) {
return began;
}
std::vector<std::byte> chunk(4096, std::byte{'c'});
auto writer_fn = [&]() {
for (int i = 0; i < 100000; ++i) {
auto accepted = writer.write_some(chunk);
if (!accepted.has_value()) {
if (accepted.error().kind() ==
ErrorKind::overloaded) {
overloaded.fetch_add(
1, std::memory_order_acq_rel);
}
break;
}
}
};
std::thread first{writer_fn};
std::thread second{writer_fn};
first.join();
second.join();
done.store(true, std::memory_order_release);
writer.cancel();
return std::unexpected{Void::Net::make_net_error(
Void::Net::NetErrorCode::cancelled, "done")};
})
.has_value());
Void::Testing::require(server.start().has_value());
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/concurrent"));
// Never read, so the socket backpressures the writers.
Void::Testing::require(wait_flag(done, 10s));
Void::Testing::expect(overloaded.load() >= 1);
(void)::close(fd);
server.shutdown();
}
Void::Testing::Test http_duplex_malformed_framing_and_error_phases()
{
HttpServer server;
std::atomic<int> bad_begin_kind{-1};
std::atomic<int> bad_header_kind{-1};
std::atomic<int> overflow_kind{-1};
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/bad-begin",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(
200, {Header{"Content-Length", "5"},
Header{"Transfer-Encoding", "chunked"}});
Void::Testing::expect(!began.has_value());
bad_begin_kind.store(
static_cast<int>(began.error().kind()),
std::memory_order_release);
return std::unexpected{std::move(began.error())};
})
.has_value());
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/bad-header",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began =
writer.begin(200, {Header{"X-Bad", "a\r\nb"}});
Void::Testing::expect(!began.has_value());
bad_header_kind.store(
static_cast<int>(began.error().kind()),
std::memory_order_release);
return std::unexpected{std::move(began.error())};
})
.has_value());
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/bad-fixed",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(
200, {Header{"Content-Length", "3"}});
if (!began.has_value()) {
return began;
}
std::array<std::byte, 4> four{};
auto accepted = writer.write_some(four);
Void::Testing::expect(!accepted.has_value());
overflow_kind.store(
static_cast<int>(accepted.error().kind()),
std::memory_order_release);
// Error after headers: the server must terminate the
// stream without a successful terminal chunk.
return std::unexpected{std::move(accepted.error())};
})
.has_value());
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/ok",
[](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
auto began = writer.begin(
200, {Header{"Content-Length", "2"}});
if (!began.has_value()) {
return began;
}
const std::string_view text = "ok";
auto accepted = writer.write_some(std::as_bytes(
std::span{text.data(), text.size()}));
if (!accepted.has_value()) {
return std::unexpected{std::move(accepted.error())};
}
return writer.finish();
})
.has_value());
Void::Testing::require(server.start().has_value());
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/bad-begin"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 500"));
}
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/bad-header"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 500"));
}
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/bad-fixed"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 200"));
Void::Testing::expect(raw.find("Content-Length: 3") !=
std::string::npos);
Void::Testing::expect(raw.find("ok") == std::string::npos);
}
Void::Testing::expect(bad_begin_kind.load() ==
static_cast<int>(ErrorKind::invalid_argument));
Void::Testing::expect(bad_header_kind.load() ==
static_cast<int>(ErrorKind::invalid_argument));
Void::Testing::expect(overflow_kind.load() ==
static_cast<int>(ErrorKind::invalid_argument));
// The server survives malformed exchanges and still serves a valid route.
{
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/ok"));
const std::string raw = recv_to_eof(fd);
(void)::close(fd);
Void::Testing::expect(raw.starts_with("HTTP/1.1 200"));
Void::Testing::expect(raw.ends_with("ok"));
}
server.shutdown();
}
Void::Testing::Test http_duplex_server_shutdown_cancels_exchange()
{
HttpServerOptions opts;
opts.write_timeout = 200ms;
HttpServer server{opts};
std::atomic<bool> started{false};
std::atomic<bool> exited{false};
Void::Testing::require(
server
.add_duplex_route(
Method::Get, "/shutdown",
[&](const ServerRequest&, BodyReader&,
ResponseWriter& writer) -> Result<void> {
writer.set_write_timeout(200ms);
auto began = writer.begin(200);
if (!began.has_value()) {
return began;
}
started.store(true, std::memory_order_release);
std::array<std::byte, 1> one{std::byte{'x'}};
while (!writer.cancelled()) {
auto accepted = writer.write_some(one);
if (!accepted.has_value()) {
break;
}
std::this_thread::sleep_for(5ms);
}
exited.store(true, std::memory_order_release);
return std::unexpected{Void::Net::make_net_error(
Void::Net::NetErrorCode::cancelled, "shutdown")};
})
.has_value());
Void::Testing::require(server.start().has_value());
const int fd = connect_loopback(server.bound_port());
send_bytes(fd, get_request("/shutdown"));
Void::Testing::require(wait_flag(started));
const auto begin = std::chrono::steady_clock::now();
server.shutdown(2s);
const auto elapsed = std::chrono::steady_clock::now() - begin;
Void::Testing::expect(elapsed < 3s);
Void::Testing::expect(exited.load());
(void)::close(fd);
}