Files
Library/include/Void/Net/HttpServer.hpp
T

205 lines
6.9 KiB
C++

#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <Void/Net/WebSocket.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <vector>
namespace Void::Net
{
struct HttpServerOptions {
std::string bind_host{"127.0.0.1"};
std::uint16_t port{0};
std::size_t max_header_bytes{64ULL * 1024};
std::size_t max_headers{128};
std::uint64_t max_body_bytes{16ULL * 1024 * 1024};
std::uint64_t max_streaming_body_bytes{512ULL * 1024 * 1024};
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};
};
/// Streaming request body reader passed to streaming HTTP route handlers.
class BodyReader
{
public:
struct State;
explicit BodyReader(State& state) noexcept : m_state(&state) {}
BodyReader(const BodyReader&) = delete;
BodyReader& operator=(const BodyReader&) = delete;
[[nodiscard]] std::optional<std::uint64_t>
content_length() const noexcept;
[[nodiscard]] bool is_chunked() const noexcept;
[[nodiscard]] std::uint64_t bytes_read() const noexcept;
/// Read up to dst.size() decoded body bytes. Returns 0 at EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read_some(std::span<std::byte> dst);
/// Stream the request body atomically to `destination`, enforcing
/// `max_bytes` (or server max_streaming_body_bytes when 0).
[[nodiscard]] Void::Result::Result<std::uint64_t>
read_to_file(const std::filesystem::path& destination,
std::uint64_t max_bytes = 0);
private:
State* m_state{nullptr};
};
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
{
public:
explicit HttpServer(HttpServerOptions options = {});
explicit HttpServer(Router& external_router,
HttpServerOptions options = {});
~HttpServer() noexcept;
HttpServer(HttpServer&&) noexcept;
HttpServer& operator=(HttpServer&&) noexcept;
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
[[nodiscard]] Router& router() noexcept;
[[nodiscard]] Void::Result::Result<void>
add_route(Method method, std::string pattern,
RouteHandler handler);
[[nodiscard]] Void::Result::Result<void>
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()`).
[[nodiscard]] Void::Result::Result<void>
add_websocket_route(std::string pattern,
WebSocketSessions& sessions,
WebSocketUpgradeOptions options = {});
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
std::chrono::seconds{5}) noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::string bind_address() const;
[[nodiscard]] std::string base_url() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace Void::Net