feat(daemon,platform): add Unix-socket daemon core, split Linux platform backends, and fix CMake feature-carrier translation
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 7s

This commit is contained in:
faumaray committed 2026-12-03 16:10:25 +03:00
1 parent 55ea305528
commit 0bde74f739
20 files changed
+1194 -21

No files matched your search

+691
View File
@@ -0,0 +1,691 @@
#include <Void/Build/Daemon/Daemon.hpp>
#include <Void/Build/State/StateStore.hpp>
#include <Void/Build/Watch/Watcher.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Functional/Error.hpp>
#include <cerrno>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <fcntl.h>
#include <format>
#include <limits>
#include <poll.h>
#include <string>
#include <string_view>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <system_error>
#include <unistd.h>
#include <utility>
#include <variant>
namespace Void::Build::Daemon {
namespace {
using JsonValue = Void::Json::Strict::Value;
using Clock = std::chrono::steady_clock;
constexpr std::size_t kMaxRequestBytes = 64U * 1024U;
constexpr std::size_t kMaxJsonDepth = 16U;
constexpr int kListenBacklog = 8;
constexpr auto kClientIoTimeout = std::chrono::milliseconds{2000};
constexpr auto kProbeTimeout = std::chrono::milliseconds{1000};
Void::Result::Error make_error(Void::Result::ErrorKind kind, std::string message,
int system_errno = 0) {
std::error_code sys{};
if (system_errno != 0) {
sys = std::error_code{system_errno, std::system_category()};
}
return Void::Result::Error{kind, std::move(message), {}, sys};
}
int poll_timeout_ms(std::chrono::milliseconds timeout) noexcept {
if (timeout.count() <= 0) {
return 0;
}
const auto maximum = static_cast<long long>(std::numeric_limits<int>::max());
return timeout.count() > maximum ? std::numeric_limits<int>::max()
: static_cast<int>(timeout.count());
}
class UniqueFd {
public:
UniqueFd() = default;
explicit UniqueFd(int fd) noexcept : fd_{fd} {}
~UniqueFd() { reset(); }
UniqueFd(const UniqueFd &) = delete;
UniqueFd &operator=(const UniqueFd &) = delete;
UniqueFd(UniqueFd &&other) noexcept : fd_{std::exchange(other.fd_, -1)} {}
UniqueFd &operator=(UniqueFd &&other) noexcept {
if (this != &other) {
reset(std::exchange(other.fd_, -1));
}
return *this;
}
[[nodiscard]] int get() const noexcept { return fd_; }
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
int release() noexcept { return std::exchange(fd_, -1); }
void reset(int fd = -1) noexcept {
if (fd_ >= 0) {
::close(fd_);
}
fd_ = fd;
}
private:
int fd_{-1};
};
Void::Result::Result<void, Void::Result::Error> set_close_on_exec(int fd) {
const int flags = ::fcntl(fd, F_GETFD);
if (flags < 0) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: fcntl(F_GETFD) failed", errno)};
}
if (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
return std::unexpected{make_error(Void::Result::ErrorKind::io,
"daemon: fcntl(F_SETFD, FD_CLOEXEC) failed", errno)};
}
return {};
}
Void::Result::Result<sockaddr_un, Void::Result::Error>
make_address(const std::filesystem::path &socket_path) {
const std::string text = socket_path.string();
if (text.empty()) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: socket path must not be empty")};
}
sockaddr_un address{};
address.sun_family = AF_UNIX;
if (text.size() >= sizeof(address.sun_path)) {
return std::unexpected{make_error(
Void::Result::ErrorKind::invalid_argument,
std::format("daemon: socket path '{}' is {} bytes; a Unix socket address holds at "
"most {} bytes including the terminator",
text, text.size(), sizeof(address.sun_path) - 1))};
}
std::memcpy(address.sun_path, text.c_str(), text.size() + 1);
return address;
}
Void::Result::Result<void, Void::Result::Error> write_all(int fd, std::string_view data) {
while (!data.empty()) {
const ssize_t written = ::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
if (written < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: send failed", errno)};
}
data.remove_prefix(static_cast<std::size_t>(written));
}
return {};
}
Void::Result::Result<std::string, Void::Result::Error>
read_line(int fd, std::chrono::milliseconds timeout) {
const auto deadline = Clock::now() + timeout;
std::string line;
line.reserve(256);
char buffer[4096];
while (true) {
if (const auto newline = line.find('\n'); newline != std::string::npos) {
line.resize(newline);
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
return line;
}
if (line.size() > kMaxRequestBytes) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: request exceeds 64 KiB")};
}
auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - Clock::now());
if (remaining.count() < 0) {
remaining = std::chrono::milliseconds{0};
}
pollfd descriptor{fd, POLLIN, 0};
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(remaining));
if (ready < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
}
if (ready == 0) {
return std::unexpected{make_error(Void::Result::ErrorKind::timeout,
"daemon: timed out waiting for request line")};
}
const ssize_t count = ::read(fd, buffer, sizeof(buffer));
if (count < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: read failed", errno)};
}
if (count == 0) {
if (line.empty()) {
return std::unexpected{make_error(Void::Result::ErrorKind::io,
"daemon: connection closed before request")};
}
return line;
}
line.append(buffer, static_cast<std::size_t>(count));
if (line.size() > kMaxRequestBytes) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: request exceeds 64 KiB")};
}
}
}
Void::Result::Result<UniqueFd, Void::Result::Error>
connect_socket(const std::filesystem::path &socket_path, std::chrono::milliseconds timeout) {
auto address = make_address(socket_path);
if (!address) {
return std::unexpected{std::move(address.error())};
}
UniqueFd fd{::socket(AF_UNIX, SOCK_STREAM, 0)};
if (!fd.valid()) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: socket() failed", errno)};
}
if (auto cloexec = set_close_on_exec(fd.get()); !cloexec) {
return std::unexpected{std::move(cloexec.error())};
}
const int flags = ::fcntl(fd.get(), F_GETFL);
if (flags < 0 || ::fcntl(fd.get(), F_SETFL, flags | O_NONBLOCK) < 0) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: fcntl(F_SETFL) failed", errno)};
}
int result =
::connect(fd.get(), reinterpret_cast<const sockaddr *>(&*address), sizeof(sockaddr_un));
if (result < 0 && errno != EINPROGRESS) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io,
std::format("daemon: cannot connect to '{}'", socket_path.string()), errno)};
}
if (result < 0) {
pollfd descriptor{fd.get(), POLLOUT, 0};
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(timeout));
if (ready < 0) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
}
if (ready == 0) {
return std::unexpected{make_error(Void::Result::ErrorKind::timeout,
"daemon: timed out connecting to socket")};
}
int socket_error = 0;
socklen_t length = sizeof(socket_error);
if (::getsockopt(fd.get(), SOL_SOCKET, SO_ERROR, &socket_error, &length) < 0) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: getsockopt failed", errno)};
}
if (socket_error != 0) {
return std::unexpected{make_error(
Void::Result::ErrorKind::io,
std::format("daemon: cannot connect to '{}'", socket_path.string()), socket_error)};
}
}
if (::fcntl(fd.get(), F_SETFL, flags) < 0) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: fcntl restore failed", errno)};
}
return fd;
}
std::string serialize_response(const JsonValue &value) {
auto serialized = Void::Json::Strict::serialize(value);
if (serialized) {
return *serialized;
}
return R"({"ok":false,"error":"daemon: response serialization failed"})";
}
std::string error_response(std::string_view message) {
JsonValue::Object object;
object.emplace("ok", JsonValue{false});
object.emplace("error", JsonValue{std::string{message}});
return serialize_response(JsonValue{std::move(object)});
}
std::string ok_response(std::string_view op) {
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{op}});
return serialize_response(JsonValue{std::move(object)});
}
} // namespace
struct DaemonServer::Impl {
struct DispatchResult {
std::string response;
bool shutdown{false};
};
Impl(DaemonOptions daemon_options, std::filesystem::path path, State::StateStore state,
Watch::InotifyWatcher project_watcher)
: options{std::move(daemon_options)}, socket_path{std::move(path)},
state_store{std::move(state)}, watcher{std::move(project_watcher)},
started{Clock::now()} {}
~Impl() { close_socket(); }
Impl(const Impl &) = delete;
Impl &operator=(const Impl &) = delete;
[[nodiscard]] DaemonStatus current_status() const;
[[nodiscard]] std::string status_response() const;
DispatchResult dispatch(std::string_view line);
void close_socket() noexcept {
if (listen_fd >= 0) {
::close(listen_fd);
listen_fd = -1;
}
if (!created_socket) {
return;
}
created_socket = false;
struct stat current{};
if (::lstat(socket_path.c_str(), &current) == 0 && current.st_dev == socket_device &&
current.st_ino == socket_inode) {
::unlink(socket_path.c_str());
}
}
DaemonOptions options;
std::filesystem::path socket_path;
State::StateStore state_store;
Watch::InotifyWatcher watcher;
Clock::time_point started;
int listen_fd{-1};
bool created_socket{false};
dev_t socket_device{};
ino_t socket_inode{};
std::uint64_t watch_events{0};
std::string last_event_path;
std::uint64_t sequence{0};
};
DaemonStatus DaemonServer::Impl::current_status() const {
DaemonStatus status;
status.pid = static_cast<std::uint64_t>(::getpid());
status.uptime_ms = static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - started).count());
status.recorded_actions = state_store.recorded_action_count();
status.watched_directories = watcher.watched_directory_count();
status.watch_events = watch_events;
status.last_event_path = last_event_path;
status.sequence = sequence;
return status;
}
std::string DaemonServer::Impl::status_response() const {
const DaemonStatus status = current_status();
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"status"}});
object.emplace("pid", JsonValue{static_cast<std::int64_t>(status.pid)});
object.emplace("uptime_ms", JsonValue{static_cast<std::int64_t>(status.uptime_ms)});
object.emplace("recorded_actions",
JsonValue{static_cast<std::int64_t>(status.recorded_actions)});
object.emplace("watched_directories",
JsonValue{static_cast<std::int64_t>(status.watched_directories)});
object.emplace("watch_events", JsonValue{static_cast<std::int64_t>(status.watch_events)});
object.emplace("last_event_path", JsonValue{status.last_event_path});
object.emplace("sequence", JsonValue{static_cast<std::int64_t>(status.sequence)});
return serialize_response(JsonValue{std::move(object)});
}
DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view line) {
auto parsed = Void::Json::Strict::parse(line, kMaxJsonDepth);
if (!parsed) {
return {error_response(std::format("malformed JSON: {}", parsed.error().message)), false};
}
const auto *object = std::get_if<JsonValue::Object>(&parsed->value);
if (object == nullptr) {
return {error_response("request must be a JSON object"), false};
}
const auto op = object->find("op");
if (op == object->end()) {
return {error_response("request is missing \"op\""), false};
}
const auto *name = std::get_if<std::string>(&op->second.value);
if (name == nullptr) {
return {error_response("\"op\" must be a string"), false};
}
if (*name == "ping") {
return {ok_response("ping"), false};
}
if (*name == "status") {
return {status_response(), false};
}
if (*name == "shutdown") {
return {ok_response("shutdown"), true};
}
if (*name == "gc") {
std::uint64_t max_bytes = 0;
if (const auto entry = object->find("max_bytes"); entry != object->end()) {
const auto *value = std::get_if<std::int64_t>(&entry->second.value);
if (value == nullptr) {
return {error_response("\"max_bytes\" must be an integer"), false};
}
if (*value < 0) {
return {error_response("\"max_bytes\" must be non-negative"), false};
}
max_bytes = static_cast<std::uint64_t>(*value);
}
auto stats = state_store.gc(max_bytes);
if (!stats) {
return {error_response(stats.error().format()), false};
}
JsonValue::Object response;
response.emplace("ok", JsonValue{true});
response.emplace("op", JsonValue{std::string{"gc"}});
response.emplace("removed_blobs",
JsonValue{static_cast<std::int64_t>(stats->removed_blobs)});
response.emplace("freed_bytes", JsonValue{static_cast<std::int64_t>(stats->freed_bytes)});
response.emplace("retained_blobs",
JsonValue{static_cast<std::int64_t>(stats->retained_blobs)});
response.emplace("cleaned_staging_files",
JsonValue{static_cast<std::int64_t>(stats->cleaned_staging_files)});
return {serialize_response(JsonValue{std::move(response)}), false};
}
if (*name == "recover") {
auto recovered = state_store.recover();
if (!recovered) {
return {error_response(recovered.error().format()), false};
}
JsonValue::Object response;
response.emplace("ok", JsonValue{true});
response.emplace("op", JsonValue{std::string{"recover"}});
response.emplace("recovered", JsonValue{static_cast<std::int64_t>(*recovered)});
return {serialize_response(JsonValue{std::move(response)}), false};
}
return {error_response(std::format("unknown op '{}'", *name)), false};
}
DaemonServer::DaemonServer(std::unique_ptr<Impl> impl) noexcept : impl_{std::move(impl)} {}
DaemonServer::~DaemonServer() = default;
DaemonServer::DaemonServer(DaemonServer &&) noexcept = default;
DaemonServer &DaemonServer::operator=(DaemonServer &&) noexcept = default;
Void::Result::Result<DaemonServer, Void::Result::Error>
DaemonServer::create(DaemonOptions options) {
if (options.project_root.empty()) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: project_root must not be empty")};
}
if (options.build_root.empty()) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: build_root must not be empty")};
}
if (options.poll_interval.count() < 0) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: poll_interval must be non-negative")};
}
std::filesystem::path socket_path = options.socket_path;
if (socket_path.empty()) {
socket_path = options.build_root / ".vbs" / "vbs-daemon.sock";
}
auto address = make_address(socket_path);
if (!address) {
return std::unexpected{std::move(address.error())};
}
auto state_store = State::StateStore::open(options.build_root / ".vbs");
if (!state_store) {
return std::unexpected{state_store.error().with_context("daemon: opening state store")};
}
auto watcher = Watch::InotifyWatcher::create(options.project_root);
if (!watcher) {
return std::unexpected{watcher.error().with_context("daemon: creating project watcher")};
}
std::error_code ec;
if (socket_path.has_parent_path()) {
std::filesystem::create_directories(socket_path.parent_path(), ec);
if (ec) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io,
std::format("daemon: cannot create socket directory '{}': {}",
socket_path.parent_path().string(), ec.message()))};
}
}
const auto existing = std::filesystem::symlink_status(socket_path, ec);
if (ec && ec != std::errc::no_such_file_or_directory) {
return std::unexpected{make_error(Void::Result::ErrorKind::io,
std::format("daemon: cannot inspect socket path '{}': {}",
socket_path.string(), ec.message()))};
}
if (!ec && std::filesystem::exists(existing)) {
const auto probe = request(socket_path, R"({"op":"ping"})", kProbeTimeout);
bool live = false;
if (probe) {
auto parsed = Void::Json::Strict::parse(*probe, kMaxJsonDepth);
if (parsed) {
if (const auto *object = std::get_if<JsonValue::Object>(&parsed->value)) {
if (const auto ok = object->find("ok");
ok != object->end() && std::get_if<bool>(&ok->second.value) != nullptr &&
std::get<bool>(ok->second.value)) {
live = true;
}
}
}
}
if (live) {
return std::unexpected{
make_error(Void::Result::ErrorKind::conflict,
std::format("daemon: already running at '{}'", socket_path.string()))};
}
if (!std::filesystem::is_socket(existing)) {
return std::unexpected{make_error(
Void::Result::ErrorKind::conflict,
std::format("daemon: '{}' exists and is not a socket", socket_path.string()))};
}
std::filesystem::remove(socket_path, ec);
if (ec) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io,
std::format("daemon: cannot remove stale socket '{}': {}",
socket_path.string(), ec.message()))};
}
}
UniqueFd listen_fd{::socket(AF_UNIX, SOCK_STREAM, 0)};
if (!listen_fd.valid()) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: socket() failed", errno)};
}
if (auto cloexec = set_close_on_exec(listen_fd.get()); !cloexec) {
return std::unexpected{std::move(cloexec.error())};
}
bool bound = false;
const auto unlink_if_bound = [&]() noexcept {
if (bound) {
::unlink(socket_path.c_str());
}
};
if (::bind(listen_fd.get(), reinterpret_cast<const sockaddr *>(&*address),
sizeof(sockaddr_un)) < 0) {
return std::unexpected{
make_error(Void::Result::ErrorKind::io,
std::format("daemon: cannot bind '{}'", socket_path.string()), errno)};
}
bound = true;
if (::chmod(socket_path.c_str(), 0600) < 0) {
const int saved = errno;
unlink_if_bound();
return std::unexpected{make_error(
Void::Result::ErrorKind::io,
std::format("daemon: cannot chmod socket '{}'", socket_path.string()), saved)};
}
if (::listen(listen_fd.get(), kListenBacklog) < 0) {
const int saved = errno;
unlink_if_bound();
return std::unexpected{
make_error(Void::Result::ErrorKind::io,
std::format("daemon: cannot listen on '{}'", socket_path.string()), saved)};
}
struct stat socket_stat{};
if (::lstat(socket_path.c_str(), &socket_stat) != 0) {
const int saved = errno;
unlink_if_bound();
return std::unexpected{make_error(
Void::Result::ErrorKind::io,
std::format("daemon: cannot stat socket '{}'", socket_path.string()), saved)};
}
auto impl = std::make_unique<Impl>(std::move(options), socket_path, std::move(*state_store),
std::move(*watcher));
impl->listen_fd = listen_fd.release();
impl->created_socket = true;
impl->socket_device = socket_stat.st_dev;
impl->socket_inode = socket_stat.st_ino;
return DaemonServer{std::move(impl)};
}
Void::Result::Result<void, Void::Result::Error> DaemonServer::run(std::stop_token stop) {
if (!impl_) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: server has been moved from")};
}
auto &impl = *impl_;
if (impl.listen_fd < 0) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: server is not listening")};
}
std::size_t served = 0;
bool shutdown_requested = false;
while (!stop.stop_requested() && !shutdown_requested &&
(impl.options.max_requests == 0 || served < impl.options.max_requests)) {
pollfd descriptor{impl.listen_fd, POLLIN, 0};
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(impl.options.poll_interval));
if (ready < 0) {
if (errno == EINTR) {
continue;
}
impl.close_socket();
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
}
if (ready > 0 && (descriptor.revents & POLLIN) != 0) {
sockaddr_un peer{};
socklen_t peer_length = sizeof(peer);
const int client =
::accept(impl.listen_fd, reinterpret_cast<sockaddr *>(&peer), &peer_length);
if (client < 0) {
if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
impl.close_socket();
return std::unexpected{
make_error(Void::Result::ErrorKind::io, "daemon: accept failed", errno)};
}
} else {
UniqueFd client_fd{client};
if (auto cloexec = set_close_on_exec(client_fd.get()); !cloexec) {
continue;
}
auto line = read_line(client_fd.get(), kClientIoTimeout);
if (line) {
Impl::DispatchResult result = impl.dispatch(*line);
static_cast<void>(write_all(client_fd.get(), result.response + "\n"));
++served;
shutdown_requested = result.shutdown;
}
}
}
auto batch =
impl.watcher.poll_events(std::chrono::milliseconds{0}, std::chrono::milliseconds{0});
if (!batch) {
// Watcher failures are surfaced through the next scan; the daemon stays alive.
continue;
}
if (batch->overflowed || batch->rescan_required) {
static_cast<void>(impl.watcher.rescan_watches());
++impl.sequence;
}
if (!batch->changed_paths.empty()) {
impl.watch_events += batch->changed_paths.size();
impl.last_event_path = batch->changed_paths.back().string();
++impl.sequence;
}
}
impl.close_socket();
return {};
}
const std::filesystem::path &DaemonServer::socket_path() const noexcept {
static const std::filesystem::path empty;
return impl_ ? impl_->socket_path : empty;
}
DaemonStatus DaemonServer::status() const {
if (!impl_) {
return {};
}
return impl_->current_status();
}
Void::Result::Result<std::string, Void::Result::Error>
request(const std::filesystem::path &socket_path, std::string_view request_json,
std::chrono::milliseconds timeout) {
if (request_json.find('\n') != std::string_view::npos ||
request_json.find('\r') != std::string_view::npos) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: request must be a single JSON line")};
}
if (request_json.size() > kMaxRequestBytes) {
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
"daemon: request exceeds 64 KiB")};
}
auto fd = connect_socket(socket_path, timeout);
if (!fd) {
return std::unexpected{std::move(fd.error())};
}
std::string payload{request_json};
payload.push_back('\n');
if (auto written = write_all(fd->get(), payload); !written) {
return std::unexpected{std::move(written.error())};
}
return read_line(fd->get(), timeout);
}
} // namespace Void::Build::Daemon