Files
Library/examples/platforms/networked-kv/src/application.cpp
T

416 lines
12 KiB
C++

#include "networked_kv/application.hpp"
#include "networked_kv/sqlite_store.hpp"
#include <Void/Time/Clock.hpp>
#include <charconv>
#include <cstdint>
#include <string>
#include <string_view>
#include <utility>
namespace NetworkedKv
{
namespace
{
[[nodiscard]] Void::Result::Error
config_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
[[nodiscard]] Void::Result::Error state_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] bool parse_address(std::string_view address, std::string& host,
std::uint16_t& port) noexcept
{
const auto colon = address.rfind(':');
if (colon == std::string_view::npos || colon == 0 ||
colon + 1 >= address.size()) {
return false;
}
host = std::string{address.substr(0, colon)};
const auto digits = address.substr(colon + 1);
unsigned int value = 0;
const auto parsed = std::from_chars(
digits.data(), digits.data() + digits.size(), value);
if (parsed.ec != std::errc{} ||
parsed.ptr != digits.data() + digits.size() || value > 65535U) {
return false;
}
port = static_cast<std::uint16_t>(value);
return true;
}
[[nodiscard]] std::string method_name(Void::Net::Method method)
{
switch (method) {
case Void::Net::Method::Get: return "GET";
case Void::Net::Method::Post: return "POST";
case Void::Net::Method::Put: return "PUT";
case Void::Net::Method::Delete: return "DELETE";
case Void::Net::Method::Patch: return "PATCH";
case Void::Net::Method::Head: return "HEAD";
case Void::Net::Method::Options: return "OPTIONS";
}
return "GET";
}
[[nodiscard]] HttpRequest
to_http_request(const Void::Net::ServerRequest& request)
{
HttpRequest out;
out.method = method_name(request.method);
out.target = request.path;
if (!request.query.empty()) {
out.target += '?';
out.target += request.query;
}
for (const auto& header : request.headers) {
out.headers[header.name] = header.value;
}
out.body = request.body;
return out;
}
[[nodiscard]] Void::Net::ServerResponse
to_server_response(const HttpResponse& response)
{
Void::Net::ServerResponse out;
out.status = static_cast<std::uint16_t>(response.status);
out.body = response.body;
out.headers.reserve(response.headers.size());
for (const auto& [name, value] : response.headers) {
out.headers.push_back(Void::Net::Header{name, value});
}
return out;
}
[[nodiscard]] Void::Async::OperationOptions
deadline_after(std::chrono::milliseconds grace)
{
Void::Async::OperationOptions options;
options.deadline = Void::Time::SystemMonotonicClock::instance().now() +
grace;
return options;
}
} // namespace
Void::Result::Result<void> NetworkedConfig::validate() const
{
if (listen_address.empty()) {
return std::unexpected{
config_error("NetworkedConfig: listen_address must not be empty")};
}
if (max_connections == 0) {
return std::unexpected{
config_error("NetworkedConfig: max_connections must be positive")};
}
if (max_request_bytes == 0) {
return std::unexpected{config_error(
"NetworkedConfig: max_request_bytes must be positive")};
}
if (max_scan_page == 0) {
return std::unexpected{
config_error("NetworkedConfig: max_scan_page must be positive")};
}
if (request_deadline.count() <= 0) {
return std::unexpected{config_error(
"NetworkedConfig: request_deadline must be positive")};
}
if (shutdown_grace.count() < 0) {
return std::unexpected{config_error(
"NetworkedConfig: shutdown_grace must not be negative")};
}
return {};
}
NetworkedApplication::NetworkedApplication(NetworkedApplication&& other) noexcept
: m_config(std::move(other.m_config))
, m_resources(other.m_resources)
, m_owned_host(std::move(other.m_owned_host))
, m_host(other.m_host)
, m_store(std::move(other.m_store))
, m_api(std::move(other.m_api))
, m_server(std::move(other.m_server))
, m_admin_server(std::move(other.m_admin_server))
, m_state(other.m_state)
{
other.m_host = nullptr;
other.m_state = ApplicationState::Stopped;
}
NetworkedApplication&
NetworkedApplication::operator=(NetworkedApplication&& other) noexcept
{
if (this != &other) {
stop_owned_host();
m_config = std::move(other.m_config);
m_resources = other.m_resources;
m_owned_host = std::move(other.m_owned_host);
m_host = other.m_host;
m_store = std::move(other.m_store);
m_api = std::move(other.m_api);
m_server = std::move(other.m_server);
m_admin_server = std::move(other.m_admin_server);
m_state = other.m_state;
other.m_host = nullptr;
other.m_state = ApplicationState::Stopped;
}
return *this;
}
NetworkedApplication::~NetworkedApplication()
{
if (m_server) {
m_server->shutdown(m_config.shutdown_grace);
m_server.reset();
}
if (m_admin_server) {
m_admin_server->shutdown(m_config.shutdown_grace);
m_admin_server.reset();
}
stop_owned_host();
}
Void::Result::Result<NetworkedApplication>
NetworkedApplication::create(ApplicationResources resources,
NetworkedConfig config)
{
if (auto valid = config.validate(); !valid) {
return std::unexpected{std::move(valid).error()};
}
if (resources.ownership == ResourceOwnership::Embedded &&
(resources.borrowed_host == nullptr ||
!resources.borrowed_host->valid())) {
return std::unexpected{config_error(
"NetworkedApplication: embedded mode requires a valid borrowed "
"host")};
}
NetworkedApplication app;
app.m_config = std::move(config);
app.m_resources = resources;
if (app.m_config.storage_path.empty()) {
app.m_store = std::make_unique<MemoryKvStore>();
} else {
auto durable = SqliteKvStore::open(app.m_config.storage_path);
if (!durable) {
return std::unexpected{std::move(durable).error()};
}
app.m_store = std::move(*durable);
}
app.m_api = std::make_unique<KvApi>(
*app.m_store,
ApiConfig{.bearer_token = app.m_config.bearer_token,
.max_body_bytes = app.m_config.max_request_bytes,
.max_scan_limit = app.m_config.max_scan_page});
return app;
}
Void::Result::Result<void> NetworkedApplication::start()
{
if (m_state == ApplicationState::Running) {
return std::unexpected{
state_error("NetworkedApplication: already running")};
}
if (m_resources.ownership == ResourceOwnership::Managed) {
if (!m_owned_host) {
auto created =
Void::Runtime::Host::create(m_resources.runtime_options);
if (!created) {
m_state = ApplicationState::Failed;
return std::unexpected{std::move(created).error()};
}
m_owned_host =
std::make_unique<Void::Runtime::Host>(std::move(*created));
m_host = m_owned_host.get();
}
if (!m_host->is_running()) {
if (auto started = m_host->start(); !started) {
m_state = ApplicationState::Failed;
return started;
}
}
} else {
m_host = m_resources.borrowed_host;
if (m_host == nullptr || !m_host->is_running()) {
return std::unexpected{state_error(
"NetworkedApplication: embedded mode requires a running "
"borrowed host")};
}
}
if (!m_server) {
std::string host;
std::uint16_t port = 0;
if (!parse_address(m_config.listen_address, host, port)) {
m_state = ApplicationState::Failed;
return std::unexpected{config_error(
"NetworkedApplication: listen_address must be host:port")};
}
Void::Net::HttpServerOptions options;
options.bind_host = std::move(host);
options.port = port;
options.max_body_bytes = m_config.max_request_bytes;
options.max_concurrent_connections = m_config.max_connections;
auto server = std::make_unique<Void::Net::HttpServer>(options);
auto add = [&](Void::Net::Method method, const char* pattern) {
return server->add_route(
method, pattern,
[this](const Void::Net::ServerRequest& request)
-> Void::Net::RouteResult {
return to_server_response(
m_api->handle(to_http_request(request)));
});
};
Void::Result::Error route_error{};
bool routes_ok = true;
auto add_checked = [&](Void::Net::Method method, const char* pattern) {
if (!routes_ok) {
return;
}
if (auto added = add(method, pattern); !added) {
routes_ok = false;
route_error = std::move(added).error();
}
};
add_checked(Void::Net::Method::Get, "/v1/kv/:key");
add_checked(Void::Net::Method::Put, "/v1/kv/:key");
add_checked(Void::Net::Method::Delete, "/v1/kv/:key");
add_checked(Void::Net::Method::Get, "/v1/scan");
if (!routes_ok) {
m_state = ApplicationState::Failed;
return std::unexpected{std::move(route_error)};
}
if (auto started = server->start(); !started) {
m_state = ApplicationState::Failed;
return started;
}
m_server = std::move(server);
}
// The administrative listener is separate from the data plane and
// only exposes bounded lifecycle and telemetry views.
if (!m_admin_server && !m_config.admin_address.empty()) {
std::string host;
std::uint16_t port = 0;
if (!parse_address(m_config.admin_address, host, port)) {
m_state = ApplicationState::Failed;
return std::unexpected{config_error(
"NetworkedApplication: admin_address must be host:port")};
}
Void::Net::HttpServerOptions options;
options.bind_host = std::move(host);
options.port = port;
options.max_concurrent_connections = 8;
auto admin = std::make_unique<Void::Net::HttpServer>(options);
auto add_admin = [&](const char* pattern) {
return admin->add_route(
Void::Net::Method::Get, pattern,
[this](const Void::Net::ServerRequest& request)
-> Void::Net::RouteResult {
return to_server_response(
m_api->admin(to_http_request(request)));
});
};
Void::Result::Error admin_error{};
bool admin_ok = true;
for (const char* pattern : {"/live", "/ready", "/metrics"}) {
if (!admin_ok) {
break;
}
if (auto added = add_admin(pattern); !added) {
admin_ok = false;
admin_error = std::move(added).error();
}
}
if (!admin_ok) {
m_state = ApplicationState::Failed;
return std::unexpected{std::move(admin_error)};
}
if (auto started = admin->start(); !started) {
m_state = ApplicationState::Failed;
return started;
}
m_admin_server = std::move(admin);
}
m_state = ApplicationState::Running;
return {};
}
Void::Result::Result<Void::Runtime::ShutdownReport>
NetworkedApplication::stop()
{
if (m_state == ApplicationState::Stopped) {
return Void::Runtime::ShutdownReport{};
}
if (m_state != ApplicationState::Running) {
m_state = ApplicationState::Stopped;
return Void::Runtime::ShutdownReport{};
}
m_state = ApplicationState::Stopping;
if (m_server) {
m_server->shutdown(m_config.shutdown_grace);
m_server.reset();
}
if (m_admin_server) {
m_admin_server->shutdown(m_config.shutdown_grace);
m_admin_server.reset();
}
if (m_resources.ownership == ResourceOwnership::Managed && m_host) {
auto report =
m_host->shutdown_blocking(deadline_after(m_config.shutdown_grace));
m_state = ApplicationState::Stopped;
return report;
}
// Embedded: the borrowed host belongs to the application, so only
// this composition's view stops.
m_state = ApplicationState::Stopped;
Void::Runtime::ShutdownReport report;
report.complete = true;
report.state = m_host ? m_host->state()
: Void::Runtime::HostState::stopped;
return report;
}
HealthSnapshot NetworkedApplication::health() const
{
HealthSnapshot snapshot;
snapshot.state = m_state;
snapshot.managed = m_resources.ownership == ResourceOwnership::Managed;
if (m_host != nullptr) {
snapshot.ready = m_host->is_ready();
snapshot.started_workers = m_host->started_worker_count();
}
snapshot.bound_port = bound_port();
return snapshot;
}
std::uint16_t NetworkedApplication::bound_port() const noexcept
{
return m_server ? m_server->bound_port() : 0;
}
std::uint16_t NetworkedApplication::admin_bound_port() const noexcept
{
return m_admin_server ? m_admin_server->bound_port() : 0;
}
void NetworkedApplication::stop_owned_host() noexcept
{
if (m_resources.ownership != ResourceOwnership::Managed ||
!m_owned_host || m_state != ApplicationState::Running) {
return;
}
m_state = ApplicationState::Stopping;
(void)m_owned_host->shutdown_blocking(
deadline_after(m_config.shutdown_grace));
m_state = ApplicationState::Stopped;
}
} // namespace NetworkedKv