feat(cache): add shared HTTP action cache and parallel snapshot hashing
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 4s

- D1: RemoteCasClient + registry /api/v1/cas endpoints with bearer auth and digest verification, StateStore remote action/blob APIs, build-path-independent action keys, --remote-cache CLI
- D2: parallel snapshot revalidation hashing via Void::Concurrency::ThreadPool
- Verified in Docker GCC 16: 8/8 CTest suites, cross-build-dir 100% cache hit, 5001-file warm no-op 374 ms
- Fix self-host recipe source list for RemoteCache.cpp and accept GCC 16 -lgcc_s_asneeded
This commit is contained in:
faumaray committed 2026-12-03 12:36:21 +03:00
1 parent 6c225c2dff
commit 09c0a91d1d
19 files changed
+1213 -18

No files matched your search

+319
View File
@@ -3,7 +3,9 @@
#include <Void/Async/ThreadPool.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
@@ -126,6 +128,256 @@ bool restore_outputs_from_cache(const Graph::ActionNode &action,
return true;
}
// Build-path-independent path mapping used for shared remote cache keys and records.
// Longest prefix wins so nested build/root prefixes are replaced before their parents.
struct PathMapper {
std::vector<std::pair<std::string, std::string>> pairs;
[[nodiscard]] std::string normalize(std::string_view input) const {
std::string out{input};
for (const auto &[prefix, token] : pairs) {
std::size_t pos = 0;
while ((pos = out.find(prefix, pos)) != std::string::npos) {
out.replace(pos, prefix.size(), token);
pos += token.size();
}
}
return out;
}
[[nodiscard]] std::string denormalize(std::string_view input) const {
std::string out{input};
for (const auto &[prefix, token] : pairs) {
std::size_t pos = 0;
while ((pos = out.find(token, pos)) != std::string::npos) {
out.replace(pos, token.size(), prefix);
pos += prefix.size();
}
}
return out;
}
};
PathMapper make_path_mapper(const Graph::BuildGraph &graph) {
std::vector<std::pair<std::string, std::string>> pairs;
auto add = [&](const std::filesystem::path &path, std::string token) {
if (!path.empty()) {
pairs.emplace_back(path.lexically_normal().string(), std::move(token));
}
};
add(graph.snapshot_materialized_root, "${SNAPSHOT}");
add(graph.profile_build_dir, "${PROFILE}");
if (!graph.profile_build_dir.empty()) {
// The whole build root (probes, .vbs state, other profiles) must stay portable too.
add(graph.profile_build_dir.parent_path().parent_path(), "${BUILD}");
}
add(graph.project_root, "${PROJECT}");
std::ranges::sort(pairs,
[](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
return PathMapper{std::move(pairs)};
}
std::string portable_executable(const std::filesystem::path &exe, const PathMapper &mapper) {
const std::string raw = exe.string();
const std::string normalized = mapper.normalize(raw);
if (normalized == raw && exe.has_filename()) {
// Toolchain identity already covers the compiler; keep external tool paths portable.
return exe.filename().string();
}
return normalized;
}
// Portable action identity: logical action id + flags + input content digests, with all
// build-root/project-root prefixes normalized away. Absolute output paths are excluded.
std::string compute_remote_action_key(const Graph::ActionNode &action,
const Graph::BuildGraph &graph, RunDigestCache &digest_cache,
const PathMapper &mapper) {
Util::Sha256Hasher hasher;
hasher.update_length_prefixed("vbs-remote-action-v1");
hasher.update_length_prefixed(graph.profile_identity);
hasher.update_length_prefixed(graph.toolchain.identity_hash);
hasher.update_length_prefixed(action.id);
hasher.update_u64(static_cast<std::uint64_t>(action.kind));
hasher.update_length_prefixed(portable_executable(action.executable, mapper));
hasher.update_u64(action.arguments.size());
for (const auto &arg : action.arguments) {
hasher.update_length_prefixed(mapper.normalize(arg));
}
hasher.update_length_prefixed(mapper.normalize(action.response_file_content));
hasher.update_u64(action.environment.size());
for (const auto &[k, v] : action.environment) {
hasher.update_length_prefixed(k);
hasher.update_length_prefixed(mapper.normalize(v));
}
hasher.update_u64(action.declared_inputs.size());
for (const auto &in : action.declared_inputs) {
hasher.update_length_prefixed(mapper.normalize(in.string()));
if (auto digest = digest_cache.hash_file(in); digest) {
hasher.update_length_prefixed(*digest);
} else {
hasher.update_length_prefixed("<missing>");
}
}
hasher.update_u64(action.nondeterministic ? 1u : 0u);
return hasher.finalize_hex();
}
std::string serialize_remote_record(const State::ActionSuccessRecord &record,
const Graph::ActionNode &action, const PathMapper &mapper,
std::string_view remote_key) {
using Util::json_array;
using Util::json_quote;
std::vector<State::BlobRef> ordered_outputs;
ordered_outputs.reserve(action.declared_outputs.size());
for (const auto &out : action.declared_outputs) {
const auto it = record.outputs.find(out.string());
if (it == record.outputs.end()) {
return {};
}
ordered_outputs.push_back(it->second);
}
std::string json = "{\"schema_version\":1,\"action_key\":" + json_quote(remote_key) +
",\"profile_identity\":" + json_quote(record.profile_identity) +
",\"target_name\":" + json_quote(record.target_name) +
",\"recorded_epoch\":" + std::to_string(record.recorded_epoch) +
",\"outputs\":";
json += json_array(ordered_outputs, [](const State::BlobRef &ref) {
return "{\"sha256\":" + json_quote(ref.sha256) + ",\"size\":" + std::to_string(ref.size) +
",\"mode\":" + std::to_string(ref.mode) + '}';
});
json += ",\"discovered_inputs\":[";
bool first = true;
for (const auto &[path, digest] : record.discovered_inputs) {
if (!first) {
json += ',';
}
first = false;
json += "{\"path\":" + json_quote(mapper.normalize(path)) +
",\"sha256\":" + json_quote(digest) + '}';
}
json += "],\"lookup_guards\":";
json += json_array(record.lookup_guards, [&](const Snapshot::LookupGuard &guard) {
std::vector<std::string> roots;
roots.reserve(guard.search_roots.size());
for (const auto &root : guard.search_roots) {
roots.push_back(mapper.normalize(root));
}
return "{\"search_roots\":" + json_array(roots, json_quote) +
",\"lookup_name\":" + json_quote(guard.lookup_name) +
",\"matched_root_index\":" + std::to_string(guard.matched_root_index) +
",\"matched_sha256\":" + json_quote(guard.matched_sha256) + '}';
});
json += '}';
return json;
}
using RemoteJson = Void::Json::Strict::Value;
const RemoteJson *remote_find(const RemoteJson::Object &obj, const std::string &key) {
const auto it = obj.find(key);
return it == obj.end() ? nullptr : &it->second;
}
std::string remote_str(const RemoteJson::Object &obj, const std::string &key) {
const auto *value = remote_find(obj, key);
if (!value) {
return {};
}
const auto *text = std::get_if<std::string>(&value->value);
return text ? *text : std::string{};
}
std::int64_t remote_i64(const RemoteJson::Object &obj, const std::string &key) {
const auto *value = remote_find(obj, key);
if (!value) {
return 0;
}
const auto *number = std::get_if<std::int64_t>(&value->value);
return number ? *number : 0;
}
std::optional<State::ActionSuccessRecord> parse_remote_record(std::string_view json_text,
const Graph::ActionNode &action,
const PathMapper &mapper) {
auto parsed = Void::Json::Strict::parse(json_text);
if (!parsed) {
return std::nullopt;
}
const auto *root = std::get_if<RemoteJson::Object>(&parsed->value);
if (!root) {
return std::nullopt;
}
State::ActionSuccessRecord record;
record.profile_identity = remote_str(*root, "profile_identity");
record.target_name = remote_str(*root, "target_name");
record.recorded_epoch = remote_i64(*root, "recorded_epoch");
const auto *outputs = remote_find(*root, "outputs");
const auto *output_array = outputs ? std::get_if<RemoteJson::Array>(&outputs->value) : nullptr;
if (!output_array || output_array->size() != action.declared_outputs.size()) {
return std::nullopt;
}
for (std::size_t i = 0; i < output_array->size(); ++i) {
const auto *obj = std::get_if<RemoteJson::Object>(&(*output_array)[i].value);
if (!obj) {
return std::nullopt;
}
State::BlobRef ref;
ref.sha256 = remote_str(*obj, "sha256");
ref.size = static_cast<std::uint64_t>(remote_i64(*obj, "size"));
ref.mode = static_cast<std::uint32_t>(remote_i64(*obj, "mode"));
if (ref.sha256.size() != 64) {
return std::nullopt;
}
record.outputs[action.declared_outputs[i].string()] = std::move(ref);
}
if (const auto *discovered = remote_find(*root, "discovered_inputs")) {
if (const auto *array = std::get_if<RemoteJson::Array>(&discovered->value)) {
for (const auto &item : *array) {
const auto *obj = std::get_if<RemoteJson::Object>(&item.value);
if (!obj) {
continue;
}
const auto path = remote_str(*obj, "path");
const auto digest = remote_str(*obj, "sha256");
if (!path.empty() && !digest.empty()) {
record.discovered_inputs[mapper.denormalize(path)] = digest;
}
}
}
}
if (const auto *guards = remote_find(*root, "lookup_guards")) {
if (const auto *array = std::get_if<RemoteJson::Array>(&guards->value)) {
for (const auto &item : *array) {
const auto *obj = std::get_if<RemoteJson::Object>(&item.value);
if (!obj) {
continue;
}
Snapshot::LookupGuard guard;
guard.lookup_name = remote_str(*obj, "lookup_name");
guard.matched_root_index = static_cast<int>(remote_i64(*obj, "matched_root_index"));
guard.matched_sha256 = remote_str(*obj, "matched_sha256");
if (const auto *roots = remote_find(*obj, "search_roots")) {
if (const auto *root_array = std::get_if<RemoteJson::Array>(&roots->value)) {
for (const auto &root_value : *root_array) {
if (const auto *text = std::get_if<std::string>(&root_value.value)) {
guard.search_roots.push_back(mapper.denormalize(*text));
}
}
}
}
record.lookup_guards.push_back(std::move(guard));
}
}
}
return record;
}
std::set<std::string> collect_ancestors(const Graph::BuildGraph &graph, const std::string &id) {
std::set<std::string> ancestors;
std::queue<std::string> q;
@@ -309,6 +561,7 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
std::atomic<std::size_t> started_exec_count{0};
bool abort_scheduling = false;
RunDigestCache digest_cache;
const PathMapper path_mapper = make_path_mapper(graph);
auto action_label = [&](const Graph::ActionNode &act) -> std::string {
auto rel_name = [&](const std::filesystem::path &p) -> std::string {
@@ -385,6 +638,40 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
}
}
// 1b. Shared remote action cache lookup (Track D1) on local miss.
if (act.cacheable && !act.nondeterministic && options.use_cache &&
state.has_remote_cache()) {
const std::string remote_key =
compute_remote_action_key(act, graph, digest_cache, path_mapper);
auto remote_json = state.fetch_remote_action(remote_key);
if (remote_json && remote_json->has_value()) {
auto remote_record = parse_remote_record(**remote_json, act, path_mapper);
bool usable = remote_record.has_value();
if (usable) {
for (const auto &entry : remote_record->outputs) {
auto have = state.ensure_remote_blob(entry.second.sha256);
if (!have || !*have) {
usable = false;
break;
}
}
}
if (usable &&
verify_discovered_inputs_unchanged(remote_record->discovered_inputs,
digest_cache) &&
(verify_outputs_match_record(act, *remote_record, digest_cache) ||
restore_outputs_from_cache(act, *remote_record, state, digest_cache))) {
remote_record->action_key = remote_key;
(void)state.record_action_success(*remote_record);
res.succeeded = true;
res.from_cache = true;
res.exit_code = 0;
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
return res;
}
}
}
const std::size_t seq = started_exec_count.fetch_add(1, std::memory_order_relaxed) + 1;
Void::Log::info("Build", "[{:>2}/{}] {}", seq, selected_indices.size(), label);
emit_event(ExecutionEvent::Kind::ActionStarted, act, label, seq);
@@ -529,6 +816,38 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
committed.error().message());
return res;
}
// Best-effort publication to the shared remote cache (Track D1): blobs first,
// then the action record. Cache upload failures never fail the build.
if (state.has_remote_cache()) {
const std::string remote_key =
compute_remote_action_key(act, graph, digest_cache, path_mapper);
bool uploaded = true;
for (const auto &out : act.declared_outputs) {
const auto it = rec.outputs.find(out.string());
if (it == rec.outputs.end()) {
uploaded = false;
break;
}
auto pushed = state.publish_remote_blob(it->second.sha256);
if (!pushed) {
Void::Log::warn("Remote", "Skipping remote cache upload for '{}': {}",
act.id, pushed.error().message());
uploaded = false;
break;
}
}
if (uploaded) {
const auto json = serialize_remote_record(rec, act, path_mapper, remote_key);
if (!json.empty()) {
auto pushed = state.publish_remote_action(remote_key, json);
if (!pushed) {
Void::Log::warn("Remote", "Skipping remote action record for '{}': {}",
act.id, pushed.error().message());
}
}
}
}
}
res.succeeded = true;
+22
View File
@@ -502,6 +502,8 @@ struct BuildCmdOptions {
std::optional<std::string> editor_profile;
std::optional<std::string> compiler_arg;
std::optional<std::string> jobs_arg;
std::optional<std::string> remote_cache_arg;
std::optional<std::string> remote_cache_token_env;
bool no_cache{false};
bool locked{false};
bool offline{false};
@@ -591,6 +593,21 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) {
return 1;
}
const std::string remote_cache_url =
opts.remote_cache_arg
? *opts.remote_cache_arg
: std::string{Void::Configuration::get_env_or("VBS_REMOTE_CACHE", "")};
if (!remote_cache_url.empty()) {
State::RemoteCacheConfig remote_cfg;
remote_cfg.url = remote_cache_url;
const std::string token_env = opts.remote_cache_token_env
? *opts.remote_cache_token_env
: std::string{"VBS_REMOTE_CACHE_TOKEN"};
remote_cfg.bearer_token = Void::Configuration::get_env_or(token_env, "");
state->configure_remote_cache(std::move(remote_cfg));
Void::Log::info("Cache", "Using shared remote action cache at {}", remote_cache_url);
}
const auto lock_path = project_root / "vbs.lock";
auto pinned_lock = Package::load_pinned_lock(lock_path);
if (!pinned_lock) {
@@ -1980,6 +1997,11 @@ int main(int argc, char **argv) {
.option_many("--build-source", "", "Additional build description source",
build_opts.extra_build_sources)
.option("--jobs", "-j", "Maximum parallel compilation/link jobs", build_opts.jobs_arg)
.option("--remote-cache", "", "Shared HTTP action cache URL (or VBS_REMOTE_CACHE)",
build_opts.remote_cache_arg)
.option("--remote-cache-token-env", "",
"Environment variable holding the remote cache bearer token",
build_opts.remote_cache_token_env)
.flag("--locked", "", "Require existing up-to-date vbs.lock", build_opts.locked)
.flag("--offline", "", "Disallow network fetches", build_opts.offline)
.flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache)
+4 -1
View File
@@ -123,8 +123,11 @@ std::vector<std::string> split_shell_tokens(std::string_view text) {
}
bool is_safe_system_link_flag(std::string_view tok) {
// GCC 16 ships an as-needed linker script for libgcc_s, which CMake exposes as
// `-lgcc_s_asneeded` in codemodel link fragments; it is a real system library.
return tok == "-pthread" || tok == "-lpthread" || tok == "-ldl" || tok == "-lm" ||
tok == "-lrt" || tok.starts_with("-Wl,");
tok == "-lrt" || tok == "-lgcc" || tok == "-lgcc_s" || tok == "-lgcc_s_asneeded" ||
tok.starts_with("-Wl,");
}
std::string trim_copy(std::string_view sv) {
+43 -7
View File
@@ -1,18 +1,22 @@
#include <Void/Build/Snapshot/Snapshot.hpp>
#include <Void/Async/ThreadPool.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/System/Types.hpp>
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <dirent.h>
#include <fcntl.h>
#include <format>
#include <functional>
#include <future>
#include <set>
#include <sys/stat.h>
#include <thread>
#include <unistd.h>
namespace Void::Build::Snapshot {
@@ -32,6 +36,29 @@ bool is_excluded_name(std::string_view name, const std::vector<std::string> &exc
return std::ranges::contains(excluded, name);
}
// Bounded-parallel index loop used for content hashing (Track D2). Small inputs stay
// sequential to avoid thread-pool startup overhead.
template <typename Fn> void parallel_for_indices(std::size_t count, Fn fn) {
constexpr std::size_t kParallelThreshold = 32;
if (count < kParallelThreshold) {
for (std::size_t i = 0; i < count; ++i) {
fn(i);
}
return;
}
const std::size_t workers =
std::min<std::size_t>(count, std::max(1u, std::thread::hardware_concurrency()));
Void::Concurrency::ThreadPool pool{workers};
std::vector<std::future<void>> futures;
futures.reserve(count);
for (std::size_t i = 0; i < count; ++i) {
futures.push_back(pool.submit([&fn, i] { fn(i); }));
}
for (auto &future : futures) {
future.get();
}
}
bool path_has_excluded_component(const std::filesystem::path &rel_path,
const std::vector<std::string> &excluded) {
for (const auto &part : rel_path) {
@@ -393,15 +420,24 @@ Void::Result::Result<InputSnapshot, Void::Result::Error> capture_snapshot(
}
// Revalidation pass before sealing: detect concurrent mutations during capture.
bool mutated = false;
for (const auto &[logical, src_path] : source_files_to_verify) {
// Content hashing runs on a bounded thread pool for large trees (Track D2).
std::vector<std::pair<std::string, std::filesystem::path>> files_to_rehash;
files_to_rehash.reserve(source_files_to_verify.size());
for (const auto &entry : source_files_to_verify) {
files_to_rehash.push_back(entry);
}
std::atomic<bool> mutated{false};
parallel_for_indices(files_to_rehash.size(), [&](std::size_t i) {
if (mutated.load(std::memory_order_relaxed)) {
return;
}
const auto &[logical, src_path] = files_to_rehash[i];
auto rehash = Util::sha256_file_hex(src_path);
if (!rehash || *rehash != snap.entries.at(logical).sha256) {
mutated = true;
break;
mutated.store(true, std::memory_order_relaxed);
}
}
if (!mutated) {
});
if (!mutated.load()) {
for (const auto &[logical_dir, dir_path] : dirs_to_verify) {
auto meta = Platform::stat_lstat(dir_path);
if (!meta) {
@@ -422,7 +458,7 @@ Void::Result::Result<InputSnapshot, Void::Result::Error> capture_snapshot(
}
}
}
if (mutated) {
if (mutated.load()) {
continue;
}
+355
View File
@@ -0,0 +1,355 @@
#include <Void/Build/State/RemoteCache.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Core/Scope.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Str.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <format>
#include <map>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
namespace Void::Build::State {
namespace {
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, std::move(msg));
}
bool is_valid_sha256_hex(std::string_view hex) {
if (hex.size() != 64) {
return false;
}
return std::ranges::all_of(
hex, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); });
}
struct ParsedUrl {
std::string scheme;
std::string host;
std::uint16_t port{80};
std::string base_path;
};
Void::Result::Result<ParsedUrl, Void::Result::Error> parse_remote_url(std::string_view url) {
url = Void::Str::trim_ascii(url);
const auto sep = url.find("://");
if (sep == std::string_view::npos) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"remote cache URL must include http:// or https://")};
}
ParsedUrl out;
out.scheme = Void::Str::to_lower_ascii(url.substr(0, sep));
if (out.scheme != "http" && out.scheme != "https") {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"unsupported remote cache URL scheme")};
}
const auto rest = url.substr(sep + 3);
const auto slash = rest.find('/');
const auto authority = slash == std::string_view::npos ? rest : rest.substr(0, slash);
out.base_path =
slash == std::string_view::npos ? std::string{} : std::string{rest.substr(slash)};
while (!out.base_path.empty() && out.base_path.back() == '/') {
out.base_path.pop_back();
}
const auto colon = authority.rfind(':');
if (colon != std::string_view::npos) {
out.host = std::string{authority.substr(0, colon)};
int p = 0;
if (!Void::Str::to_int(authority.substr(colon + 1), p) || p <= 0 || p > 65535) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"invalid port in remote cache URL")};
}
out.port = static_cast<std::uint16_t>(p);
} else {
out.host = std::string{authority};
out.port = out.scheme == "https" ? 443 : 80;
}
if (out.host.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"empty host in remote cache URL")};
}
return out;
}
struct HttpReply {
std::uint16_t status{0};
std::string body;
};
bool send_all(int fd, std::string_view data) {
std::size_t off = 0;
while (off < data.size()) {
const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
off += static_cast<std::size_t>(n);
}
return true;
}
Void::Result::Result<HttpReply, Void::Result::Error>
http_exchange(const ParsedUrl &parsed, std::string_view method, std::string_view path,
const std::map<std::string, std::string, std::less<>> &headers,
std::string_view body) {
const std::string full_path = parsed.base_path + std::string{path};
if (parsed.scheme == "http") {
struct addrinfo hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo *res = nullptr;
const std::string port_s = std::to_string(parsed.port);
if (::getaddrinfo(parsed.host.c_str(), port_s.c_str(), &hints, &res) != 0 || !res) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("remote cache: failed resolving host '{}'", parsed.host))};
}
auto free_ai = Void::Scope::on_exit([&] { ::freeaddrinfo(res); });
const int fd = ::socket(res->ai_family, res->ai_socktype | SOCK_CLOEXEC, res->ai_protocol);
if (fd < 0) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"remote cache: socket() failed")};
}
Void::System::OwnedFd guard{fd};
struct timeval tv{60, 0};
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
if (::connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("remote cache: connect to {}:{} failed", parsed.host, parsed.port))};
}
std::string req = std::format("{} {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n"
"Content-Length: {}\r\n",
method, full_path, parsed.host, parsed.port, body.size());
for (const auto &[k, v] : headers) {
req += k + ": " + v + "\r\n";
}
req += "\r\n";
req += body;
if (!send_all(fd, req)) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "remote cache: send() failed")};
}
std::string raw;
std::array<char, 16384> buf{};
for (;;) {
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
if (n > 0) {
raw.append(buf.data(), static_cast<std::size_t>(n));
} else if (n == 0) {
break;
} else if (errno != EINTR) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"remote cache: recv() failed")};
}
}
const auto hdr_end = raw.find("\r\n\r\n");
if (hdr_end == std::string::npos) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"remote cache: malformed HTTP response")};
}
HttpReply reply;
const auto first_crlf = raw.find("\r\n");
const std::string_view status_line{
raw.data(), first_crlf == std::string::npos ? raw.size() : first_crlf};
const auto sp1 = status_line.find(' ');
if (sp1 != std::string_view::npos) {
int code = 0;
if (Void::Str::to_int(status_line.substr(sp1 + 1, 3), code)) {
reply.status = static_cast<std::uint16_t>(code);
}
}
reply.body = raw.substr(hdr_end + 4);
return reply;
}
// HTTPS via curl preserves TLS certificate verification (never disables TLS).
auto curl = Platform::resolve_executable("curl");
if (!curl) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found,
"HTTPS remote cache requires curl (Void::Net not linked)")};
}
const std::string full_url =
std::format("https://{}:{}{}", parsed.host, parsed.port, full_path);
Platform::ProcessRequest req;
req.executable = *curl;
req.arguments = {"--silent", "--show-error", "--proto", "=https",
"-X", std::string{method}, "-w", "\n%{http_code}"};
for (const auto &[k, v] : headers) {
req.arguments.push_back("-H");
req.arguments.push_back(k + ": " + v);
}
if (!body.empty()) {
req.arguments.push_back("--data-binary");
req.arguments.push_back("@-");
req.stdin_data = std::string{body};
}
req.arguments.push_back(full_url);
req.timeout = std::chrono::seconds{120};
auto proc = Platform::run_supervised(req);
if (!proc || !proc->succeeded()) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("remote cache HTTPS request failed: {}",
proc ? proc->stderr_data : proc.error().message()))};
}
HttpReply reply;
const auto nl = proc->stdout_data.rfind('\n');
if (nl != std::string::npos) {
int code = 0;
if (Void::Str::to_int(Void::Str::trim_ascii(proc->stdout_data.substr(nl + 1)), code)) {
reply.status = static_cast<std::uint16_t>(code);
}
reply.body = proc->stdout_data.substr(0, nl);
}
return reply;
}
std::map<std::string, std::string, std::less<>> auth_headers(const RemoteCacheConfig &config) {
std::map<std::string, std::string, std::less<>> headers;
if (!config.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + config.bearer_token;
}
return headers;
}
Void::Result::Result<ParsedUrl, Void::Result::Error> require_url(const RemoteCacheConfig &config) {
if (config.url.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"remote cache is not configured")};
}
return parse_remote_url(config.url);
}
} // namespace
RemoteCasClient::RemoteCasClient(RemoteCacheConfig config) : config_{std::move(config)} {}
Void::Result::Result<void, Void::Result::Error>
RemoteCasClient::put_blob(std::string_view sha256, std::string_view bytes) const {
if (!is_valid_sha256_hex(sha256)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"remote cache: invalid blob SHA-256")};
}
auto parsed = require_url(config_);
if (!parsed) {
return std::unexpected{parsed.error()};
}
auto headers = auth_headers(config_);
headers["Content-Type"] = "application/octet-stream";
const std::string path = "/api/v1/cas/blobs/" + std::string{sha256};
auto reply = http_exchange(*parsed, "PUT", path, headers, bytes);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200 && reply->status != 201) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("remote cache: blob upload failed with HTTP {}", reply->status))};
}
return {};
}
Void::Result::Result<std::optional<std::string>, Void::Result::Error>
RemoteCasClient::get_blob(std::string_view sha256) const {
if (!is_valid_sha256_hex(sha256)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"remote cache: invalid blob SHA-256")};
}
auto parsed = require_url(config_);
if (!parsed) {
return std::unexpected{parsed.error()};
}
const std::string path = "/api/v1/cas/blobs/" + std::string{sha256};
auto reply = http_exchange(*parsed, "GET", path, auth_headers(config_), {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status == 404) {
return std::optional<std::string>{};
}
if (reply->status != 200) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("remote cache: blob download failed with HTTP {}", reply->status))};
}
if (Util::sha256_hex(reply->body) != sha256) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument,
"remote cache: downloaded blob failed SHA-256 verification (discarded)")};
}
return std::optional<std::string>{std::move(reply->body)};
}
Void::Result::Result<void, Void::Result::Error>
RemoteCasClient::put_action(std::string_view action_key, std::string_view json) const {
if (!is_valid_sha256_hex(action_key)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"remote cache: invalid action key")};
}
auto parsed = require_url(config_);
if (!parsed) {
return std::unexpected{parsed.error()};
}
auto headers = auth_headers(config_);
headers["Content-Type"] = "application/json";
const std::string path = "/api/v1/cas/actions/" + std::string{action_key};
auto reply = http_exchange(*parsed, "PUT", path, headers, json);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200 && reply->status != 201) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("remote cache: action upload failed with HTTP {}", reply->status))};
}
return {};
}
Void::Result::Result<std::optional<std::string>, Void::Result::Error>
RemoteCasClient::get_action(std::string_view action_key) const {
if (!is_valid_sha256_hex(action_key)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"remote cache: invalid action key")};
}
auto parsed = require_url(config_);
if (!parsed) {
return std::unexpected{parsed.error()};
}
const std::string path = "/api/v1/cas/actions/" + std::string{action_key};
auto reply = http_exchange(*parsed, "GET", path, auth_headers(config_), {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status == 404) {
return std::optional<std::string>{};
}
if (reply->status != 200) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("remote cache: action download failed with HTTP {}", reply->status))};
}
return std::optional<std::string>{std::move(reply->body)};
}
} // namespace Void::Build::State
+96
View File
@@ -512,6 +512,102 @@ StateStore::materialize_blob(const BlobRef &ref, const std::filesystem::path &de
return {};
}
void StateStore::configure_remote_cache(std::optional<RemoteCacheConfig> config) {
if (config && !config->url.empty()) {
remote_.emplace(std::move(*config));
} else {
remote_.reset();
}
}
Void::Result::Result<std::optional<std::string>, Void::Result::Error>
StateStore::fetch_remote_action(std::string_view action_key) const {
if (!remote_) {
return std::optional<std::string>{};
}
return remote_->get_action(action_key);
}
Void::Result::Result<void, Void::Result::Error>
StateStore::publish_remote_action(std::string_view action_key, std::string_view json) const {
if (!remote_) {
return {};
}
return remote_->put_action(action_key, json);
}
Void::Result::Result<void, Void::Result::Error>
StateStore::publish_remote_blob(std::string_view sha256) const {
if (!remote_) {
return {};
}
if (!is_valid_sha256_hex(sha256)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"StateStore: invalid CAS blob digest")};
}
auto bytes = Void::FileSystem::read_file(cas_blob_path(sha256));
if (!bytes) {
return std::unexpected{bytes.error()};
}
if (Util::sha256_hex(*bytes) != sha256) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("StateStore: refusing to upload corrupted CAS blob '{}'", sha256))};
}
return remote_->put_blob(sha256, *bytes);
}
Void::Result::Result<bool, Void::Result::Error>
StateStore::ensure_remote_blob(std::string_view sha256) {
if (!is_valid_sha256_hex(sha256)) {
return false;
}
auto local = verify_blob(sha256);
if (!local) {
return std::unexpected{local.error()};
}
if (*local) {
return true;
}
if (!remote_) {
return false;
}
auto fetched = remote_->get_blob(sha256);
if (!fetched) {
return std::unexpected{fetched.error()};
}
if (!fetched->has_value()) {
return false;
}
const std::string &bytes = **fetched;
if (Util::sha256_hex(bytes) != sha256) {
return false;
}
const auto final_path = cas_blob_path(sha256);
std::error_code ec;
std::filesystem::create_directories(final_path.parent_path(), ec);
const auto stage_path =
staging_dir_ / std::format("remote_{}_{}.stage", sha256,
g_lease_seq.fetch_add(1, std::memory_order_relaxed));
auto wrote = Platform::atomic_write_file(stage_path, bytes, true, 0644);
if (!wrote) {
return std::unexpected{wrote.error()};
}
(void)::chmod(stage_path.c_str(), 0444);
std::filesystem::rename(stage_path, final_path, ec);
if (ec) {
std::filesystem::remove(stage_path, ec);
if (!std::filesystem::exists(final_path)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("StateStore: failed publishing remote CAS blob '{}'", sha256))};
}
}
(void)Platform::fsync_directory(final_path.parent_path());
return true;
}
Void::Result::Result<std::optional<ActionSuccessRecord>, Void::Result::Error>
StateStore::lookup_action(std::string_view action_key) const {
std::optional<ActionSuccessRecord> found;