#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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 kMaxPendingChanges = 4096U; 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(std::numeric_limits::max()); return timeout.count() > maximum ? std::numeric_limits::max() : static_cast(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 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 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 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(written)); } return {}; } Void::Result::Result 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(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(count)); if (line.size() > kMaxRequestBytes) { return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument, "daemon: request exceeds 64 KiB")}; } } } Void::Result::Result 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(&*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 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 evaluate_project_graph(const DaemonOptions &options, std::string_view profile_name, std::optional 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; } Void::Result::Result lower_graph(const DaemonOptions &options, const EvaluatedProject &evaluated, std::map> 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 materialize_project_dependencies( const DaemonOptions &options, State::StateStore &state, const EvaluatedProject &evaluated, std::size_t jobs, std::map> &imported_targets) { const auto &description = evaluated.description; if (description.dependencies.empty() && description.dependency_files.empty()) { return 0; } std::vector 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; } auto pinned_lock = Package::load_pinned_lock(options.project_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 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. std::string build_project(const DaemonOptions &options, State::StateStore &state, std::string_view profile_name, std::optional compiler_override, const std::vector &selected_targets, std::size_t jobs) { auto evaluated = evaluate_project_graph(options, profile_name, compiler_override, "build"); if (!evaluated) { return error_response(evaluated.error()); } std::map> imported_targets; auto materialized = materialize_project_dependencies(options, state, *evaluated, jobs, imported_targets); if (!materialized) { return error_response(materialized.error()); } auto graph = lower_graph(options, *evaluated, std::move(imported_targets), "build"); if (!graph) { return error_response(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 error_response(std::format("build: {}", report.error().format())); } JsonValue::Array failed_actions; 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}); failed_actions.emplace_back(std::move(failure)); } } JsonValue::Object object; object.emplace("ok", JsonValue{report->succeeded}); object.emplace("op", JsonValue{std::string{"build"}}); object.emplace("profile", JsonValue{evaluated->context.name}); object.emplace("targets", JsonValue{static_cast(graph->targets.size())}); object.emplace("actions", JsonValue{static_cast(graph->actions.size())}); object.emplace("dependencies", JsonValue{static_cast(*materialized)}); object.emplace("executed", JsonValue{static_cast(report->executed_count)}); object.emplace("cached", JsonValue{static_cast(report->cached_count)}); object.emplace("failed", JsonValue{static_cast(report->failed_count)}); object.emplace("diagnostic", JsonValue{report->diagnostic}); object.emplace("failed_actions", JsonValue{std::move(failed_actions)}); return serialize_response(JsonValue{std::move(object)}); } // Publishes the profile compilation database, selecting it when no editor selection exists. Void::Result::Result 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 compiler_override) { auto evaluated = evaluate_project_graph(options, profile_name, compiler_override, "compdb"); if (!evaluated) { return error_response(evaluated.error()); } auto graph = lower_graph(options, *evaluated, {}, "compdb"); if (!graph) { return error_response(graph.error()); } auto published = publish_compdb(options, *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(options, *published).string()}); object.emplace("entries", JsonValue{static_cast(published->entry_count)}); 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 compiler_override, std::string_view editor_name, bool force) { auto kind = Editor::parse_ide_kind(editor_name); if (!kind) { return error_response(kind.error().format()); } auto evaluated = evaluate_project_graph(options, profile_name, compiler_override, "ide_generate"); if (!evaluated) { return error_response(evaluated.error()); } auto graph = lower_graph(options, *evaluated, {}, "ide_generate"); if (!graph) { return error_response(graph.error()); } auto published = publish_compdb(options, *graph); if (!published) { return error_response(std::format("ide_generate: {}", published.error())); } const auto frontend = make_frontend_options(options); Editor::IdeConfigOptions ide; ide.project_root = options.project_root; ide.build_root = options.build_root; ide.sdk_include_dir = frontend.sdk_include_dir; ide.compdb_path = effective_compdb_path(options, *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 compiler_override) { auto evaluated = evaluate_project_graph(options, profile_name, compiler_override, "ide_query"); if (!evaluated) { return error_response(evaluated.error()); } auto graph = lower_graph(options, *evaluated, {}, "ide_query"); if (!graph) { return error_response(graph.error()); } const auto frontend = make_frontend_options(options); auto published = publish_compdb(options, *graph); if (!published) { return error_response(std::format("ide_query: {}", published.error())); } const auto compdb_path = effective_compdb_path(options, *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 compiler_override) { 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; std::vector 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); bool truncated = false; 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)); } 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(graph.targets.size())}); object.emplace("actions", JsonValue{static_cast(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(), ¤t) == 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 pending_changes; }; DaemonStatus DaemonServer::Impl::current_status() const { DaemonStatus status; status.pid = static_cast(::getpid()); status.uptime_ms = static_cast( std::chrono::duration_cast(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(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(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(status.pid)}); object.emplace("uptime_ms", JsonValue{static_cast(status.uptime_ms)}); object.emplace("recorded_actions", JsonValue{static_cast(status.recorded_actions)}); object.emplace("watched_directories", JsonValue{static_cast(status.watched_directories)}); object.emplace("watch_events", JsonValue{static_cast(status.watch_events)}); object.emplace("last_event_path", JsonValue{status.last_event_path}); object.emplace("sequence", JsonValue{static_cast(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(&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(&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(sequence)}); object.emplace("watch_events", JsonValue{static_cast(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 == "describe" || *name == "build" || *name == "ide_query" || *name == "ide_generate" || *name == "compdb_export") { std::string profile_name{"debug"}; if (const auto entry = object->find("profile"); entry != object->end()) { const auto *value = std::get_if(&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 compiler_override; if (const auto entry = object->find("compiler"); entry != object->end()) { const auto *value = std::get_if(&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}; } } 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), false}; } if (*name == "compdb_export") { return {compdb_export_project(options, profile_name, compiler_override), 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(&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(&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), false}; } std::vector selected_targets; if (const auto entry = object->find("targets"); entry != object->end()) { const auto *array = std::get_if(&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(&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(&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(*value); } return {build_project(options, state_store, profile_name, compiler_override, selected_targets, jobs), 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(&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(*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(stats->removed_blobs)}); response.emplace("freed_bytes", JsonValue{static_cast(stats->freed_bytes)}); response.emplace("retained_blobs", JsonValue{static_cast(stats->retained_blobs)}); response.emplace("cleaned_staging_files", JsonValue{static_cast(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(*recovered)}); return {serialize_response(JsonValue{std::move(response)}), false}; } return {error_response(std::format("unknown op '{}'", *name)), false}; } DaemonServer::DaemonServer(std::unique_ptr impl) noexcept : impl_{std::move(impl)} {} DaemonServer::~DaemonServer() = default; DaemonServer::DaemonServer(DaemonServer &&) noexcept = default; DaemonServer &DaemonServer::operator=(DaemonServer &&) noexcept = default; Void::Result::Result 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(&parsed->value)) { if (const auto ok = object->find("ok"); ok != object->end() && std::get_if(&ok->second.value) != nullptr && std::get(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(&*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(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 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(&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(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 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