#include "settlement/core/save_service.hpp" #include #include #ifndef NOMINMAX #define NOMINMAX #endif #include #include #include #include #include #include namespace settlement { namespace { // CREATE_NEW establishes ownership. No cleanup ever scans by filename prefix. struct StagingFile { HANDLE handle{INVALID_HANDLE_VALUE}; std::filesystem::path path; bool owned{false}; void cleanup(SaveResult& result) noexcept { if (handle != INVALID_HANDLE_VALUE) { if (!CloseHandle(handle)) result.cleanup_error = GetLastError(); handle = INVALID_HANDLE_VALUE; } if (owned && !DeleteFileW(path.c_str())) { result.cleanup_error = GetLastError(); // Moving a path is noexcept, including during allocation failure. result.retained_staging_file = std::move(path); } owned = false; } }; bool valid_request(const SaveRequest& request) { const auto& path = request.destination; if (!request.produce || request.session.is_nil() || !path.is_absolute() || path.native().find(L'\0') != std::wstring::npos) return false; const auto filename = path.filename(); return !filename.empty() && filename != L"." && filename != L".." && filename.native().find(L':') == std::wstring::npos; } SaveResult publish(const SaveRequest& request, std::uint64_t id, const SaveServiceOptions& options) noexcept { SaveResult result; result.request_id = id; result.tick = request.tick; result.session = request.session; StagingFile staging; const auto phase = [&](SavePhase next) { result.phase = next; if (options.fault_hook) { result.native_error = options.fault_hook(next); if (result.native_error != 0) { result.error = SaveError::Injected; return false; } } return true; }; const auto io_error = [&] { result.error = SaveError::Io; result.native_error = GetLastError(); }; try { // A single exit after this body performs cleanup before returning the // result, including when path allocation or the producer throws. [&] { if (!phase(SavePhase::Materialize)) return; std::string bytes; try { bytes = request.produce(); } catch (...) { result.error = SaveError::ProducerFailed; return; } if (bytes.size() > options.max_bytes) { result.error = SaveError::TooLarge; return; } if (!phase(SavePhase::CreateStage)) return; for (int attempt = 0; attempt < 16; ++attempt) { const auto uuid = Void::Uuid::try_v4(); if (!uuid) { result.error = SaveError::Internal; return; } const auto name = uuid->to_string(); staging.path = request.destination.parent_path() / (L".settlement-save-" + std::wstring(name.begin(), name.end()) + L".tmp"); staging.handle = CreateFileW(staging.path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if (staging.handle != INVALID_HANDLE_VALUE) { staging.owned = true; break; } const auto error = GetLastError(); if (error != ERROR_FILE_EXISTS && error != ERROR_ALREADY_EXISTS) { result.error = SaveError::Io; result.native_error = error; return; } } if (!staging.owned) { result.error = SaveError::Io; result.native_error = ERROR_FILE_EXISTS; return; } std::size_t offset = 0; while (offset < bytes.size()) { if (!phase(SavePhase::WriteStage)) return; const auto count = static_cast(std::min(bytes.size() - offset, 65536)); DWORD written = 0; if (!WriteFile(staging.handle, bytes.data() + offset, count, &written, nullptr)) { io_error(); return; } if (written == 0 || written > count) { result.error = SaveError::Io; result.native_error = ERROR_WRITE_FAULT; return; } offset += written; // Includes short successful writes. } if (!phase(SavePhase::FlushStage)) return; if (!FlushFileBuffers(staging.handle)) { io_error(); return; } if (!phase(SavePhase::CloseStage)) return; if (!CloseHandle(staging.handle)) { io_error(); return; } staging.handle = INVALID_HANDLE_VALUE; if (!phase(SavePhase::Publish)) return; // Same-directory rename, no MOVEFILE_COPY_ALLOWED fallback. This // publishes complete flushed bytes; WRITE_THROUGH alone does not // establish power-loss durability of directory metadata. if (!MoveFileExW(staging.path.c_str(), request.destination.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { io_error(); return; } staging.owned = false; result.visible_on_disk = true; static_cast(phase(SavePhase::Published)); }(); } catch (...) { result.error = SaveError::Internal; } result.durability_unknown = result.visible_on_disk && result.error != SaveError::None; staging.cleanup(result); return result; } } // namespace struct SaveService::Impl { explicit Impl(SaveServiceOptions configured) : options(std::move(configured)) { if (options.capacity == 0 || options.max_bytes == 0) { throw std::invalid_argument("save service limits must be positive"); } auto created = Void::Async::ThreadExecutor::create({.workers = 1, .max_admitted = options.capacity}); if (!created) throw std::runtime_error("cannot create save writer"); executor = std::move(*created); pool = std::make_unique(*executor); if (!executor->start()) throw std::runtime_error("cannot start save writer"); } SaveServiceOptions options; std::unique_ptr executor; std::unique_ptr pool; std::mutex admission_mutex; bool closed{false}; std::uint64_t next_id{1}; }; SaveService::SaveService(SaveServiceOptions options) : impl_(std::make_unique(std::move(options))) {} SaveService::~SaveService() { shutdown(); } SaveSubmission SaveService::try_submit(const SaveRequest& request) { std::unique_lock lock(impl_->admission_mutex, std::try_to_lock); if (!lock.owns_lock()) return {SaveAdmission::Busy, 0, {}}; if (impl_->closed) return {SaveAdmission::Closed, 0, {}}; if (impl_->executor->admitted() >= impl_->options.capacity) return {SaveAdmission::Busy, 0, {}}; if (!valid_request(request)) return {SaveAdmission::InvalidRequest, 0, {}}; if (impl_->next_id == 0) return {SaveAdmission::IdExhausted, 0, {}}; const auto id = impl_->next_id; auto submitted = impl_->pool->try_submit([state = impl_.get(), request = SaveRequest(request), id]() mutable { auto result = publish(request, id, state->options); request.produce = {}; // Release snapshot even if the caller keeps its future. return result; }); if (!submitted) { return {submitted.error() == Void::Async::AdmissionError::overloaded ? SaveAdmission::Busy : SaveAdmission::Closed, 0, {}}; } ++impl_->next_id; // Unsigned wrap to zero permanently exhausts identities. return {SaveAdmission::Accepted, id, std::move(*submitted)}; } void SaveService::shutdown() { if (impl_->executor->is_executor_thread()) { throw std::logic_error("save writer cannot join itself"); } { std::lock_guard lock(impl_->admission_mutex); impl_->closed = true; } static_cast(impl_->executor->join()); } } // namespace settlement