Files
Build-System/src/Daemon/Daemon.cpp
T
faumaray 40fef50a6f
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 4s
VoidBuildSystem CI / signing-openssl-gcc16 (push) Failing after 41s
feat(daemon): serve bounded compile command entries to editor extensions
2026-12-03 22:58:17 +03:00

1918 lines
81 KiB
C++

#include <Void/Build/Daemon/Daemon.hpp>
#include <Void/Build.hpp>
#include <Void/Build/BootstrapConfig.hpp>
#include <Void/Build/Config/Frontend.hpp>
#include <Void/Build/Editor/CompDb.hpp>
#include <Void/Build/Execution/Scheduler.hpp>
#include <Void/Build/Graph/Graph.hpp>
#include <Void/Build/Package/Lockfile.hpp>
#include <Void/Build/Package/Resolver.hpp>
#include <Void/Build/Package/Toml.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Provenance/TrustedKeys.hpp>
#include <Void/Build/Provider/Provider.hpp>
#include <Void/Build/State/StateStore.hpp>
#include <Void/Build/Toolchain/Driver.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Watch/Watcher.hpp>
#include <Void/Configuration/Env.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/System/Path.hpp>
#include <algorithm>
#include <cerrno>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <format>
#include <fstream>
#include <limits>
#include <optional>
#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>
#include <vector>
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};
constexpr auto kDescribeEvalTimeout = std::chrono::seconds{10};
constexpr std::size_t kMaxDescribeProfileBytes = 128U;
constexpr std::size_t kMaxDescribeTargetNames = 128U;
constexpr std::size_t kMaxDescribeTargetNameBytes = 200U;
constexpr std::size_t kMaxBuildTargets = 64U;
constexpr std::size_t kMaxCompdbArguments = 256U;
constexpr std::size_t kMaxCompdbArgumentBytes = 1024U;
constexpr std::size_t kMaxCompdbEntries = 500U;
constexpr std::size_t kMaxPendingChanges = 4096U;
constexpr std::int64_t kMaxWatchWaitMs = 5000;
constexpr std::int64_t kDefaultWatchWaitMs = 2000;
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)});
}
// Mirrors the executable's frontend option construction: SDK include/source roots come from the
// generated BootstrapConfig, and the prebuilt SDK archive is discovered from the running binary
// or the configured binary directory.
Config::FrontendOptions make_frontend_options(const DaemonOptions &options) {
Config::FrontendOptions frontend;
frontend.project_root = options.project_root;
frontend.build_root = options.build_root;
frontend.sdk_include_dir = std::filesystem::path{Bootstrap::sdk_include_dir};
frontend.sdk_source_dir = std::filesystem::path{Bootstrap::sdk_source_dir};
frontend.eval_timeout = kDescribeEvalTimeout;
std::error_code ec;
std::vector<std::filesystem::path> sdk_candidates;
if (const auto self_exe = std::filesystem::read_symlink("/proc/self/exe", ec);
!ec && !self_exe.empty()) {
const auto self_root = self_exe.parent_path().parent_path();
sdk_candidates.push_back(self_root / "libVoidBuildSdk.a");
sdk_candidates.push_back(self_root / "libVoidBuild_Sdk.a");
sdk_candidates.push_back(self_root / "lib" / "libVoidBuildSdk.a");
}
if (!Bootstrap::binary_dir.empty()) {
const auto bin_dir = std::filesystem::path{Bootstrap::binary_dir};
sdk_candidates.push_back(bin_dir / "libVoidBuild_Sdk.a");
sdk_candidates.push_back(bin_dir / "out" / "libVoidBuildSdk.a");
sdk_candidates.push_back(bin_dir / "profiles" / "debug" / "out" / "libVoidBuildSdk.a");
}
for (const auto &candidate : sdk_candidates) {
if (std::filesystem::is_regular_file(candidate, ec)) {
frontend.sdk_library_path = candidate;
break;
}
}
return frontend;
}
struct EvaluatedProject {
ProfileContext context;
Graph::ProjectDescription description;
Toolchain::ToolchainCapabilities toolchain;
};
// Evaluates the project description in-process and lowers its graph. Workspace roots are
// rejected explicitly: member selection belongs to the CLI.
Void::Result::Result<EvaluatedProject, std::string>
evaluate_project_graph(const DaemonOptions &options, std::string_view profile_name,
std::optional<CompilerFamily> compiler_override, std::string_view op) {
if (Config::is_workspace_root(options.project_root)) {
return std::unexpected{
std::format("{}: workspace roots are not supported by the daemon yet", op)};
}
const auto frontend = make_frontend_options(options);
auto compiled = Config::compile_descriptor(frontend);
if (!compiled) {
return std::unexpected{std::format("{}: {}", op, compiled.error().format())};
}
auto profiles = Config::discover_profiles(*compiled, frontend);
if (!profiles) {
return std::unexpected{std::format("{}: {}", op, profiles.error().format())};
}
EvaluatedProject evaluated;
try {
evaluated.context =
profiles->resolve(profile_name, compiler_override, Toolchain::host_os_name(),
Toolchain::host_architecture_name());
} catch (const std::exception &ex) {
return std::unexpected{std::format("{}: {}", op, ex.what())};
}
auto description = Config::evaluate_project(*compiled, evaluated.context, frontend);
if (!description) {
return std::unexpected{std::format("{}: {}", op, description.error().format())};
}
auto toolchain =
Toolchain::discover_and_probe(evaluated.context, options.build_root / ".vbs" / "probes");
if (!toolchain) {
return std::unexpected{std::format("{}: {}", op, toolchain.error().format())};
}
evaluated.description = std::move(*description);
evaluated.toolchain = std::move(*toolchain);
return evaluated;
}
struct WorkspaceMemberDir {
std::string name;
std::filesystem::path path;
};
// Evaluates workspace.cpp, canonicalizes members, and exports VBS_WORKSPACE_MEMBER_<name>
// so member descriptors resolve cross-member dependencies exactly like the CLI.
Void::Result::Result<std::vector<WorkspaceMemberDir>, std::string>
evaluate_workspace_members(const DaemonOptions &options) {
const auto frontend = make_frontend_options(options);
auto compiled = Config::compile_descriptor(frontend);
if (!compiled) {
return std::unexpected{std::format("workspace: {}", compiled.error().format())};
}
auto workspace = Config::evaluate_workspace(*compiled, frontend);
if (!workspace) {
return std::unexpected{std::format("workspace: {}", workspace.error().format())};
}
if (workspace->members.empty()) {
return std::unexpected{std::string{"workspace declares no members"}};
}
if (workspace->members.size() > 64) {
return std::unexpected{std::string{"workspace declares too many members (max 64)"}};
}
std::vector<WorkspaceMemberDir> members;
for (const auto &member : workspace->members) {
std::filesystem::path dir = member.path;
if (!dir.is_absolute()) {
dir = options.project_root / dir;
}
std::error_code ec;
const auto canonical = std::filesystem::weakly_canonical(dir, ec);
if (ec || !std::filesystem::is_directory(canonical)) {
return std::unexpected{std::format("workspace member '{}' path '{}' is not a directory",
member.name, dir.string())};
}
const std::string env_name = "VBS_WORKSPACE_MEMBER_" + member.name;
(void)::setenv(env_name.c_str(), canonical.c_str(), 1);
members.push_back(WorkspaceMemberDir{member.name, canonical});
}
return members;
}
DaemonOptions member_options(const DaemonOptions &options,
const std::filesystem::path &member_dir) {
DaemonOptions member = options;
member.project_root = member_dir;
member.lock_root = options.project_root;
return member;
}
// Resolves an optional workspace member selector into effective daemon options. Non-workspace
// roots reject a member selector; workspace roots require one.
Void::Result::Result<DaemonOptions, std::string>
resolve_member_options(const DaemonOptions &options, std::string_view member) {
if (!Config::is_workspace_root(options.project_root)) {
if (!member.empty()) {
return std::unexpected{
std::format("\"member\" is only valid for workspace roots (got '{}')", member)};
}
return options;
}
auto members = evaluate_workspace_members(options);
if (!members) {
return std::unexpected{members.error()};
}
if (member.empty()) {
return std::unexpected{std::string{"workspace roots require \"member\""}};
}
const auto match = std::ranges::find_if(
*members, [&](const WorkspaceMemberDir &candidate) { return candidate.name == member; });
if (match == members->end()) {
return std::unexpected{std::format("unknown workspace member '{}'", member)};
}
return member_options(options, match->path);
}
JsonValue::Array bounded_target_names(const Graph::BuildGraph &graph, bool &truncated) {
std::vector<std::string> target_names;
target_names.reserve(graph.targets.size());
for (const auto &target : graph.targets) {
target_names.push_back(target.name);
}
std::ranges::sort(target_names);
if (target_names.size() > kMaxDescribeTargetNames) {
target_names.resize(kMaxDescribeTargetNames);
truncated = true;
}
JsonValue::Array names_json;
names_json.reserve(target_names.size());
for (auto &name : target_names) {
if (name.size() > kMaxDescribeTargetNameBytes) {
name.resize(kMaxDescribeTargetNameBytes);
truncated = true;
}
names_json.emplace_back(std::move(name));
}
return names_json;
}
Void::Result::Result<Graph::BuildGraph, std::string>
lower_graph(const DaemonOptions &options, const EvaluatedProject &evaluated,
std::map<std::string, Graph::ImportedTargetInterface, std::less<>> imported_targets,
std::string_view op) {
Graph::GraphLowerOptions lower_options;
lower_options.project_root = options.project_root;
lower_options.build_root = options.build_root;
lower_options.imported_targets = std::move(imported_targets);
auto graph =
Graph::lower_project_graph(evaluated.description, evaluated.toolchain, lower_options);
if (!graph) {
return std::unexpected{std::format("{}: {}", op, graph.error().format())};
}
return std::move(*graph);
}
// Resolves, materializes, and imports the project's declared dependencies into typed target
// interfaces. Returns the number of materialized sources.
Void::Result::Result<std::size_t, std::string> materialize_project_dependencies(
const DaemonOptions &options, State::StateStore &state, const EvaluatedProject &evaluated,
std::size_t jobs,
std::map<std::string, Graph::ImportedTargetInterface, std::less<>> &imported_targets) {
const auto &description = evaluated.description;
if (description.dependencies.empty() && description.dependency_files.empty()) {
return 0;
}
std::vector<Package::NormalizedDependency> toml_deps;
for (const auto &dep_file : description.dependency_files) {
const auto path = std::filesystem::path{dep_file}.is_absolute()
? std::filesystem::path{dep_file}
: (options.project_root / dep_file);
auto loaded = Package::load_dependencies_toml(path);
if (!loaded) {
return std::unexpected{std::format("build: {}", loaded.error().format())};
}
toml_deps.insert(toml_deps.end(), loaded->begin(), loaded->end());
}
auto merged = Package::merge_dependencies(description.dependencies, toml_deps);
if (!merged) {
return std::unexpected{std::format("build: {}", merged.error().format())};
}
if (merged->empty()) {
return 0;
}
const auto lock_root = options.lock_root.empty() ? options.project_root : options.lock_root;
auto pinned_lock = Package::load_pinned_lock(lock_root / "vbs.lock");
if (!pinned_lock) {
return std::unexpected{std::format("build: {}", pinned_lock.error().format())};
}
Package::ResolveOptions resolve_options;
resolve_options.project_root = options.project_root;
resolve_options.build_root = options.build_root;
resolve_options.pinned_lock = *pinned_lock;
resolve_options.default_registry_url = Void::Configuration::get_env_or("VBS_REGISTRY_URL", "");
resolve_options.registry_auth =
Package::RegistryAuth{Void::Configuration::get_env_or("VBS_REGISTRY_TOKEN", "")};
const std::string trusted_environment =
Void::Configuration::get_env_or("VBS_TRUSTED_PUBLIC_KEYS", "");
std::optional<std::string_view> trusted_environment_value;
if (!trusted_environment.empty()) {
trusted_environment_value = trusted_environment;
}
auto trusted_keys =
Provenance::load_trusted_keys({}, options.project_root, trusted_environment_value);
if (!trusted_keys) {
return std::unexpected{std::format("build: {}", trusted_keys.error().format())};
}
resolve_options.trusted_public_keys = std::move(*trusted_keys);
auto resolved =
Package::resolve_and_materialize_dependencies(evaluated.context, *merged, resolve_options);
if (!resolved) {
return std::unexpected{std::format("build: {}", resolved.error().format())};
}
const auto frontend = make_frontend_options(options);
for (const auto &[dependency, source] : resolved->materialized) {
DependencyRecord effective = dependency;
std::error_code ec;
if (effective.builder.empty()) {
if (std::filesystem::is_regular_file(source.source_dir / "build.cpp", ec)) {
effective.builder = "native";
} else if (std::filesystem::is_regular_file(source.source_dir / "CMakeLists.txt", ec)) {
effective.builder = "cmake";
} else if (std::filesystem::is_regular_file(source.source_dir / "meson.build", ec)) {
effective.builder = "meson";
}
}
if (effective.builder != "cmake" && effective.builder != "meson" &&
effective.builder != "conan" && effective.builder != "native") {
continue;
}
Provider::ProviderRequest request{effective,
source,
evaluated.context,
evaluated.toolchain,
options.build_root / ".vbs" / "providers",
Provider::ProviderMode::FullBuild,
{},
frontend.sdk_include_dir,
frontend.sdk_source_dir,
frontend.sdk_library_path.empty()
? std::nullopt
: std::optional{frontend.sdk_library_path},
&state,
jobs};
auto exported = Provider::resolve_foreign_provider(request);
if (!exported) {
return std::unexpected{std::format("build: {}", exported.error().format())};
}
for (const auto &[name, interface] : exported->targets) {
imported_targets[name] = interface;
}
}
return resolved->materialized.size();
}
// Bounded build-serving request: resolves dependencies, lowers the project graph, and executes it
// in-process against the daemon's warm StateStore.
struct TestOutcome {
std::string name;
bool passed{false};
int exit_code{-1};
std::string stdout_tail;
std::string stderr_tail;
};
constexpr std::size_t kMaxTestOutputBytes = 4096U;
std::string bounded_tail(const std::string &text) {
if (text.size() <= kMaxTestOutputBytes) {
return text;
}
return text.substr(text.size() - kMaxTestOutputBytes);
}
struct BuildOutcome {
std::string profile;
std::size_t targets{0};
std::size_t actions{0};
std::size_t dependencies{0};
std::size_t executed{0};
std::size_t cached{0};
std::size_t failed{0};
bool succeeded{false};
std::string diagnostic;
JsonValue::Array failed_actions;
std::vector<TestOutcome> tests;
std::size_t tests_passed{0};
std::size_t tests_failed{0};
};
Void::Result::Result<BuildOutcome, std::string> execute_project_build(
const DaemonOptions &options, State::StateStore &state, std::string_view profile_name,
std::optional<CompilerFamily> compiler_override,
const std::vector<std::string> &selected_targets, std::size_t jobs, bool run_tests) {
auto evaluated = evaluate_project_graph(options, profile_name, compiler_override, "build");
if (!evaluated) {
return std::unexpected{evaluated.error()};
}
std::map<std::string, Graph::ImportedTargetInterface, std::less<>> imported_targets;
auto materialized =
materialize_project_dependencies(options, state, *evaluated, jobs, imported_targets);
if (!materialized) {
return std::unexpected{materialized.error()};
}
auto graph = lower_graph(options, *evaluated, std::move(imported_targets), "build");
if (!graph) {
return std::unexpected{graph.error()};
}
Execution::ExecutionOptions exec_options;
exec_options.jobs = jobs;
exec_options.selected_targets = selected_targets;
auto report = Execution::execute_graph(*graph, state, exec_options);
if (!report) {
return std::unexpected{std::format("build: {}", report.error().format())};
}
BuildOutcome outcome;
outcome.profile = evaluated->context.name;
outcome.targets = graph->targets.size();
outcome.actions = graph->actions.size();
outcome.dependencies = *materialized;
outcome.executed = report->executed_count;
outcome.cached = report->cached_count;
outcome.failed = report->failed_count;
outcome.succeeded = report->succeeded;
outcome.diagnostic = report->diagnostic;
for (const auto &result : report->results) {
if (!result.succeeded) {
JsonValue::Object failure;
failure.emplace("action", JsonValue{result.action_id});
failure.emplace("target", JsonValue{result.target_name});
failure.emplace("error", JsonValue{result.error_message});
outcome.failed_actions.emplace_back(std::move(failure));
}
}
// Runs declared test targets after a successful build, mirroring `vbs test`.
if (run_tests && report->succeeded) {
for (const auto &target : graph->targets) {
if (target.kind != TargetKind::Test || target.primary_outputs.empty()) {
continue;
}
if (!selected_targets.empty() &&
!std::ranges::contains(selected_targets, target.name)) {
continue;
}
Void::Build::Platform::ProcessRequest test_request;
test_request.executable = target.primary_outputs.front();
test_request.working_directory = options.project_root;
test_request.timeout = std::chrono::seconds{300};
auto test_result = Void::Build::Platform::run_supervised(test_request);
TestOutcome test;
test.name = target.name;
if (!test_result) {
test.stderr_tail = test_result.error().message();
} else {
test.passed = test_result->succeeded();
test.exit_code = test_result->exit_code;
test.stdout_tail = bounded_tail(test_result->stdout_data);
test.stderr_tail = bounded_tail(test_result->stderr_data);
}
if (test.passed) {
++outcome.tests_passed;
} else {
++outcome.tests_failed;
}
outcome.tests.push_back(std::move(test));
}
if (outcome.tests_failed > 0) {
outcome.succeeded = false;
}
}
return outcome;
}
JsonValue::Object build_outcome_json(const BuildOutcome &outcome) {
JsonValue::Object object;
object.emplace("profile", JsonValue{outcome.profile});
object.emplace("targets", JsonValue{static_cast<std::int64_t>(outcome.targets)});
object.emplace("actions", JsonValue{static_cast<std::int64_t>(outcome.actions)});
object.emplace("dependencies", JsonValue{static_cast<std::int64_t>(outcome.dependencies)});
object.emplace("executed", JsonValue{static_cast<std::int64_t>(outcome.executed)});
object.emplace("cached", JsonValue{static_cast<std::int64_t>(outcome.cached)});
object.emplace("failed", JsonValue{static_cast<std::int64_t>(outcome.failed)});
object.emplace("diagnostic", JsonValue{outcome.diagnostic});
object.emplace("failed_actions", JsonValue{outcome.failed_actions});
object.emplace("tests_passed", JsonValue{static_cast<std::int64_t>(outcome.tests_passed)});
object.emplace("tests_failed", JsonValue{static_cast<std::int64_t>(outcome.tests_failed)});
JsonValue::Array tests;
for (const auto &test : outcome.tests) {
JsonValue::Object entry;
entry.emplace("name", JsonValue{test.name});
entry.emplace("passed", JsonValue{test.passed});
entry.emplace("exit_code", JsonValue{static_cast<std::int64_t>(test.exit_code)});
entry.emplace("stdout", JsonValue{test.stdout_tail});
entry.emplace("stderr", JsonValue{test.stderr_tail});
tests.emplace_back(std::move(entry));
}
object.emplace("tests", JsonValue{std::move(tests)});
return object;
}
std::string build_project(const DaemonOptions &options, State::StateStore &state,
std::string_view profile_name,
std::optional<CompilerFamily> compiler_override,
const std::vector<std::string> &selected_targets, std::size_t jobs,
std::string_view selected_member, bool run_tests) {
const bool workspace = Config::is_workspace_root(options.project_root);
// Workspace-wide build: every member in declared order, sharing the root lock and CAS.
if (workspace && selected_member.empty()) {
auto members = evaluate_workspace_members(options);
if (!members) {
return error_response(members.error());
}
JsonValue::Array member_array;
std::size_t executed = 0;
std::size_t cached = 0;
std::size_t failed = 0;
bool all_ok = true;
for (const auto &member : *members) {
const auto member_opts = member_options(options, member.path);
auto outcome =
execute_project_build(member_opts, state, profile_name, compiler_override,
selected_targets, jobs, run_tests);
if (!outcome) {
return error_response(
std::format("build: member '{}': {}", member.name, outcome.error()));
}
JsonValue::Object entry = build_outcome_json(*outcome);
entry.emplace("name", JsonValue{member.name});
entry.emplace("ok", JsonValue{outcome->succeeded});
member_array.emplace_back(std::move(entry));
executed += outcome->executed;
cached += outcome->cached;
failed += outcome->failed;
all_ok = all_ok && outcome->succeeded;
}
JsonValue::Object object;
object.emplace("ok", JsonValue{all_ok});
object.emplace("op", JsonValue{std::string{run_tests ? "test" : "build"}});
object.emplace("workspace", JsonValue{true});
object.emplace("members", JsonValue{std::move(member_array)});
object.emplace("executed", JsonValue{static_cast<std::int64_t>(executed)});
object.emplace("cached", JsonValue{static_cast<std::int64_t>(cached)});
object.emplace("failed", JsonValue{static_cast<std::int64_t>(failed)});
return serialize_response(JsonValue{std::move(object)});
}
auto effective_result = resolve_member_options(options, selected_member);
if (!effective_result) {
return error_response(std::format("build: {}", effective_result.error()));
}
auto outcome = execute_project_build(*effective_result, state, profile_name, compiler_override,
selected_targets, jobs, run_tests);
if (!outcome) {
return error_response(outcome.error());
}
JsonValue::Object object = build_outcome_json(*outcome);
object.emplace("ok", JsonValue{outcome->succeeded});
object.emplace("op", JsonValue{std::string{run_tests ? "test" : "build"}});
if (workspace) {
object.emplace("member", JsonValue{std::string{selected_member}});
}
return serialize_response(JsonValue{std::move(object)});
}
// Publishes the profile compilation database, selecting it when no editor selection exists.
Void::Result::Result<Editor::EditorGeneration, std::string>
publish_compdb(const DaemonOptions &options, const Graph::BuildGraph &graph) {
const auto frontend = make_frontend_options(options);
const auto existing_selection =
Editor::read_selection_state(options.project_root).value_or(std::nullopt);
Editor::PublishOptions publish;
publish.project_root = options.project_root;
publish.build_root = options.build_root;
publish.update_selection = !existing_selection.has_value();
publish.sdk_include_dir = frontend.sdk_include_dir;
auto published = Editor::publish_profile_compdb(graph, publish);
if (!published) {
return std::unexpected{published.error().format()};
}
return *published;
}
std::filesystem::path effective_compdb_path(const DaemonOptions &options,
const Editor::EditorGeneration &published) {
std::error_code ec;
const auto root_compdb = options.build_root / "compile_commands.json";
return std::filesystem::exists(root_compdb, ec) ? root_compdb : published.compdb_path;
}
// Publishes the compilation database and reports its path and entry count.
std::string compdb_export_project(const DaemonOptions &options, std::string_view profile_name,
std::optional<CompilerFamily> compiler_override,
std::string_view member) {
auto effective_result = resolve_member_options(options, member);
if (!effective_result) {
return error_response(std::format("compdb: {}", effective_result.error()));
}
const DaemonOptions &effective = *effective_result;
auto evaluated = evaluate_project_graph(effective, profile_name, compiler_override, "compdb");
if (!evaluated) {
return error_response(evaluated.error());
}
auto graph = lower_graph(effective, *evaluated, {}, "compdb");
if (!graph) {
return error_response(graph.error());
}
auto published = publish_compdb(effective, *graph);
if (!published) {
return error_response(std::format("compdb: {}", published.error()));
}
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"compdb"}});
object.emplace("profile", JsonValue{evaluated->context.name});
object.emplace("compdb", JsonValue{effective_compdb_path(effective, *published).string()});
object.emplace("entries", JsonValue{static_cast<std::int64_t>(published->entry_count)});
return serialize_response(JsonValue{std::move(object)});
}
// Renders the evaluated target dependency graph as Graphviz DOT or JSON.
std::string graph_project(const DaemonOptions &options, std::string_view profile_name,
std::optional<CompilerFamily> compiler_override, std::string_view member,
std::string_view format) {
if (format != "dot" && format != "json") {
return error_response(
std::format("graph: unsupported format '{}' (expected dot or json)", format));
}
auto effective_result = resolve_member_options(options, member);
if (!effective_result) {
return error_response(std::format("graph: {}", effective_result.error()));
}
auto evaluated =
evaluate_project_graph(*effective_result, profile_name, compiler_override, "graph");
if (!evaluated) {
return error_response(evaluated.error());
}
const auto &description = evaluated->description;
const auto link_name = [](const LinkRecord &link) {
return link.kind == LinkKind::Imported ? (link.dependency + "::" + link.target)
: link.target;
};
std::string rendered;
if (format == "json") {
rendered = "{\"profile\":" + Util::json_quote(description.profile.name) + ",\"targets\":";
rendered += Util::json_array(description.targets, [](const TargetRecord &target) {
return "{\"name\":" + Util::json_quote(target.name) +
",\"kind\":" + Util::json_quote(target_kind_name(target.kind)) + ",\"links\":" +
Util::json_array(target.links,
[](const LinkRecord &link) {
return Util::json_quote(
link.kind == LinkKind::Imported
? (link.dependency + "::" + link.target)
: link.target);
}) +
'}';
});
rendered += '}';
} else {
rendered = "digraph vbs_targets {\n rankdir=LR;\n";
for (const auto &target : description.targets) {
rendered += " " + Util::json_quote(target.name) + " [label=" +
Util::json_quote(target.name + "\\n(" +
std::string{target_kind_name(target.kind)} + ")") +
"];\n";
}
for (const auto &target : description.targets) {
for (const auto &prerequisite : target.prerequisites) {
rendered += " " + Util::json_quote(target.name) + " -> " +
Util::json_quote(prerequisite) + " [style=dashed];\n";
}
for (const auto &link : target.links) {
rendered += " " + Util::json_quote(target.name) + " -> " +
Util::json_quote(link_name(link)) + ";\n";
}
}
rendered += "}\n";
}
return "{\"ok\":true,\"op\":\"graph\",\"format\":" + Util::json_quote(format) +
",\"profile\":" + Util::json_quote(description.profile.name) +
",\"graph\":" + Util::json_quote(rendered) + '}';
}
// Returns bounded compile_commands entries from the active compilation database, optionally
// filtered by a path suffix. Editor extensions use this instead of parsing the file themselves.
std::string compdb_entries_project(const DaemonOptions &options, std::string_view file_filter,
std::size_t limit) {
auto selection = Editor::read_selection_state(options.project_root);
if (!selection) {
return error_response(std::format("compdb_entries: {}", selection.error().format()));
}
std::filesystem::path compdb_path;
if (selection->has_value()) {
compdb_path = (*selection)->selected_compdb_path;
} else {
std::error_code ec;
const auto root_alias = options.build_root / "compile_commands.json";
if (std::filesystem::exists(root_alias, ec)) {
compdb_path = root_alias;
}
}
if (compdb_path.empty()) {
return error_response(
"compdb_entries: no compilation database is published; run compdb export first");
}
auto text = Void::FileSystem::read_file(compdb_path);
if (!text) {
return error_response(std::format("compdb_entries: {}", text.error().format()));
}
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return error_response("compdb_entries: compilation database is not valid JSON");
}
const auto *entries = std::get_if<JsonValue::Array>(&parsed->value);
if (entries == nullptr) {
return error_response("compdb_entries: compilation database must be a JSON array");
}
JsonValue::Array matched;
std::size_t total = 0;
for (const auto &entry : *entries) {
const auto *object = std::get_if<JsonValue::Object>(&entry.value);
if (object == nullptr) {
continue;
}
const auto file_it = object->find("file");
if (file_it == object->end()) {
continue;
}
const auto *file = std::get_if<std::string>(&file_it->second.value);
if (file == nullptr) {
continue;
}
if (!file_filter.empty() &&
!std::string_view{*file}.ends_with(std::string_view{file_filter})) {
continue;
}
++total;
if (matched.size() >= limit) {
continue;
}
JsonValue::Object projected;
projected.emplace("file", JsonValue{*file});
const auto copy_string = [&](std::string_view field_name) {
if (const auto it = object->find(field_name); it != object->end()) {
if (const auto *value = std::get_if<std::string>(&it->second.value)) {
projected.emplace(std::string{field_name}, JsonValue{*value});
}
}
};
copy_string("directory");
copy_string("output");
copy_string("command");
if (const auto it = object->find("arguments"); it != object->end()) {
if (const auto *arguments = std::get_if<JsonValue::Array>(&it->second.value)) {
JsonValue::Array bounded;
for (const auto &argument : *arguments) {
const auto *value = std::get_if<std::string>(&argument.value);
if (value == nullptr) {
continue;
}
if (bounded.size() >= kMaxCompdbArguments) {
projected.emplace("arguments_truncated", JsonValue{true});
break;
}
bounded.emplace_back(value->size() > kMaxCompdbArgumentBytes
? value->substr(0, kMaxCompdbArgumentBytes)
: *value);
}
projected.emplace("arguments", JsonValue{std::move(bounded)});
}
}
matched.emplace_back(std::move(projected));
}
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"compdb_entries"}});
object.emplace("compdb", JsonValue{compdb_path.string()});
object.emplace("total", JsonValue{static_cast<std::int64_t>(total)});
object.emplace("returned", JsonValue{static_cast<std::int64_t>(matched.size())});
object.emplace("entries", JsonValue{std::move(matched)});
return serialize_response(JsonValue{std::move(object)});
}
// Switches the active editor profile to an already-published compilation database.
std::string compdb_use_project(const DaemonOptions &options, std::string_view profile_name) {
auto state =
Editor::select_editor_profile(options.project_root, options.build_root, profile_name);
if (!state) {
return error_response(std::format("compdb_use: {}", state.error().format()));
}
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"compdb_use"}});
object.emplace("profile", JsonValue{state->selected_profile});
object.emplace("generation_id", JsonValue{state->selected_generation_id});
object.emplace("ticket", JsonValue{static_cast<std::int64_t>(state->ticket)});
object.emplace("compdb", JsonValue{state->selected_compdb_path.string()});
return serialize_response(JsonValue{std::move(object)});
}
// Reports the active editor selection and the published compilation database state.
std::string editor_status_project(const DaemonOptions &options) {
auto selection = Editor::read_selection_state(options.project_root);
if (!selection) {
return error_response(std::format("editor_status: {}", selection.error().format()));
}
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"editor_status"}});
if (!selection->has_value()) {
object.emplace("selection", JsonValue{nullptr});
object.emplace("compdb_exists", JsonValue{false});
return serialize_response(JsonValue{std::move(object)});
}
const auto &state = **selection;
JsonValue::Object selected;
selected.emplace("ticket", JsonValue{static_cast<std::int64_t>(state.ticket)});
selected.emplace("profile", JsonValue{state.selected_profile});
selected.emplace("build_root", JsonValue{state.selected_build_root.string()});
selected.emplace("generation_id", JsonValue{state.selected_generation_id});
selected.emplace("compdb_path", JsonValue{state.selected_compdb_path.string()});
selected.emplace("alias_active", JsonValue{state.managed_root_alias_active});
selected.emplace("alias_warning", JsonValue{state.root_alias_warning});
object.emplace("selection", JsonValue{std::move(selected)});
std::ifstream compdb{state.selected_compdb_path};
const bool compdb_exists = compdb.good();
object.emplace("compdb_exists", JsonValue{compdb_exists});
if (compdb_exists) {
std::string text{std::istreambuf_iterator<char>{compdb}, std::istreambuf_iterator<char>{}};
auto parsed = Void::Json::Strict::parse(text);
if (parsed) {
if (const auto *array = std::get_if<JsonValue::Array>(&parsed->value)) {
object.emplace("compdb_entries",
JsonValue{static_cast<std::int64_t>(array->size())});
}
}
}
return serialize_response(JsonValue{std::move(object)});
}
// Publishes the compilation database and writes the requested editor configuration files.
std::string ide_generate_project(const DaemonOptions &options, std::string_view profile_name,
std::optional<CompilerFamily> compiler_override,
std::string_view editor_name, bool force,
std::string_view member) {
auto kind = Editor::parse_ide_kind(editor_name);
if (!kind) {
return error_response(kind.error().format());
}
auto effective_result = resolve_member_options(options, member);
if (!effective_result) {
return error_response(std::format("ide_generate: {}", effective_result.error()));
}
const DaemonOptions &effective = *effective_result;
auto evaluated =
evaluate_project_graph(effective, profile_name, compiler_override, "ide_generate");
if (!evaluated) {
return error_response(evaluated.error());
}
auto graph = lower_graph(effective, *evaluated, {}, "ide_generate");
if (!graph) {
return error_response(graph.error());
}
auto published = publish_compdb(effective, *graph);
if (!published) {
return error_response(std::format("ide_generate: {}", published.error()));
}
const auto frontend = make_frontend_options(effective);
Editor::IdeConfigOptions ide;
ide.project_root = effective.project_root;
ide.build_root = effective.build_root;
ide.sdk_include_dir = frontend.sdk_include_dir;
ide.compdb_path = effective_compdb_path(effective, *published);
ide.editor = *kind;
ide.force = force;
std::error_code ec;
ide.vbs_executable = std::filesystem::read_symlink("/proc/self/exe", ec);
if (ec || ide.vbs_executable.empty()) {
ide.vbs_executable = "vbs";
}
auto report = Editor::generate_ide_configs(*graph, ide);
if (!report) {
return error_response(std::format("ide_generate: {}", report.error().format()));
}
JsonValue::Array written;
for (const auto &path : report->written_files) {
written.emplace_back(path.string());
}
JsonValue::Array skipped;
for (const auto &path : report->skipped_existing_files) {
skipped.emplace_back(path.string());
}
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"ide_generate"}});
object.emplace("profile", JsonValue{evaluated->context.name});
object.emplace("editor", JsonValue{std::string{Editor::ide_kind_name(*kind)}});
object.emplace("written", JsonValue{std::move(written)});
object.emplace("skipped", JsonValue{std::move(skipped)});
return serialize_response(JsonValue{std::move(object)});
}
// Publishes the profile compilation database and returns the IDE query metadata JSON.
std::string ide_query_project(const DaemonOptions &options, std::string_view profile_name,
std::optional<CompilerFamily> compiler_override,
std::string_view member) {
auto effective_result = resolve_member_options(options, member);
if (!effective_result) {
return error_response(std::format("ide_query: {}", effective_result.error()));
}
const DaemonOptions &effective = *effective_result;
auto evaluated =
evaluate_project_graph(effective, profile_name, compiler_override, "ide_query");
if (!evaluated) {
return error_response(evaluated.error());
}
auto graph = lower_graph(effective, *evaluated, {}, "ide_query");
if (!graph) {
return error_response(graph.error());
}
const auto frontend = make_frontend_options(effective);
auto published = publish_compdb(effective, *graph);
if (!published) {
return error_response(std::format("ide_query: {}", published.error()));
}
const auto compdb_path = effective_compdb_path(effective, *published);
std::string query =
Editor::format_ide_query_json(*graph, compdb_path, frontend.sdk_include_dir);
// The socket protocol is one JSON object per line: the embedded query must not contain
// newlines before the final response terminator.
while (!query.empty() && (query.back() == '\n' || query.back() == '\r')) {
query.pop_back();
}
return "{\"ok\":true,\"op\":\"ide_query\",\"compdb\":" +
Util::json_quote(compdb_path.string()) + ",\"query\":" + query + '}';
}
// Lowers the project graph to a bounded summary without executing it.
std::string describe_project(const DaemonOptions &options, std::string_view profile_name,
std::optional<CompilerFamily> compiler_override) {
if (Config::is_workspace_root(options.project_root)) {
auto members = evaluate_workspace_members(options);
if (!members) {
return error_response(members.error());
}
JsonValue::Array member_array;
for (const auto &member : *members) {
const auto member_opts = member_options(options, member.path);
auto evaluated =
evaluate_project_graph(member_opts, profile_name, compiler_override, "describe");
if (!evaluated) {
return error_response(evaluated.error());
}
auto lowered = lower_graph(member_opts, *evaluated, {}, "describe");
if (!lowered) {
return error_response(lowered.error());
}
bool truncated = false;
JsonValue::Array names = bounded_target_names(*lowered, truncated);
JsonValue::Object entry;
entry.emplace("name", JsonValue{member.name});
entry.emplace("path", JsonValue{member.path.string()});
entry.emplace("targets", JsonValue{static_cast<std::int64_t>(lowered->targets.size())});
entry.emplace("actions", JsonValue{static_cast<std::int64_t>(lowered->actions.size())});
entry.emplace("target_names", JsonValue{std::move(names)});
if (truncated) {
entry.emplace("target_names_truncated", JsonValue{true});
}
member_array.emplace_back(std::move(entry));
}
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"describe"}});
object.emplace("workspace", JsonValue{true});
object.emplace("members", JsonValue{std::move(member_array)});
return serialize_response(JsonValue{std::move(object)});
}
auto evaluated = evaluate_project_graph(options, profile_name, compiler_override, "describe");
if (!evaluated) {
return error_response(evaluated.error());
}
auto lowered = lower_graph(options, *evaluated, {}, "describe");
if (!lowered) {
return error_response(lowered.error());
}
const auto &graph = *lowered;
const auto &context = evaluated->context;
bool truncated = false;
JsonValue::Array names_json = bounded_target_names(graph, truncated);
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"describe"}});
object.emplace("profile", JsonValue{context.name});
object.emplace("targets", JsonValue{static_cast<std::int64_t>(graph.targets.size())});
object.emplace("actions", JsonValue{static_cast<std::int64_t>(graph.actions.size())});
object.emplace("target_names", JsonValue{std::move(names_json)});
if (truncated) {
object.emplace("target_names_truncated", JsonValue{true});
}
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 record_watch_batch(const Watch::WatchBatch &batch);
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};
std::vector<std::filesystem::path> pending_changes;
};
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;
}
void DaemonServer::Impl::record_watch_batch(const Watch::WatchBatch &batch) {
if (batch.overflowed || batch.rescan_required) {
static_cast<void>(watcher.rescan_watches());
++sequence;
}
if (batch.changed_paths.empty()) {
return;
}
watch_events += batch.changed_paths.size();
last_event_path = batch.changed_paths.back().string();
++sequence;
for (const auto &path : batch.changed_paths) {
pending_changes.push_back(path);
}
if (pending_changes.size() > kMaxPendingChanges) {
pending_changes.erase(
pending_changes.begin(),
pending_changes.begin() +
static_cast<std::ptrdiff_t>(pending_changes.size() - kMaxPendingChanges));
}
}
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 == "watch_poll") {
auto batch =
watcher.poll_events(std::chrono::milliseconds{0}, std::chrono::milliseconds{0});
if (!batch) {
return {error_response(std::format("watch_poll: {}", batch.error().format())), false};
}
record_watch_batch(*batch);
JsonValue::Array changed;
for (const auto &path : pending_changes) {
changed.emplace_back(path.string());
}
pending_changes.clear();
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"watch_poll"}});
object.emplace("sequence", JsonValue{static_cast<std::int64_t>(sequence)});
object.emplace("watch_events", JsonValue{static_cast<std::int64_t>(watch_events)});
object.emplace("changed", JsonValue{std::move(changed)});
object.emplace("overflowed", JsonValue{batch->overflowed});
object.emplace("rescan_required", JsonValue{batch->rescan_required});
return {serialize_response(JsonValue{std::move(object)}), false};
}
if (*name == "editor_status") {
return {editor_status_project(options), false};
}
if (*name == "compdb_entries") {
std::string file_filter;
if (const auto entry = object->find("file"); entry != object->end()) {
const auto *value = std::get_if<std::string>(&entry->second.value);
if (value == nullptr || value->size() > 4096) {
return {error_response("\"file\" must be a bounded string"), false};
}
file_filter = *value;
}
std::size_t limit = 50;
if (const auto entry = object->find("limit"); entry != object->end()) {
const auto *value = std::get_if<std::int64_t>(&entry->second.value);
if (value == nullptr || *value < 0 ||
*value > static_cast<std::int64_t>(kMaxCompdbEntries)) {
return {error_response(std::format("\"limit\" must be an integer in [0, {}]",
kMaxCompdbEntries)),
false};
}
limit = static_cast<std::size_t>(*value);
}
return {compdb_entries_project(options, file_filter, limit), false};
}
if (*name == "compdb_use") {
const auto entry = object->find("profile");
if (entry == object->end()) {
return {error_response("compdb_use requires \"profile\""), false};
}
const auto *value = std::get_if<std::string>(&entry->second.value);
if (value == nullptr || value->empty() || value->size() > kMaxDescribeProfileBytes) {
return {error_response("\"profile\" must be a bounded non-empty string"), false};
}
return {compdb_use_project(options, *value), false};
}
if (*name == "watch_wait") {
std::int64_t timeout_ms = kDefaultWatchWaitMs;
if (const auto entry = object->find("timeout_ms"); entry != object->end()) {
const auto *value = std::get_if<std::int64_t>(&entry->second.value);
if (value == nullptr || *value < 0 || *value > kMaxWatchWaitMs) {
return {error_response(std::format("\"timeout_ms\" must be an integer in [0, {}]",
kMaxWatchWaitMs)),
false};
}
timeout_ms = *value;
}
bool timed_out = false;
if (pending_changes.empty() && timeout_ms > 0) {
auto batch = watcher.poll_events(std::chrono::milliseconds{timeout_ms},
std::chrono::milliseconds{0});
if (!batch) {
return {error_response(std::format("watch_wait: {}", batch.error().format())),
false};
}
timed_out =
batch->changed_paths.empty() && !batch->overflowed && !batch->rescan_required;
record_watch_batch(*batch);
}
JsonValue::Array changed;
for (const auto &path : pending_changes) {
changed.emplace_back(path.string());
}
pending_changes.clear();
JsonValue::Object object;
object.emplace("ok", JsonValue{true});
object.emplace("op", JsonValue{std::string{"watch_wait"}});
object.emplace("sequence", JsonValue{static_cast<std::int64_t>(sequence)});
object.emplace("watch_events", JsonValue{static_cast<std::int64_t>(watch_events)});
object.emplace("changed", JsonValue{std::move(changed)});
object.emplace("timed_out", JsonValue{timed_out});
return {serialize_response(JsonValue{std::move(object)}), false};
}
if (*name == "describe" || *name == "build" || *name == "test" || *name == "ide_query" ||
*name == "ide_generate" || *name == "compdb_export" || *name == "graph") {
std::string profile_name{"debug"};
if (const auto entry = object->find("profile"); entry != object->end()) {
const auto *value = std::get_if<std::string>(&entry->second.value);
if (value == nullptr) {
return {error_response("\"profile\" must be a string"), false};
}
if (value->empty()) {
return {error_response("\"profile\" must not be empty"), false};
}
if (value->size() > kMaxDescribeProfileBytes) {
return {error_response("\"profile\" is too long"), false};
}
profile_name = *value;
}
std::optional<CompilerFamily> compiler_override;
if (const auto entry = object->find("compiler"); entry != object->end()) {
const auto *value = std::get_if<std::string>(&entry->second.value);
if (value == nullptr) {
return {error_response("\"compiler\" must be a string"), false};
}
try {
compiler_override = parse_compiler(*value);
} catch (const std::exception &ex) {
return {error_response(ex.what()), false};
}
}
std::string member;
if (const auto entry = object->find("member"); entry != object->end()) {
const auto *value = std::get_if<std::string>(&entry->second.value);
if (value == nullptr || value->empty() || value->size() > 128) {
return {error_response("\"member\" must be a bounded non-empty string"), false};
}
member = *value;
}
if (*name == "describe") {
return {describe_project(options, profile_name, compiler_override), false};
}
if (*name == "ide_query") {
return {ide_query_project(options, profile_name, compiler_override, member), false};
}
if (*name == "compdb_export") {
return {compdb_export_project(options, profile_name, compiler_override, member), false};
}
if (*name == "graph") {
std::string graph_format{"dot"};
if (const auto entry = object->find("format"); entry != object->end()) {
const auto *value = std::get_if<std::string>(&entry->second.value);
if (value == nullptr) {
return {error_response("\"format\" must be a string"), false};
}
graph_format = *value;
}
return {graph_project(options, profile_name, compiler_override, member, graph_format),
false};
}
if (*name == "ide_generate") {
std::string editor_name{"all"};
if (const auto entry = object->find("editor"); entry != object->end()) {
const auto *value = std::get_if<std::string>(&entry->second.value);
if (value == nullptr || value->empty()) {
return {error_response("\"editor\" must be a non-empty string"), false};
}
editor_name = *value;
}
bool force = false;
if (const auto entry = object->find("force"); entry != object->end()) {
const auto *value = std::get_if<bool>(&entry->second.value);
if (value == nullptr) {
return {error_response("\"force\" must be a boolean"), false};
}
force = *value;
}
return {ide_generate_project(options, profile_name, compiler_override, editor_name,
force, member),
false};
}
std::vector<std::string> selected_targets;
if (const auto entry = object->find("targets"); entry != object->end()) {
const auto *array = std::get_if<JsonValue::Array>(&entry->second.value);
if (array == nullptr) {
return {error_response("\"targets\" must be an array of strings"), false};
}
if (array->size() > kMaxBuildTargets) {
return {error_response("\"targets\" has too many entries"), false};
}
for (const auto &item : *array) {
const auto *text = std::get_if<std::string>(&item.value);
if (text == nullptr || text->empty() ||
text->size() > kMaxDescribeTargetNameBytes) {
return {error_response("\"targets\" entries must be non-empty bounded strings"),
false};
}
selected_targets.push_back(*text);
}
}
std::size_t jobs = 0;
if (const auto entry = object->find("jobs"); entry != object->end()) {
const auto *value = std::get_if<std::int64_t>(&entry->second.value);
if (value == nullptr || *value < 0 || *value > 256) {
return {error_response("\"jobs\" must be an integer in [0, 256]"), false};
}
jobs = static_cast<std::size_t>(*value);
}
return {build_project(options, state_store, profile_name, compiler_override,
selected_targets, jobs, member, *name == "test"),
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;
}
impl.record_watch_batch(*batch);
}
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