#include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Update { namespace { std::atomic g_install_seq{0}; [[nodiscard]] std::string sha256_hex(std::string_view data) { auto d = Crypto::sha256(data); if (!d.has_value()) { return {}; } return Encoding::Hex::encode(*d); } [[nodiscard]] std::string state_to_string(InstallState state) noexcept { switch (state) { case InstallState::Verified: return "Verified"; case InstallState::Downloading: return "Downloading"; case InstallState::Staged: return "Staged"; case InstallState::Published: return "Published"; case InstallState::Activated: return "Activated"; case InstallState::HealthyCommitted: return "HealthyCommitted"; case InstallState::CleanupPending: return "CleanupPending"; case InstallState::RolledBack: return "RolledBack"; case InstallState::RecoveryRequired: return "RecoveryRequired"; } return "RecoveryRequired"; } [[nodiscard]] std::optional parse_state(std::string_view text) noexcept { if (text == "Verified") { return InstallState::Verified; } if (text == "Downloading") { return InstallState::Downloading; } if (text == "Staged") { return InstallState::Staged; } if (text == "Published") { return InstallState::Published; } if (text == "Activated") { return InstallState::Activated; } if (text == "HealthyCommitted") { return InstallState::HealthyCommitted; } if (text == "CleanupPending") { return InstallState::CleanupPending; } if (text == "RolledBack") { return InstallState::RolledBack; } if (text == "RecoveryRequired") { return InstallState::RecoveryRequired; } return std::nullopt; } [[nodiscard]] std::string floor_key(std::string_view feed_id, std::string_view channel) { return std::format("{}\x1f{}", feed_id, channel); } struct JournalRecord { std::string install_id{}; InstallState state{InstallState::Verified}; ActivationMode activation_mode{ ActivationMode::InternalVersionStore}; std::string component{}; std::string channel{}; std::string version{}; std::string signer_key_id{}; std::uint64_t sequence{0}; std::string diagnostic{}; }; [[nodiscard]] std::string serialize_journal_payload(const JournalRecord& rec) { Json::Value::Object_t obj; obj.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); obj.emplace_back("installId", Json::Value{rec.install_id}); obj.emplace_back("state", Json::Value{state_to_string(rec.state)}); obj.emplace_back( "activationMode", Json::Value{ rec.activation_mode == ActivationMode::ExternalLifecycle ? std::string{"external"} : std::string{"internal"}}); obj.emplace_back("component", Json::Value{rec.component}); obj.emplace_back("channel", Json::Value{rec.channel}); obj.emplace_back("version", Json::Value{rec.version}); obj.emplace_back("signerKeyId", Json::Value{rec.signer_key_id}); obj.emplace_back( "sequence", Json::Value{static_cast(rec.sequence)}); obj.emplace_back("diagnostic", Json::Value{rec.diagnostic}); return Json::serialize(Json::Value{std::move(obj)}); } [[nodiscard]] Void::Result::Result write_operation_journal(const std::filesystem::path& path, const JournalRecord& rec) { const std::string payload = serialize_journal_payload(rec); const std::string checksum = sha256_hex(payload); if (checksum.empty()) { return std::unexpected{make_update_error( UpdateErrorCode::io_error, "Update: failed to checksum operation journal")}; } Json::Value::Object_t wrapper; wrapper.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); wrapper.emplace_back("sha256", Json::Value{checksum}); wrapper.emplace_back("payload", Json::Value{payload}); const std::string serialized = Json::serialize(Json::Value{std::move(wrapper)}); auto res = Void::FileSystem::replace_file( path, serialized, Void::FileSystem::ReplaceOptions{ .durability = Void::FileSystem::ReplaceDurability::durable_sync, .mode = 0600}); if (!res.has_value()) { return std::unexpected{make_update_error( res.error().durability_unknown ? UpdateErrorCode::unknown_outcome : UpdateErrorCode::io_error, std::format("Update: write operation journal failed: {}", res.error().error.message()))}; } return {}; } [[nodiscard]] Void::Result::Result> read_operation_journal(const std::filesystem::path& path) { std::error_code ec; if (!std::filesystem::exists(path, ec)) { if (ec) { return std::unexpected{make_update_error( UpdateErrorCode::io_error, std::format("Update: inspect journal failed: {}", ec.message()), ec)}; } return std::optional{std::nullopt}; } auto content = Void::FileSystem::read_file_bounded( path, Void::FileSystem::ReadFileOptions{.max_bytes = 256 * 1024}); if (!content.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, std::format("Update: unreadable operation journal: {}", content.error().message()))}; } auto wrapper = Json::parse(*content); if (!wrapper.has_value() || !wrapper->is_object()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "Update: operation journal is not valid JSON")}; } const auto* ver = wrapper->find("schemaVersion"); const auto* sha = wrapper->find("sha256"); const auto* pay = wrapper->find("payload"); if (!ver || !ver->is_number() || ver->get_int().value_or(0) != 1 || !sha || !sha->is_string() || !pay || !pay->is_string()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "Update: operation journal has unknown schema or missing " "checksum")}; } const std::string actual_sha = sha256_hex(pay->as_string()); if (actual_sha != sha->as_string()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "Update: operation journal checksum mismatch")}; } auto doc = Json::parse(pay->as_string()); if (!doc.has_value() || !doc->is_object()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "Update: operation journal payload is corrupt")}; } const auto* state_val = doc->find("state"); const auto* id_val = doc->find("installId"); const auto* ver_val = doc->find("version"); if (!state_val || !state_val->is_string() || !id_val || !id_val->is_string() || !ver_val || !ver_val->is_string()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "Update: operation journal missing required fields")}; } const auto parsed_state = parse_state(state_val->as_string()); if (!parsed_state.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "Update: unknown state in operation journal")}; } JournalRecord rec; rec.install_id = id_val->as_string(); rec.state = *parsed_state; if (const auto* m = doc->find("activationMode"); m && m->is_string() && m->as_string() == "external") { rec.activation_mode = ActivationMode::ExternalLifecycle; } if (const auto* c = doc->find("component"); c && c->is_string()) { rec.component = c->as_string(); } if (const auto* ch = doc->find("channel"); ch && ch->is_string()) { rec.channel = ch->as_string(); } rec.version = ver_val->as_string(); if (const auto* k = doc->find("signerKeyId"); k && k->is_string()) { rec.signer_key_id = k->as_string(); } if (const auto* s = doc->find("sequence"); s && s->is_number()) { rec.sequence = s->get_uint().value_or(0); } if (const auto* d = doc->find("diagnostic"); d && d->is_string()) { rec.diagnostic = d->as_string(); } return std::optional{std::move(rec)}; } void remove_journal_best_effort(const std::filesystem::path& path) { std::error_code ec; (void)std::filesystem::remove(path, ec); } } // namespace // ── ReplayFloorStore ───────────────────────────────────────────────────── ReplayFloorStore::ReplayFloorStore(std::filesystem::path file_path) : m_path(std::move(file_path)) { } Void::Result::Result ReplayFloorStore::load() { std::lock_guard lk{m_mu}; std::error_code ec; if (!std::filesystem::exists(m_path, ec)) { if (ec) { return std::unexpected{make_update_error( UpdateErrorCode::io_error, std::format("ReplayFloorStore: inspect failed: {}", ec.message()), ec)}; } m_floors.clear(); m_loaded = true; return {}; } auto text = Void::FileSystem::read_file_bounded( m_path, Void::FileSystem::ReadFileOptions{.max_bytes = 1024 * 1024}); if (!text.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, std::format("ReplayFloorStore: cannot read floor file: {}", text.error().message()))}; } auto wrapper = Json::parse(*text); if (!wrapper.has_value() || !wrapper->is_object()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "ReplayFloorStore: corrupt floor file JSON")}; } const auto* ver = wrapper->find("schemaVersion"); const auto* sha = wrapper->find("sha256"); const auto* pay = wrapper->find("payload"); if (!ver || !ver->is_number() || ver->get_int().value_or(0) != 1 || !sha || !sha->is_string() || !pay || !pay->is_string()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "ReplayFloorStore: unknown schema or missing checksum")}; } if (sha256_hex(pay->as_string()) != sha->as_string()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "ReplayFloorStore: floor file checksum mismatch")}; } auto doc = Json::parse(pay->as_string()); if (!doc.has_value() || !doc->is_object()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "ReplayFloorStore: floor payload is not an object")}; } std::map> loaded; for (const auto& [k, v] : doc->as_object()) { auto seq = v.get_uint(); if (!seq.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "ReplayFloorStore: invalid sequence value")}; } loaded.emplace(k, *seq); } m_floors = std::move(loaded); m_loaded = true; return {}; } std::optional ReplayFloorStore::floor(std::string_view feed_id, std::string_view channel) const { std::lock_guard lk{m_mu}; const std::string key = floor_key(feed_id, channel); auto it = m_floors.find(key); if (it == m_floors.end()) { return std::nullopt; } return it->second; } Void::Result::Result ReplayFloorStore::advance(std::string_view feed_id, std::string_view channel, std::uint64_t sequence, bool require_strictly_greater) { if (feed_id.empty() || channel.empty()) { return std::unexpected{make_update_error( UpdateErrorCode::invalid_argument, "ReplayFloorStore: feed_id and channel are required")}; } { std::lock_guard lk{m_mu}; if (!m_loaded) { // Load before mutating to never clobber an existing persisted // floor. } } if (!m_loaded) { if (auto ld = load(); !ld.has_value()) { return ld; } } std::lock_guard lk{m_mu}; const std::string key = floor_key(feed_id, channel); auto it = m_floors.find(key); if (it != m_floors.end()) { if (sequence < it->second || (require_strictly_greater && sequence == it->second)) { return std::unexpected{make_update_error( UpdateErrorCode::replay_rejected, std::format("ReplayFloorStore: sequence {} rejected below " "floor {}", sequence, it->second))}; } if (sequence == it->second) { return {}; } } auto next_map = m_floors; next_map[key] = sequence; Json::Value::Object_t payload_obj; for (const auto& [k, v] : next_map) { payload_obj.emplace_back(k, Json::Value{v}); } const std::string payload = Json::serialize(Json::Value{std::move(payload_obj)}); const std::string checksum = sha256_hex(payload); Json::Value::Object_t wrapper; wrapper.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); wrapper.emplace_back("sha256", Json::Value{checksum}); wrapper.emplace_back("payload", Json::Value{payload}); const std::string serialized = Json::serialize(Json::Value{std::move(wrapper)}); if (m_path.has_parent_path()) { std::error_code ec; std::filesystem::create_directories(m_path.parent_path(), ec); } auto written = Void::FileSystem::replace_file( m_path, serialized, Void::FileSystem::ReplaceOptions{ .durability = Void::FileSystem::ReplaceDurability::durable_sync, .mode = 0600}); if (!written.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::io_error, std::format("ReplayFloorStore: persist failed: {}", written.error().error.message()))}; } m_floors = std::move(next_map); return {}; } // ── TrustStore ─────────────────────────────────────────────────────────── std::string TrustStore::rotation_statement(std::string_view new_key_id, const Ed25519PublicKey& new_public_key) { return std::format("VOID_TRUST_ROTATE_V1:{}:{}", new_key_id, Encoding::Hex::encode(new_public_key)); } Void::Result::Result TrustStore::bootstrap(Keyring keys) { if (keys.empty()) { return std::unexpected{make_update_error( UpdateErrorCode::invalid_argument, "TrustStore::bootstrap: at least one trust key is required")}; } std::lock_guard lk{m_mu}; m_active = std::move(keys); return {}; } Void::Result::Result TrustStore::rotate_key_authenticated( std::string new_key_id, const Ed25519PublicKey& new_public_key, std::span signature, std::string_view authorizing_key_id) { if (new_key_id.empty()) { return std::unexpected{make_update_error( UpdateErrorCode::invalid_argument, "TrustStore: new_key_id must be non-empty")}; } std::lock_guard lk{m_mu}; if (m_revoked.contains(new_key_id)) { return std::unexpected{make_update_error( UpdateErrorCode::untrusted_key, "TrustStore: cannot re-admit revoked key_id")}; } auto auth_it = m_active.find(std::string{authorizing_key_id}); if (auth_it == m_active.end()) { return std::unexpected{make_update_error( UpdateErrorCode::untrusted_key, "TrustStore: authorizing key is not active")}; } const std::string stmt = rotation_statement(new_key_id, new_public_key); auto ok = Crypto::verifyEd25519( std::as_bytes(std::span{stmt.data(), stmt.size()}), signature, auth_it->second); if (!ok.has_value() || !*ok) { return std::unexpected{make_update_error( UpdateErrorCode::signature_failed, "TrustStore: authenticated key rotation signature failed")}; } m_active[std::move(new_key_id)] = new_public_key; return {}; } Void::Result::Result TrustStore::rotate_key_operator(std::string new_key_id, const Ed25519PublicKey& new_public_key) { if (new_key_id.empty()) { return std::unexpected{make_update_error( UpdateErrorCode::invalid_argument, "TrustStore: new_key_id must be non-empty")}; } std::lock_guard lk{m_mu}; if (m_revoked.contains(new_key_id)) { return std::unexpected{make_update_error( UpdateErrorCode::untrusted_key, "TrustStore: cannot re-admit revoked key_id")}; } m_active[std::move(new_key_id)] = new_public_key; return {}; } Void::Result::Result TrustStore::revoke_key(std::string_view key_id) { std::lock_guard lk{m_mu}; auto it = m_active.find(std::string{key_id}); if (it == m_active.end()) { return std::unexpected{make_update_error( UpdateErrorCode::untrusted_key, "TrustStore: key_id not found in active keyring")}; } m_active.erase(it); m_revoked.emplace(key_id); return {}; } Keyring TrustStore::snapshot() const { std::lock_guard lk{m_mu}; return m_active; } bool TrustStore::is_revoked(std::string_view key_id) const { std::lock_guard lk{m_mu}; return m_revoked.contains(key_id); } // ── LocalFileArtifactTransport ─────────────────────────────────────────── void LocalFileArtifactTransport::map_url(std::string url, std::filesystem::path file_path, std::string validator) { std::lock_guard lk{m_mu}; m_entries[std::move(url)] = Entry{.path = std::move(file_path), .validator = std::move(validator)}; } void LocalFileArtifactTransport::set_fail_next(bool fail) noexcept { std::lock_guard lk{m_mu}; m_fail_next = fail; } void LocalFileArtifactTransport::set_truncate_bytes( std::optional bytes) noexcept { std::lock_guard lk{m_mu}; m_truncate_bytes = bytes; } Void::Result::Result LocalFileArtifactTransport::download( const DownloadRequest& request, const std::function< Void::Result::Result(std::span)>& on_chunk) { Entry entry; std::optional truncate_limit; { std::lock_guard lk{m_mu}; if (m_fail_next) { m_fail_next = false; return std::unexpected{make_update_error( UpdateErrorCode::transport_error, "LocalFileArtifactTransport: injected transport error")}; } auto it = m_entries.find(request.url); if (it == m_entries.end()) { return std::unexpected{make_update_error( UpdateErrorCode::transport_error, std::format("LocalFileArtifactTransport: unknown URL '{}'", request.url))}; } entry = it->second; truncate_limit = m_truncate_bytes; } std::ifstream in{entry.path, std::ios::binary}; if (!in.is_open()) { return std::unexpected{make_update_error( UpdateErrorCode::transport_error, std::format("LocalFileArtifactTransport: cannot open '{}'", entry.path.string()))}; } bool resumed = false; if (request.resume_offset > 0 && request.resume_validator.has_value() && *request.resume_validator == entry.validator) { in.seekg(static_cast(request.resume_offset)); resumed = static_cast(in); } std::array buf{}; std::size_t sent = 0; while (in) { if (request.stop.stop_requested()) { return std::unexpected{make_update_error( UpdateErrorCode::cancelled, "LocalFileArtifactTransport: cancelled")}; } std::size_t want = buf.size(); if (truncate_limit.has_value()) { if (sent >= *truncate_limit) { break; } want = std::min(want, *truncate_limit - sent); } in.read(reinterpret_cast(buf.data()), static_cast(want)); const auto n = static_cast(in.gcount()); if (n > 0) { if (auto cb = on_chunk(std::span{buf.data(), n}); !cb.has_value()) { return std::unexpected{std::move(cb.error())}; } sent += n; } } if (in.bad()) { return std::unexpected{make_update_error( UpdateErrorCode::transport_error, "LocalFileArtifactTransport: I/O error reading artifact")}; } return DownloadMetadata{.validator = entry.validator, .resumed = resumed}; } // ── InstallCoordinator ─────────────────────────────────────────────────── InstallCoordinator::InstallCoordinator( VersionStore& store, ReplayFloorStore& floor_store, std::shared_ptr transport, LifecycleHooks hooks) : m_store(store), m_floor_store(floor_store), m_transport(std::move(transport)), m_hooks(std::move(hooks)) { } std::filesystem::path InstallCoordinator::operation_journal_path() const { return m_store.root() / ".update.op_journal.json"; } void InstallCoordinator::shutdown() noexcept { std::lock_guard lk{m_state_mu}; m_shutdown = true; } bool InstallCoordinator::is_shutdown() const noexcept { std::lock_guard lk{m_state_mu}; return m_shutdown; } Void::Result::Result InstallCoordinator::install(const VerifiedSelection& selection, const InstallOptions& options) { if (!m_transport) { return std::unexpected{make_update_error( UpdateErrorCode::invalid_argument, "InstallCoordinator: ArtifactTransport is required")}; } if (options.activation_mode == ActivationMode::ExternalLifecycle && !m_hooks.activate_external) { return std::unexpected{make_update_error( UpdateErrorCode::invalid_argument, "InstallCoordinator: ExternalLifecycle requires " "activate_external hook")}; } // Serialize one active install per store while keeping transport & // lifecycle callbacks outside the coordinator state lock. { std::lock_guard lk{m_state_mu}; if (m_shutdown) { return std::unexpected{make_update_error( UpdateErrorCode::closed, "InstallCoordinator: coordinator is shut down")}; } if (m_active) { return std::unexpected{make_update_error( UpdateErrorCode::conflict, "InstallCoordinator: another install is already active")}; } m_active = true; } struct ActiveGuard { std::mutex& mu; bool& active; ~ActiveGuard() noexcept { std::lock_guard lk{mu}; active = false; } } active_guard{m_state_mu, m_active}; const auto& mono_clock = options.monotonic_clock ? *options.monotonic_clock : Void::Time::SystemMonotonicClock::instance(); const auto& civil_clock = options.civil_clock ? *options.civil_clock : Void::Time::SystemCivilClock::instance(); const auto deadline = mono_clock.now() + options.install_deadline; if (options.stop.stop_requested()) { return std::unexpected{make_update_error( UpdateErrorCode::cancelled, "InstallCoordinator: cancelled before admission")}; } if (civil_clock.now() >= selection.expires_at()) { return std::unexpected{make_update_error( UpdateErrorCode::expired, "InstallCoordinator: verified selection is expired")}; } if (selection.release().size == 0 || selection.release().size > options.max_artifact_bytes) { return std::unexpected{make_update_error( UpdateErrorCode::limit_exceeded, "InstallCoordinator: artifact size exceeds policy")}; } if (auto init = m_store.initialize(); !init.has_value()) { return std::unexpected{std::move(init.error())}; } // Check whether an unrecovered journal exists before admitting new // work. auto existing_j = read_operation_journal(operation_journal_path()); if (!existing_j.has_value()) { return std::unexpected{std::move(existing_j.error())}; } if (existing_j->has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, "InstallCoordinator: prior operation journal present; run " "reconcile() first")}; } // Advance durable replay floor before download/install. if (auto fl = m_floor_store.advance(selection.feed_id(), selection.release().channel, selection.sequence()); !fl.has_value()) { return std::unexpected{std::move(fl.error())}; } const std::string install_id = std::format("inst-{}-{}", static_cast(::getpid()), g_install_seq.fetch_add(1, std::memory_order_relaxed)); InstallReceipt receipt{ .install_id = install_id, .state = InstallState::Verified, .release = selection.release(), .signer_key_id = selection.signer_key_id(), }; auto emit_progress = [&]() { if (m_hooks.on_progress) { try { m_hooks.on_progress(receipt); } catch (...) { } } }; auto persist_state = [&](InstallState st, std::string diag = {}) -> Void::Result::Result { receipt.state = st; receipt.diagnostic = std::move(diag); JournalRecord rec{ .install_id = receipt.install_id, .state = receipt.state, .activation_mode = options.activation_mode, .component = receipt.release.component, .channel = receipt.release.channel, .version = receipt.release.version.to_string(), .signer_key_id = receipt.signer_key_id, .sequence = receipt.release.sequence, .diagnostic = receipt.diagnostic, }; auto w = write_operation_journal(operation_journal_path(), rec); emit_progress(); return w; }; // 1. Download artifact to exclusive staging file while checking exact // size and incremental SHA-256. if (auto ps = persist_state(InstallState::Downloading); !ps.has_value()) { return std::unexpected{std::move(ps.error())}; } const auto staging_root = m_store.root() / "staging"; const auto download_path = staging_root / std::format(".dl-{}.tar.zst", install_id); struct FileCleanup { std::filesystem::path p{}; ~FileCleanup() noexcept { if (!p.empty()) { std::error_code ec; (void)std::filesystem::remove(p, ec); } } } dl_cleanup{download_path}; auto hasher = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256); if (!hasher.has_value()) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{std::move(hasher.error())}; } int dl_fd = ::open(download_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); if (dl_fd < 0) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::staging_error, "InstallCoordinator: cannot create staging download file")}; } std::uint64_t downloaded_bytes = 0; DownloadRequest dreq{ .url = receipt.release.url, .expected_sha256 = receipt.release.sha256, .expected_size = receipt.release.size, .max_bytes = std::min(options.max_artifact_bytes, options.staging_quota_bytes), .stop = options.stop, }; auto dl_res = m_transport->download( dreq, [&](std::span chunk) -> Void::Result::Result { if (options.stop.stop_requested()) { return std::unexpected{make_update_error( UpdateErrorCode::cancelled, "InstallCoordinator: cancelled during download")}; } if (mono_clock.now() >= deadline) { return std::unexpected{make_update_error( UpdateErrorCode::timeout, "InstallCoordinator: install deadline expired during " "download")}; } const auto n = static_cast(chunk.size()); if (n > dreq.max_bytes - downloaded_bytes || n > receipt.release.size - downloaded_bytes) { return std::unexpected{make_update_error( UpdateErrorCode::size_mismatch, "InstallCoordinator: downloaded bytes exceed declared " "artifact size")}; } if (auto u = hasher->update(chunk); !u.has_value()) { return std::unexpected{std::move(u.error())}; } std::size_t off = 0; while (off < chunk.size()) { const ssize_t w = ::write( dl_fd, reinterpret_cast(chunk.data()) + off, chunk.size() - off); if (w < 0 && errno == EINTR) { continue; } if (w <= 0) { return std::unexpected{make_update_error( UpdateErrorCode::io_error, "InstallCoordinator: write staging artifact " "failed")}; } off += static_cast(w); } downloaded_bytes += n; return {}; }); const bool sync_ok = (::fsync(dl_fd) == 0); (void)::close(dl_fd); if (!dl_res.has_value()) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{std::move(dl_res.error())}; } if (!sync_ok) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::io_error, "InstallCoordinator: fsync staging artifact failed")}; } if (downloaded_bytes != receipt.release.size) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::size_mismatch, std::format("InstallCoordinator: downloaded {} bytes != " "expected {}", downloaded_bytes, receipt.release.size))}; } auto digest = hasher->finalize(); if (!digest.has_value()) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{std::move(digest.error())}; } const std::string actual_sha = Encoding::Hex::encode(*digest); if (actual_sha != receipt.release.sha256) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::digest_mismatch, "InstallCoordinator: artifact SHA-256 mismatch")}; } // 2. Safe staged extraction via Archive + atomic publication into // VersionStore. Archive::StagedExtractionOptions ext_opts{}; ext_opts.limits.max_total_bytes = std::min(ext_opts.limits.max_total_bytes, options.staging_quota_bytes); ext_opts.limits.max_file_bytes = std::min(ext_opts.limits.max_file_bytes, options.staging_quota_bytes); ext_opts.stop = options.stop; ext_opts.deadline = deadline; ext_opts.clock = &mono_clock; Void::Result::Result staged = options.isolated_archive_worker.has_value() ? Archive::extract_staged_isolated( download_path, staging_root, Archive::IsolationOptions{ .worker_executable = *options.isolated_archive_worker, .timeout = options.install_deadline, .extraction = ext_opts}) : Archive::extract_staged(download_path, staging_root, ext_opts); if (!staged.has_value()) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::staging_error, std::format("InstallCoordinator: archive extraction failed: {}", staged.error().message()))}; } if (auto ps = persist_state(InstallState::Staged); !ps.has_value()) { return std::unexpected{std::move(ps.error())}; } // Publish staged tree as an immediate child of store/staging, then hand // off to VersionStore::publish(). const std::string ready_name = std::format("{}.ready.{}", receipt.release.version.to_string(), install_id); auto stage_pub = staged->publish(ready_name); if (!stage_pub.has_value()) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::staging_error, std::format("InstallCoordinator: staging handoff failed: {}", stage_pub.error().message()))}; } if (stage_pub->outcome == Archive::PublicationOutcome::Unknown) { return std::unexpected{make_update_error( UpdateErrorCode::unknown_outcome, stage_pub->diagnostic)}; } struct ReadyDirCleanup { std::filesystem::path p{}; ~ReadyDirCleanup() noexcept { if (!p.empty()) { std::error_code ec; (void)std::filesystem::remove_all(p, ec); } } } ready_cleanup{stage_pub->destination_path}; if (auto pub = m_store.publish(receipt.release.version, stage_pub->destination_path); !pub.has_value()) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::staging_error, std::format("InstallCoordinator: VersionStore::publish failed: " "{}", pub.error().message()))}; } ready_cleanup.p.clear(); // moved into versions/ if (auto ps = persist_state(InstallState::Published); !ps.has_value()) { return std::unexpected{std::move(ps.error())}; } // 3. Activation (InternalVersionStore vs ExternalLifecycle — strictly // separate!). const auto published_dir = m_store.versionPath(receipt.release.version); if (options.activation_mode == ActivationMode::InternalVersionStore) { if (auto act = m_store.activate(receipt.release.version); !act.has_value()) { remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::activation_failed, act.error().message())}; } } else { if (auto act = m_hooks.activate_external(receipt.release.version, published_dir); !act.has_value()) { (void)m_store.recordFailed(receipt.release.version); remove_journal_best_effort(operation_journal_path()); return std::unexpected{make_update_error( UpdateErrorCode::activation_failed, act.error().message())}; } } if (auto ps = persist_state(InstallState::Activated); !ps.has_value()) { return std::unexpected{std::move(ps.error())}; } // 4. Bounded cooperative health/readiness probes outside locks. const auto readiness_deadline = std::min(deadline, mono_clock.now() + options.readiness_timeout); const std::size_t required_healthy = std::max(1, options.consecutive_healthy_required); std::size_t consecutive_ok = 0; bool ready = false; std::string readiness_diag; if (!m_hooks.health_probe) { ready = true; } else { for (;;) { if (options.stop.stop_requested()) { readiness_diag = "cancelled before durable commit"; break; } if (mono_clock.now() > readiness_deadline) { readiness_diag = "readiness timeout expired"; break; } auto probe = m_hooks.health_probe(receipt.release.version, published_dir); if (!probe.has_value()) { readiness_diag = probe.error().message(); break; } if (*probe) { ++consecutive_ok; if (consecutive_ok >= required_healthy) { ready = true; break; } } else { consecutive_ok = 0; } if (mono_clock.now() >= readiness_deadline) { readiness_diag = "candidate did not reach readiness"; break; } if (!*probe && (options.monotonic_clock != nullptr || options.health_probe_interval <= std::chrono::milliseconds{0})) { readiness_diag = "candidate health probe returned unhealthy"; break; } if (options.health_probe_interval > std::chrono::milliseconds{0} && options.monotonic_clock == nullptr) { std::this_thread::sleep_for(options.health_probe_interval); } } } if (!ready) { if (m_hooks.stop_candidate) { m_hooks.stop_candidate(receipt.release.version); } if (options.activation_mode == ActivationMode::InternalVersionStore) { if (auto rb = m_store.rollback(); !rb.has_value()) { (void)persist_state(InstallState::RecoveryRequired, rb.error().message()); return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, std::format("InstallCoordinator: rollback failed: {}", rb.error().message()))}; } } else { (void)m_store.recordFailed(receipt.release.version); } (void)persist_state(InstallState::RolledBack, readiness_diag); remove_journal_best_effort(operation_journal_path()); return receipt; } // 5. Durable commit via VersionStore's single commit marker. if (options.activation_mode == ActivationMode::InternalVersionStore) { if (auto cm = m_store.commit(); !cm.has_value()) { (void)persist_state(InstallState::RecoveryRequired, cm.error().message()); return std::unexpected{make_update_error( UpdateErrorCode::unknown_outcome, std::format("InstallCoordinator: commit outcome uncertain: " "{}", cm.error().message()))}; } } else { if (auto rh = m_store.recordHealthy(receipt.release.version); !rh.has_value()) { (void)persist_state(InstallState::RecoveryRequired, rh.error().message()); return std::unexpected{make_update_error( UpdateErrorCode::unknown_outcome, std::format("InstallCoordinator: recordHealthy failed: {}", rh.error().message()))}; } } if (auto ps = persist_state(InstallState::HealthyCommitted); !ps.has_value()) { return std::unexpected{std::move(ps.error())}; } // 6. Post-commit cleanup/pruning: failures become CleanupPending and // NEVER trigger rollback of the committed version. std::vector pins; if (m_hooks.live_pinned_versions) { pins = m_hooks.live_pinned_versions(); } std::string cleanup_diag; if (auto pr = m_store.pruneWithPins(options.retained_previous_versions, pins, options.prune_batch_limit); !pr.has_value()) { cleanup_diag = pr.error().message(); } else if (m_hooks.post_commit_cleanup_hook) { if (auto hk = m_hooks.post_commit_cleanup_hook(); !hk.has_value()) { cleanup_diag = hk.error().message(); } } if (!cleanup_diag.empty()) { receipt.cleanup_retryable = true; (void)persist_state(InstallState::CleanupPending, cleanup_diag); return receipt; } remove_journal_best_effort(operation_journal_path()); return receipt; } Void::Result::Result InstallCoordinator::reconcile() { auto journal = read_operation_journal(operation_journal_path()); if (!journal.has_value()) { return std::unexpected{std::move(journal.error())}; } if (auto rec = m_store.reconcile(); !rec.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, std::format("InstallCoordinator::reconcile: VersionStore " "reconcile failed: {}", rec.error().message()))}; } auto current = m_store.currentVersion(); if (!current.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::recovery_required, current.error().message())}; } InstallReceipt receipt{}; if (!journal->has_value()) { receipt.state = InstallState::HealthyCommitted; if (current->has_value()) { receipt.release.version = **current; } return receipt; } const auto& j = **journal; receipt.install_id = j.install_id; receipt.signer_key_id = j.signer_key_id; receipt.release.component = j.component; receipt.release.channel = j.channel; receipt.release.sequence = j.sequence; if (auto pv = Semver::parse_strict(j.version); pv.has_value()) { receipt.release.version = *pv; } if (j.state == InstallState::RecoveryRequired) { receipt.state = InstallState::RecoveryRequired; receipt.diagnostic = j.diagnostic; return receipt; } if (j.state == InstallState::CleanupPending) { receipt.state = InstallState::CleanupPending; receipt.diagnostic = j.diagnostic; receipt.cleanup_retryable = true; return receipt; } // Determine outcome from VersionStore's authoritative durable evidence. auto healthy = m_store.healthyPublishedVersions(); bool candidate_healthy = false; if (healthy.has_value()) { for (const auto& hv : *healthy) { if (hv.to_string() == j.version) { candidate_healthy = true; break; } } } const bool is_current = current->has_value() && (*current)->to_string() == j.version; if (candidate_healthy && (is_current || j.activation_mode == ActivationMode::ExternalLifecycle)) { receipt.state = InstallState::HealthyCommitted; remove_journal_best_effort(operation_journal_path()); return receipt; } // Candidate was not committed; VersionStore::reconcile() restored the // previous version if activation had started. receipt.state = InstallState::RolledBack; receipt.diagnostic = "reconciled uncommitted operation"; remove_journal_best_effort(operation_journal_path()); return receipt; } Void::Result::Result InstallCoordinator::retry_cleanup(const InstallOptions& options) { auto journal = read_operation_journal(operation_journal_path()); if (!journal.has_value()) { return std::unexpected{std::move(journal.error())}; } if (!journal->has_value()) { return InstallReceipt{.state = InstallState::HealthyCommitted}; } const auto& j = **journal; if (j.state != InstallState::CleanupPending && j.state != InstallState::HealthyCommitted) { return std::unexpected{make_update_error( UpdateErrorCode::conflict, "InstallCoordinator::retry_cleanup: journal is not in " "CleanupPending state")}; } std::vector pins; if (m_hooks.live_pinned_versions) { pins = m_hooks.live_pinned_versions(); } if (auto pr = m_store.pruneWithPins(options.retained_previous_versions, pins, options.prune_batch_limit); !pr.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::cleanup_pending, pr.error().message())}; } if (m_hooks.post_commit_cleanup_hook) { if (auto hk = m_hooks.post_commit_cleanup_hook(); !hk.has_value()) { return std::unexpected{make_update_error( UpdateErrorCode::cleanup_pending, hk.error().message())}; } } InstallReceipt receipt{ .install_id = j.install_id, .state = InstallState::HealthyCommitted, .signer_key_id = j.signer_key_id, .cleanup_retryable = false, }; if (auto pv = Semver::parse_strict(j.version); pv.has_value()) { receipt.release.version = *pv; } remove_journal_best_effort(operation_journal_path()); return receipt; } } // namespace Void::Update