394 lines
19 KiB
C++
394 lines
19 KiB
C++
#include "settlement/core/save_service.hpp"
|
|
|
|
#include <Void/Testing/Suite.hpp>
|
|
|
|
#ifndef NOMINMAX
|
|
#define NOMINMAX
|
|
#endif
|
|
#include <windows.h>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <fstream>
|
|
#include <iterator>
|
|
#include <latch>
|
|
#include <memory>
|
|
#include <stdexcept>
|
|
#include <thread>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace {
|
|
|
|
using namespace std::chrono_literals;
|
|
using namespace settlement;
|
|
using Void::Testing::Test;
|
|
|
|
void require(bool condition, const char* message) {
|
|
if (!condition) throw std::runtime_error(message);
|
|
}
|
|
|
|
struct TemporaryDirectory {
|
|
std::filesystem::path path;
|
|
TemporaryDirectory() {
|
|
const auto token = Void::Uuid::v4().to_string();
|
|
path = std::filesystem::temp_directory_path() / ("settlement-save-test-" + token);
|
|
require(std::filesystem::create_directory(path), "test directory was not exclusively created");
|
|
}
|
|
~TemporaryDirectory() {
|
|
std::error_code error;
|
|
std::filesystem::remove_all(path, error);
|
|
}
|
|
};
|
|
|
|
struct Reader {
|
|
HANDLE handle{INVALID_HANDLE_VALUE};
|
|
Reader(const std::filesystem::path& path, DWORD sharing)
|
|
: handle(CreateFileW(path.c_str(), GENERIC_READ, sharing, nullptr, OPEN_EXISTING,
|
|
FILE_ATTRIBUTE_NORMAL, nullptr)) {
|
|
require(handle != INVALID_HANDLE_VALUE, "cannot open test reader");
|
|
}
|
|
~Reader() { CloseHandle(handle); }
|
|
std::string read() const {
|
|
LARGE_INTEGER beginning{};
|
|
require(SetFilePointerEx(handle, beginning, nullptr, FILE_BEGIN), "cannot rewind test reader");
|
|
std::string bytes;
|
|
std::array<char, 8192> buffer;
|
|
for (;;) {
|
|
DWORD count = 0;
|
|
require(ReadFile(handle, buffer.data(), static_cast<DWORD>(buffer.size()), &count, nullptr),
|
|
"test read failed");
|
|
if (count == 0) return bytes;
|
|
bytes.append(buffer.data(), count);
|
|
}
|
|
}
|
|
};
|
|
|
|
std::string read(const std::filesystem::path& path) {
|
|
return Reader(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE).read();
|
|
}
|
|
|
|
void write(const std::filesystem::path& path, const std::string& bytes) {
|
|
std::ofstream file(path, std::ios::binary);
|
|
file.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
|
|
file.close();
|
|
require(static_cast<bool>(file), "cannot write test fixture");
|
|
}
|
|
|
|
Void::Uuid::Uuid session() {
|
|
Void::Uuid::Uuid id;
|
|
id.bytes[0] = 42;
|
|
return id;
|
|
}
|
|
|
|
SaveRequest request(const std::filesystem::path& path, std::string bytes, std::uint64_t tick = 9) {
|
|
return {path, tick, session(), [bytes = std::move(bytes)] { return bytes; }};
|
|
}
|
|
|
|
SaveResult completed(SaveSubmission& submission) {
|
|
require(submission.admission == SaveAdmission::Accepted && submission.request_id != 0,
|
|
"request was not accepted");
|
|
require(submission.completion.wait_for(10s) == std::future_status::ready, "save did not complete");
|
|
auto result = submission.completion.get();
|
|
require(result.request_id == submission.request_id, "completion identity changed");
|
|
return result;
|
|
}
|
|
|
|
void only_files(const TemporaryDirectory& directory, std::size_t count) {
|
|
const auto actual = static_cast<std::size_t>(std::distance(
|
|
std::filesystem::directory_iterator(directory.path), std::filesystem::directory_iterator{}));
|
|
require(actual == count, "unexpected file or staging file left in test directory");
|
|
}
|
|
|
|
// Every wait has an explicit causal signal. The timeout is only a deadlock
|
|
// watchdog; it never creates the ordering being tested.
|
|
struct Gate {
|
|
std::promise<void> entered;
|
|
std::future<void> arrival{entered.get_future()};
|
|
std::promise<void> released;
|
|
std::shared_future<void> release{released.get_future().share()};
|
|
std::atomic<bool> opened{false};
|
|
void wait() {
|
|
entered.set_value();
|
|
require(release.wait_for(10s) == std::future_status::ready, "test gate timed out");
|
|
}
|
|
void await_entry() {
|
|
require(arrival.wait_for(10s) == std::future_status::ready, "writer did not reach test gate");
|
|
}
|
|
void open() {
|
|
if (!opened.exchange(true)) released.set_value();
|
|
}
|
|
~Gate() { open(); }
|
|
};
|
|
|
|
struct [[= Void::Testing::name("SaveServiceTests")]]
|
|
SaveServiceTests : Void::Testing::Suite<SaveServiceTests> {
|
|
[[= Void::Testing::tag("save-slot")]] Test unicode_create_replace_and_open_reader();
|
|
[[= Void::Testing::tag("save-slot")]] Test prepublication_faults_preserve_slot_and_siblings();
|
|
[[= Void::Testing::tag("save-slot")]] Test partial_staging_is_never_visible();
|
|
[[= Void::Testing::tag("save-slot")]] Test fifo_bound_snapshot_lifetime_and_shutdown_drain();
|
|
[[= Void::Testing::tag("save-slot")]] Test failed_producer_does_not_stop_writer();
|
|
[[= Void::Testing::tag("save-slot")]] Test invalid_missing_parent_and_sharing_failure();
|
|
[[= Void::Testing::tag("save-slot")]] Test concurrent_submission_identity_matches_publication_order();
|
|
[[= Void::Testing::tag("save-slot")]] Test empty_file_and_size_limit();
|
|
[[= Void::Testing::tag("save-slot")]] Test self_shutdown_is_rejected_without_closing_service();
|
|
};
|
|
|
|
Test SaveServiceTests::unicode_create_replace_and_open_reader() {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"\u0441\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435-\u96ea.bin";
|
|
SaveService service;
|
|
const std::string old_bytes("old\0save", 8);
|
|
auto first = service.try_submit(request(path, old_bytes, 17));
|
|
const auto created = completed(first);
|
|
require(created.succeeded() && created.visible_on_disk && !created.durability_unknown,
|
|
"first save not published");
|
|
require(created.tick == 17 && created.session == session(), "snapshot metadata was not preserved");
|
|
std::string new_bytes(200000, 'x');
|
|
new_bytes[65536] = '\0';
|
|
new_bytes.back() = 'z';
|
|
bool retry_after_reader_closes = false;
|
|
{
|
|
Reader old_reader(path, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
|
|
auto second = service.try_submit(request(path, new_bytes));
|
|
const auto replacement = completed(second);
|
|
require(second.request_id > first.request_id, "save identity did not increase");
|
|
require(old_reader.read() == old_bytes, "open reader saw partial or replaced old file bytes");
|
|
if (replacement.succeeded()) {
|
|
require(replacement.visible_on_disk && !replacement.durability_unknown,
|
|
"successful replacement not reported as visible");
|
|
require(read(path) == new_bytes, "fresh reader did not see complete binary replacement");
|
|
} else {
|
|
// Wine 11 returns ERROR_ACCESS_DENIED (5), even with delete sharing.
|
|
// Windows/filesystem open-handle restrictions may reject publication;
|
|
// atomic visibility does not promise replacement under every lock.
|
|
require(replacement.error == SaveError::Io && replacement.phase == SavePhase::Publish &&
|
|
(replacement.native_error == ERROR_ACCESS_DENIED ||
|
|
replacement.native_error == ERROR_SHARING_VIOLATION) &&
|
|
!replacement.visible_on_disk && !replacement.durability_unknown,
|
|
"replacement failed outside the permitted sharing/access boundary");
|
|
require(read(path) == old_bytes, "rejected replacement changed the existing slot");
|
|
require(replacement.cleanup_error == 0 && replacement.retained_staging_file.empty(),
|
|
"rejected replacement did not clean its staging file");
|
|
only_files(directory, 1);
|
|
retry_after_reader_closes = true;
|
|
}
|
|
}
|
|
if (retry_after_reader_closes) {
|
|
auto retry = service.try_submit(request(path, new_bytes));
|
|
require(completed(retry).succeeded(), "next replacement failed after the reader closed");
|
|
}
|
|
require(read(path) == new_bytes, "fresh reader did not see complete binary replacement");
|
|
service.shutdown();
|
|
only_files(directory, 1);
|
|
}
|
|
|
|
Test SaveServiceTests::prepublication_faults_preserve_slot_and_siblings() {
|
|
const std::array phases{SavePhase::Materialize, SavePhase::CreateStage, SavePhase::WriteStage,
|
|
SavePhase::FlushStage, SavePhase::CloseStage, SavePhase::Publish,
|
|
SavePhase::Published};
|
|
for (const auto failed_phase : phases) {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"slot.bin";
|
|
const auto sibling = directory.path / L".settlement-save-unrelated.tmp";
|
|
write(path, "previous complete generation");
|
|
write(sibling, "unrelated sibling");
|
|
std::size_t writes = 0;
|
|
SaveService service({.fault_hook = [&](SavePhase phase) -> std::uint32_t {
|
|
if (phase != failed_phase) return 0;
|
|
if (phase == SavePhase::WriteStage && ++writes == 1) return 0;
|
|
return ERROR_DISK_FULL;
|
|
}});
|
|
const std::string bytes(150000, 'n');
|
|
auto submitted = service.try_submit(request(path, bytes));
|
|
const auto failed = completed(submitted);
|
|
service.shutdown();
|
|
const bool published = failed_phase == SavePhase::Published;
|
|
require(failed.error == SaveError::Injected && failed.phase == failed_phase &&
|
|
failed.native_error == ERROR_DISK_FULL, "incorrect phase failure reporting");
|
|
require(failed.visible_on_disk == published && failed.durability_unknown == published,
|
|
"failure incorrectly reported publication or rollback");
|
|
require(read(path) == (published ? bytes : "previous complete generation"),
|
|
"failure exposed incomplete data or lost previous slot");
|
|
require(read(sibling) == "unrelated sibling", "cleanup removed an unowned staging sibling");
|
|
require(failed.cleanup_error == 0 && failed.retained_staging_file.empty(), "cleanup failed");
|
|
only_files(directory, 2);
|
|
}
|
|
}
|
|
|
|
Test SaveServiceTests::partial_staging_is_never_visible() {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"slot.bin";
|
|
write(path, "old");
|
|
auto gate = std::make_shared<Gate>();
|
|
std::size_t writes = 0;
|
|
SaveService service({.fault_hook = [gate, &writes](SavePhase phase) -> std::uint32_t {
|
|
if (phase == SavePhase::WriteStage && ++writes == 2) gate->wait();
|
|
return 0;
|
|
}});
|
|
const std::string bytes(150000, 'n');
|
|
auto submitted = service.try_submit(request(path, bytes));
|
|
gate->await_entry();
|
|
require(read(path) == "old", "partial staging replaced old slot");
|
|
require(submitted.completion.wait_for(0s) == std::future_status::timeout, "gate did not block writer");
|
|
gate->open();
|
|
require(completed(submitted).succeeded() && read(path) == bytes, "complete generation was not published");
|
|
}
|
|
|
|
Test SaveServiceTests::fifo_bound_snapshot_lifetime_and_shutdown_drain() {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"slot.bin";
|
|
auto gate = std::make_shared<Gate>();
|
|
auto snapshot = std::make_shared<const std::string>("captured tick 123");
|
|
std::weak_ptr<const std::string> lifetime = snapshot;
|
|
SaveService service({.capacity = 2});
|
|
SaveRequest immutable{path, 123, session(), [snapshot, gate] { gate->wait(); return *snapshot; }};
|
|
auto first = service.try_submit(immutable);
|
|
immutable.produce = {};
|
|
snapshot.reset();
|
|
gate->await_entry();
|
|
require(!lifetime.expired(), "queued save did not retain immutable snapshot");
|
|
|
|
// This producer cannot run until the first is released. Admission itself
|
|
// must finish while that writer is blocked (without a disk/producer lock).
|
|
auto caller = std::async(std::launch::async, [&] { return service.try_submit(request(path, "newer", 124)); });
|
|
require(caller.wait_for(2s) == std::future_status::ready, "submission waited on the writer");
|
|
auto second = caller.get();
|
|
require(second.admission == SaveAdmission::Accepted && second.request_id == first.request_id + 1,
|
|
"second FIFO request not admitted");
|
|
std::atomic<std::size_t> rejected_invocations{0};
|
|
SaveRequest third{path, 125, session(), [&] { ++rejected_invocations; return "not accepted"; }};
|
|
const auto rejected = service.try_submit(third);
|
|
require(rejected.admission == SaveAdmission::Busy && rejected.request_id == 0 &&
|
|
!rejected.completion.valid() && static_cast<bool>(third.produce), "capacity did not include running request");
|
|
|
|
std::promise<void> shutdown_started;
|
|
auto starting = shutdown_started.get_future();
|
|
auto draining = std::async(std::launch::async, [&] { shutdown_started.set_value(); service.shutdown(); });
|
|
starting.get();
|
|
const auto deadline = std::chrono::steady_clock::now() + 2s;
|
|
SaveAdmission while_draining;
|
|
do {
|
|
while_draining = service.try_submit(third).admission;
|
|
if (while_draining == SaveAdmission::Closed) break;
|
|
std::this_thread::yield();
|
|
} while (std::chrono::steady_clock::now() < deadline);
|
|
require(while_draining == SaveAdmission::Closed, "shutdown held admission lock while draining");
|
|
require(draining.wait_for(0s) == std::future_status::timeout, "shutdown did not wait for accepted work");
|
|
gate->open();
|
|
require(draining.wait_for(10s) == std::future_status::ready, "shutdown failed to drain");
|
|
draining.get();
|
|
require(completed(first).succeeded() && completed(second).succeeded(), "accepted saves lost during shutdown");
|
|
require(read(path) == "newer", "older FIFO request overwrote newer save");
|
|
require(lifetime.expired(), "completed save unnecessarily retained its snapshot");
|
|
require(rejected_invocations == 0, "rejected producer was invoked");
|
|
require(service.try_submit(third).admission == SaveAdmission::Closed, "shutdown did not close admission");
|
|
}
|
|
|
|
Test SaveServiceTests::failed_producer_does_not_stop_writer() {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"slot.bin";
|
|
write(path, "old");
|
|
SaveService service;
|
|
SaveRequest broken{path, 1, session(), []() -> std::string { throw std::runtime_error("producer failure"); }};
|
|
auto first = service.try_submit(broken);
|
|
const auto failed = completed(first);
|
|
require(failed.error == SaveError::ProducerFailed && failed.phase == SavePhase::Materialize &&
|
|
!failed.visible_on_disk && read(path) == "old", "producer failure changed the slot");
|
|
auto second = service.try_submit(request(path, "recovered"));
|
|
require(completed(second).succeeded() && read(path) == "recovered", "writer stopped after producer failure");
|
|
service.shutdown();
|
|
only_files(directory, 1);
|
|
}
|
|
|
|
Test SaveServiceTests::invalid_missing_parent_and_sharing_failure() {
|
|
TemporaryDirectory directory;
|
|
SaveService service;
|
|
auto relative = request(L"relative.bin", "bytes");
|
|
require(service.try_submit(relative).admission == SaveAdmission::InvalidRequest, "relative path accepted");
|
|
auto nil = request(directory.path / L"nil.bin", "bytes");
|
|
nil.session = {};
|
|
require(service.try_submit(nil).admission == SaveAdmission::InvalidRequest, "nil session accepted");
|
|
auto absent = service.try_submit(request(directory.path / L"missing" / L"slot.bin", "bytes"));
|
|
const auto absent_result = completed(absent);
|
|
require(absent_result.error == SaveError::Io && absent_result.phase == SavePhase::CreateStage &&
|
|
!absent_result.visible_on_disk, "missing parent was not rejected by the writer");
|
|
const auto path = directory.path / L"locked.bin";
|
|
write(path, "locked previous generation");
|
|
{
|
|
Reader lock(path, FILE_SHARE_READ);
|
|
auto blocked = service.try_submit(request(path, "replacement"));
|
|
const auto result = completed(blocked);
|
|
require(result.error == SaveError::Io && result.phase == SavePhase::Publish &&
|
|
result.native_error != 0 && !result.visible_on_disk && !result.durability_unknown,
|
|
"sharing failure was not reported before publication");
|
|
require(lock.read() == "locked previous generation", "sharing failure modified existing file");
|
|
}
|
|
auto retry = service.try_submit(request(path, "replacement"));
|
|
require(completed(retry).succeeded() && read(path) == "replacement", "sharing failure stopped writer");
|
|
service.shutdown();
|
|
only_files(directory, 1);
|
|
}
|
|
|
|
Test SaveServiceTests::concurrent_submission_identity_matches_publication_order() {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"slot.bin";
|
|
SaveService service({.capacity = 16});
|
|
constexpr std::size_t callers = 8;
|
|
std::latch start(callers);
|
|
std::array<SaveSubmission, callers> submissions;
|
|
std::array<std::thread, callers> threads;
|
|
for (std::size_t index = 0; index < callers; ++index) {
|
|
threads[index] = std::thread([&, index] {
|
|
const auto input = request(path, std::to_string(index));
|
|
start.arrive_and_wait();
|
|
do {
|
|
submissions[index] = service.try_submit(input);
|
|
if (submissions[index].admission == SaveAdmission::Busy) std::this_thread::yield();
|
|
} while (submissions[index].admission == SaveAdmission::Busy);
|
|
});
|
|
}
|
|
for (auto& thread : threads) thread.join();
|
|
service.shutdown();
|
|
std::array<std::uint64_t, callers> ids;
|
|
std::size_t newest = 0;
|
|
for (std::size_t index = 0; index < callers; ++index) {
|
|
require(completed(submissions[index]).succeeded(), "concurrent save failed");
|
|
ids[index] = submissions[index].request_id;
|
|
if (ids[index] > ids[newest]) newest = index;
|
|
}
|
|
require(read(path) == std::to_string(newest), "publication order disagreed with acceptance identity");
|
|
std::ranges::sort(ids);
|
|
for (std::size_t index = 0; index < callers; ++index) require(ids[index] == index + 1, "duplicate or missing identity");
|
|
only_files(directory, 1);
|
|
}
|
|
|
|
Test SaveServiceTests::empty_file_and_size_limit() {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"slot.bin";
|
|
SaveService service({.max_bytes = 3});
|
|
auto empty = service.try_submit(request(path, ""));
|
|
require(completed(empty).succeeded() && read(path).empty(), "empty save failed");
|
|
auto large = service.try_submit(request(path, "four"));
|
|
const auto rejected = completed(large);
|
|
require(rejected.error == SaveError::TooLarge && !rejected.visible_on_disk && read(path).empty(),
|
|
"oversized generation modified slot");
|
|
service.shutdown();
|
|
only_files(directory, 1);
|
|
}
|
|
|
|
Test SaveServiceTests::self_shutdown_is_rejected_without_closing_service() {
|
|
TemporaryDirectory directory;
|
|
const auto path = directory.path / L"slot.bin";
|
|
SaveService service;
|
|
SaveRequest recursive{path, 1, session(), [&]() -> std::string { service.shutdown(); return "unreachable"; }};
|
|
auto first = service.try_submit(recursive);
|
|
require(completed(first).error == SaveError::ProducerFailed, "writer self-join did not fail safely");
|
|
auto second = service.try_submit(request(path, "still running"));
|
|
require(completed(second).succeeded(), "self-join closed service");
|
|
}
|
|
|
|
} // namespace
|