Files
Library/src/Update/VersionStore.cpp
T
faumaray 3851aeb703
CI / GCC 16 / C++26 / werror (push) Failing after 3m9s
CI / GCC 16 / C++26 / sanitizers (push) Failing after 10m15s
CI / GCC 16 / C++26 / default (push) Failing after 13m1s
Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-20 01:18:53 +03:00

1827 lines
55 KiB
C++

#include <Void/Update/VersionStore.hpp>
#include <Void/Data/Json.hpp>
#include <algorithm>
#include <atomic>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <format>
#include <fstream>
#include <iterator>
#include <map>
#include <set>
#include <system_error>
#include <utility>
#include <vector>
#ifndef _WIN32
#include <cerrno>
#include <cstring>
#include <dirent.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::Update
{
namespace
{
[[nodiscard]] Void::Result::Error
filesystem_error(std::string_view operation,
const std::filesystem::path& path,
const std::error_code& error)
{
return Void::Result::Error{std::format("VersionStore: {} '{}': {}",
operation, path.string(),
error.message())};
}
[[nodiscard]] Void::Result::Result<void>
require_real_directory(const std::filesystem::path& path)
{
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (error) {
return std::unexpected{
filesystem_error("inspect directory", path, error)};
}
if (std::filesystem::is_symlink(status) ||
!std::filesystem::is_directory(status)) {
return Void::Result::fail(
std::format("VersionStore: '{}' must be a real directory",
path.string()));
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
ensure_real_directory(const std::filesystem::path& path)
{
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (!error && std::filesystem::exists(status)) {
return require_real_directory(path);
}
if (error != std::errc::no_such_file_or_directory && error) {
return std::unexpected{
filesystem_error("inspect directory", path, error)};
}
error.clear();
std::filesystem::create_directories(path, error);
if (error) {
return std::unexpected{
filesystem_error("create directory", path, error)};
}
return require_real_directory(path);
}
constexpr std::uintmax_t maximumActivationJournalSize = 64 * 1024;
#ifdef _WIN32
[[nodiscard]] Void::Result::Result<std::string>
read_file(const std::filesystem::path& path)
{
std::ifstream input{path, std::ios::binary};
if (!input.is_open()) {
return Void::Result::fail(std::format(
"VersionStore: cannot read '{}'", path.string()));
}
std::string data{std::istreambuf_iterator<char>{input}, {}};
if (input.bad()) {
return Void::Result::fail(std::format(
"VersionStore: I/O error reading '{}'", path.string()));
}
return data;
}
#endif
#ifndef _WIN32
class FileDescriptor
{
public:
explicit FileDescriptor(int descriptor = -1) noexcept
: m_descriptor(descriptor)
{
}
~FileDescriptor()
{
if (m_descriptor >= 0) {
(void)::close(m_descriptor);
}
}
FileDescriptor(FileDescriptor&& other) noexcept
: m_descriptor(std::exchange(other.m_descriptor, -1))
{
}
FileDescriptor& operator=(FileDescriptor&& other) noexcept
{
if (this != &other) {
if (m_descriptor >= 0) {
(void)::close(m_descriptor);
}
m_descriptor = std::exchange(other.m_descriptor, -1);
}
return *this;
}
FileDescriptor(const FileDescriptor&) = delete;
FileDescriptor& operator=(const FileDescriptor&) = delete;
[[nodiscard]] int get() const noexcept { return m_descriptor; }
private:
int m_descriptor{-1};
};
class FileLock
{
public:
[[nodiscard]] static Void::Result::Result<FileLock>
acquire(const std::filesystem::path& path)
{
const int descriptor =
::open(path.c_str(),
O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600);
if (descriptor < 0) {
return Void::Result::fail(
std::format("VersionStore: open lock '{}': {}",
path.string(), std::strerror(errno)));
}
// The lock contains no data. Read permission lets an
// unprivileged runtime take a shared lock while a
// privileged updater remains the only writer.
if (::fchmod(descriptor, 0644) != 0) {
const auto message =
std::format("VersionStore: set lock mode '{}': {}",
path.string(), std::strerror(errno));
::close(descriptor);
return Void::Result::fail(message);
}
if (::flock(descriptor, LOCK_EX) != 0) {
const auto message =
std::format("VersionStore: lock '{}': {}",
path.string(), std::strerror(errno));
::close(descriptor);
return Void::Result::fail(message);
}
return FileLock{descriptor};
}
[[nodiscard]] static Void::Result::Result<FileLock>
acquireShared(const std::filesystem::path& path)
{
const int descriptor =
::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
if (descriptor < 0) {
return Void::Result::fail(
std::format("VersionStore: open lock '{}': {}",
path.string(), std::strerror(errno)));
}
if (::flock(descriptor, LOCK_SH) != 0) {
const auto message =
std::format("VersionStore: lock '{}': {}",
path.string(), std::strerror(errno));
::close(descriptor);
return Void::Result::fail(message);
}
return FileLock{descriptor};
}
~FileLock()
{
if (m_descriptor >= 0) {
(void)::flock(m_descriptor, LOCK_UN);
(void)::close(m_descriptor);
}
}
FileLock(FileLock&& other) noexcept
: m_descriptor(std::exchange(other.m_descriptor, -1))
{
}
FileLock& operator=(FileLock&& other) noexcept
{
if (this != &other) {
if (m_descriptor >= 0) {
(void)::flock(m_descriptor, LOCK_UN);
(void)::close(m_descriptor);
}
m_descriptor = std::exchange(other.m_descriptor, -1);
}
return *this;
}
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
private:
explicit FileLock(int descriptor) noexcept
: m_descriptor(descriptor)
{
}
int m_descriptor{-1};
};
[[nodiscard]] Void::Result::Result<void>
sync_directory(const std::filesystem::path& path)
{
const int descriptor = ::open(
path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
if (descriptor < 0) {
return Void::Result::fail(
std::format("VersionStore: open directory '{}': {}",
path.string(), std::strerror(errno)));
}
const int result = ::fsync(descriptor);
const int error = errno;
(void)::close(descriptor);
if (result != 0) {
return Void::Result::fail(
std::format("VersionStore: fsync directory '{}': {}",
path.string(), std::strerror(error)));
}
return {};
}
[[nodiscard]] std::filesystem::path
temporary_sibling(const std::filesystem::path& path)
{
static std::atomic<std::uint64_t> counter{0};
return path.parent_path() /
std::format(".{}.{}.{}", path.filename().string(),
static_cast<long long>(::getpid()),
counter.fetch_add(1, std::memory_order_relaxed));
}
[[nodiscard]] Void::Result::Result<void>
durable_write(const std::filesystem::path& path,
std::string_view data,
const bool readableByOthers = false)
{
const auto temporary = temporary_sibling(path);
const mode_t mode = readableByOthers ? 0644 : 0600;
const int descriptor =
::open(temporary.c_str(),
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode);
if (descriptor < 0) {
return Void::Result::fail(
std::format("VersionStore: create '{}': {}",
temporary.string(), std::strerror(errno)));
}
if (::fchmod(descriptor, mode) != 0) {
const auto message =
std::format("VersionStore: set mode '{}': {}",
temporary.string(), std::strerror(errno));
(void)::close(descriptor);
(void)::unlink(temporary.c_str());
return Void::Result::fail(message);
}
std::size_t written = 0;
while (written < data.size()) {
const auto count = ::write(descriptor, data.data() + written,
data.size() - written);
if (count < 0 && errno == EINTR) {
continue;
}
if (count <= 0) {
const auto message =
std::format("VersionStore: write '{}': {}",
temporary.string(), std::strerror(errno));
(void)::close(descriptor);
(void)::unlink(temporary.c_str());
return Void::Result::fail(message);
}
written += static_cast<std::size_t>(count);
}
if (::fsync(descriptor) != 0) {
const auto message =
std::format("VersionStore: fsync '{}': {}",
temporary.string(), std::strerror(errno));
(void)::close(descriptor);
(void)::unlink(temporary.c_str());
return Void::Result::fail(message);
}
if (::close(descriptor) != 0) {
(void)::unlink(temporary.c_str());
return Void::Result::fail(
std::format("VersionStore: close '{}': {}",
temporary.string(), std::strerror(errno)));
}
if (::rename(temporary.c_str(), path.c_str()) != 0) {
const auto message = std::format(
"VersionStore: rename '{}' to '{}': {}", temporary.string(),
path.string(), std::strerror(errno));
(void)::unlink(temporary.c_str());
return Void::Result::fail(message);
}
return sync_directory(path.parent_path());
}
[[nodiscard]] Void::Result::Result<void>
atomic_link(const std::filesystem::path& path,
const std::filesystem::path& target)
{
const auto temporary = temporary_sibling(path);
if (::symlink(target.c_str(), temporary.c_str()) != 0) {
return Void::Result::fail(
std::format("VersionStore: create symlink '{}': {}",
temporary.string(), std::strerror(errno)));
}
if (::rename(temporary.c_str(), path.c_str()) != 0) {
const auto message =
std::format("VersionStore: activate symlink '{}': {}",
path.string(), std::strerror(errno));
(void)::unlink(temporary.c_str());
return Void::Result::fail(message);
}
return sync_directory(path.parent_path());
}
[[nodiscard]] Void::Result::Result<FileDescriptor>
open_real_directory(const std::filesystem::path& path)
{
const int descriptor = ::open(
path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
if (descriptor < 0) {
return Void::Result::fail(
std::format("VersionStore: open directory '{}': {}",
path.string(), std::strerror(errno)));
}
return FileDescriptor{descriptor};
}
[[nodiscard]]
Void::Result::Result<std::optional<std::string>>
read_activation_journal(const std::filesystem::path& root)
{
const int directoryFlags = O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW
#ifdef O_PATH
| O_PATH
#else
| O_RDONLY
#endif
;
FileDescriptor directory{::open(root.c_str(), directoryFlags)};
if (directory.get() < 0) {
return Void::Result::fail(
std::format("VersionStore: open directory '{}': {}",
root.string(), std::strerror(errno)));
}
FileDescriptor descriptor{
::openat(directory.get(), "activation.json",
O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)};
if (descriptor.get() < 0) {
if (errno == ENOENT) {
return std::optional<std::string>{};
}
return Void::Result::fail(std::format(
"VersionStore: open activation journal '{}': {}",
(root / "activation.json").string(), std::strerror(errno)));
}
struct stat status{};
if (::fstat(descriptor.get(), &status) != 0) {
return Void::Result::fail(std::format(
"VersionStore: inspect activation journal '{}': {}",
(root / "activation.json").string(), std::strerror(errno)));
}
if (!S_ISREG(status.st_mode) || status.st_nlink != 1 ||
status.st_size < 0 ||
static_cast<std::uintmax_t>(status.st_size) >
maximumActivationJournalSize) {
return Void::Result::fail(
"VersionStore: activation journal must be a bounded "
"regular file");
}
std::string data(static_cast<std::size_t>(status.st_size), '\0');
std::size_t read = 0;
while (read < data.size()) {
const auto count = ::read(descriptor.get(), data.data() + read,
data.size() - read);
if (count < 0 && errno == EINTR) {
continue;
}
if (count <= 0) {
return Void::Result::fail(std::format(
"VersionStore: read activation journal '{}': {}",
(root / "activation.json").string(),
count == 0 ? "unexpected end of file"
: std::strerror(errno)));
}
read += static_cast<std::size_t>(count);
}
struct stat finalStatus{};
if (::fstat(descriptor.get(), &finalStatus) != 0 ||
finalStatus.st_size != status.st_size) {
return Void::Result::fail(
"VersionStore: activation journal changed while reading");
}
return std::optional<std::string>{std::move(data)};
}
[[nodiscard]] Void::Result::Result<void>
require_published_real_directory(const std::filesystem::path& root,
std::string_view versionName)
{
auto versions = open_real_directory(root / "versions");
if (!versions) {
return std::unexpected{versions.error()};
}
const std::string name{versionName};
struct stat status{};
if (::fstatat(versions->get(), name.c_str(), &status,
AT_SYMLINK_NOFOLLOW) != 0 ||
!S_ISDIR(status.st_mode)) {
return Void::Result::fail(
std::format("VersionStore: version '{}' is not a real "
"published directory",
versionName));
}
FileDescriptor opened{
::openat(versions->get(), name.c_str(),
O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)};
if (opened.get() < 0) {
return Void::Result::fail(
std::format("VersionStore: open published version '{}': {}",
versionName, std::strerror(errno)));
}
struct stat openedStatus{};
if (::fstat(opened.get(), &openedStatus) != 0 ||
openedStatus.st_dev != status.st_dev ||
openedStatus.st_ino != status.st_ino) {
return Void::Result::fail(
std::format("VersionStore: published version '{}' changed "
"while validating",
versionName));
}
return {};
}
[[nodiscard]] Void::Result::Result<std::vector<std::string>>
directory_entries(int descriptor,
const std::filesystem::path& displayPath)
{
const int duplicate =
::openat(descriptor, ".",
O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
if (duplicate < 0) {
return Void::Result::fail(
std::format("VersionStore: duplicate directory '{}': {}",
displayPath.string(), std::strerror(errno)));
}
DIR* stream = ::fdopendir(duplicate);
if (stream == nullptr) {
const int error = errno;
(void)::close(duplicate);
return Void::Result::fail(
std::format("VersionStore: enumerate directory '{}': {}",
displayPath.string(), std::strerror(error)));
}
std::vector<std::string> entries;
errno = 0;
while (const auto* entry = ::readdir(stream)) {
const std::string_view name{entry->d_name};
if (name != "." && name != "..") {
entries.emplace_back(name);
}
errno = 0;
}
const int error = errno;
(void)::closedir(stream);
if (error != 0) {
return Void::Result::fail(
std::format("VersionStore: enumerate directory '{}': {}",
displayPath.string(), std::strerror(error)));
}
return entries;
}
constexpr std::size_t maximumRemovalDepth = 128;
constexpr int maximumRemovalPasses = 16;
[[nodiscard]] Void::Result::Result<void>
remove_entry_no_follow(int parentDescriptor, std::string_view name,
const std::filesystem::path& displayPath,
std::size_t depth = 0)
{
if (depth > maximumRemovalDepth) {
return Void::Result::fail(
std::format("VersionStore: removal depth exceeded at '{}'",
displayPath.string()));
}
const std::string entryName{name};
for (int attempt = 0; attempt < maximumRemovalPasses; ++attempt) {
struct stat status{};
if (::fstatat(parentDescriptor, entryName.c_str(), &status,
AT_SYMLINK_NOFOLLOW) != 0) {
if (errno == ENOENT) {
return {};
}
return Void::Result::fail(std::format(
"VersionStore: inspect removal entry '{}': {}",
displayPath.string(), std::strerror(errno)));
}
if (!S_ISDIR(status.st_mode)) {
if (::unlinkat(parentDescriptor, entryName.c_str(), 0) ==
0 ||
errno == ENOENT) {
return {};
}
if (errno == EISDIR) {
continue;
}
return Void::Result::fail(std::format(
"VersionStore: remove entry '{}': {}",
displayPath.string(), std::strerror(errno)));
}
FileDescriptor child{
::openat(parentDescriptor, entryName.c_str(),
O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)};
if (child.get() < 0) {
if (errno == ENOENT) {
return {};
}
if (errno == ELOOP || errno == ENOTDIR) {
continue;
}
return Void::Result::fail(std::format(
"VersionStore: open removal directory '{}': {}",
displayPath.string(), std::strerror(errno)));
}
struct stat openedStatus{};
if (::fstat(child.get(), &openedStatus) != 0) {
return Void::Result::fail(std::format(
"VersionStore: inspect opened directory '{}': {}",
displayPath.string(), std::strerror(errno)));
}
if (openedStatus.st_dev != status.st_dev ||
openedStatus.st_ino != status.st_ino) {
continue;
}
auto entries = directory_entries(child.get(), displayPath);
if (!entries) {
return std::unexpected{entries.error()};
}
for (const auto& childName : *entries) {
if (auto removed = remove_entry_no_follow(
child.get(), childName, displayPath / childName,
depth + 1);
!removed) {
return removed;
}
}
if (::unlinkat(parentDescriptor, entryName.c_str(),
AT_REMOVEDIR) == 0 ||
errno == ENOENT) {
return {};
}
if (errno != ENOTEMPTY && errno != EEXIST && errno != ENOTDIR) {
return Void::Result::fail(std::format(
"VersionStore: remove directory '{}': {}",
displayPath.string(), std::strerror(errno)));
}
}
return Void::Result::fail(std::format(
"VersionStore: directory '{}' changed while pruning",
displayPath.string()));
}
#else
struct FileLock {
[[nodiscard]] static Void::Result::Result<FileLock>
acquire(const std::filesystem::path&)
{
return FileLock{};
}
[[nodiscard]] static Void::Result::Result<FileLock>
acquireShared(const std::filesystem::path&)
{
return FileLock{};
}
};
[[nodiscard]] Void::Result::Result<void>
sync_directory(const std::filesystem::path&)
{
return {};
}
[[nodiscard]] Void::Result::Result<void>
durable_write(const std::filesystem::path& path,
std::string_view data,
const bool readableByOthers = false)
{
(void)readableByOthers;
std::ofstream output{path.string() + ".tmp",
std::ios::binary | std::ios::trunc};
if (!output) {
return Void::Result::fail(
"VersionStore: create journal failed");
}
output.write(data.data(),
static_cast<std::streamsize>(data.size()));
output.close();
std::error_code error;
std::filesystem::rename(path.string() + ".tmp", path, error);
if (error) {
return std::unexpected{filesystem_error("rename", path, error)};
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
atomic_link(const std::filesystem::path& path,
const std::filesystem::path& target)
{
std::error_code error;
std::filesystem::remove(path, error);
error.clear();
std::filesystem::create_directory_symlink(target, path, error);
if (error) {
return std::unexpected{
filesystem_error("create symlink", path, error)};
}
return {};
}
[[nodiscard]]
Void::Result::Result<std::optional<std::string>>
read_activation_journal(const std::filesystem::path& root)
{
const auto path = root / "activation.json";
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (error == std::errc::no_such_file_or_directory ||
status.type() == std::filesystem::file_type::not_found) {
return std::optional<std::string>{};
}
if (error || std::filesystem::is_symlink(status) ||
!std::filesystem::is_regular_file(status)) {
return Void::Result::fail(
"VersionStore: activation journal must be a regular file");
}
const auto size = std::filesystem::file_size(path, error);
if (error || size > maximumActivationJournalSize) {
return Void::Result::fail(
"VersionStore: activation journal exceeds its size limit");
}
auto data = read_file(path);
if (!data) {
return std::unexpected{data.error()};
}
return std::optional<std::string>{std::move(*data)};
}
[[nodiscard]] Void::Result::Result<void>
require_published_real_directory(const std::filesystem::path& root,
std::string_view versionName)
{
const auto path = root / "versions" / std::string{versionName};
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (error || std::filesystem::is_symlink(status) ||
!std::filesystem::is_directory(status)) {
return Void::Result::fail(
std::format("VersionStore: version '{}' is not a real "
"published directory",
versionName));
}
return {};
}
#endif
[[nodiscard]] Void::Result::Result<std::vector<Semver::Version>>
published_versions(const std::filesystem::path& versionsRoot)
{
std::vector<Semver::Version> versions;
#ifndef _WIN32
auto directory = open_real_directory(versionsRoot);
if (!directory) {
return std::unexpected{directory.error()};
}
auto entries = directory_entries(directory->get(), versionsRoot);
if (!entries) {
return std::unexpected{entries.error()};
}
for (const auto& name : *entries) {
struct stat status{};
if (::fstatat(directory->get(), name.c_str(), &status,
AT_SYMLINK_NOFOLLOW) != 0 ||
!S_ISDIR(status.st_mode)) {
continue;
}
auto version = Semver::parse_strict(name);
if (version && version->to_string() == name) {
versions.push_back(std::move(*version));
}
}
#else
std::error_code error;
for (std::filesystem::directory_iterator
iterator{versionsRoot, error},
end;
!error && iterator != end;
iterator.increment(error)) {
const auto status = iterator->symlink_status(error);
if (error || std::filesystem::is_symlink(status) ||
!std::filesystem::is_directory(status)) {
error.clear();
continue;
}
const auto name = iterator->path().filename().string();
auto version = Semver::parse_strict(name);
if (version && version->to_string() == name) {
versions.push_back(std::move(*version));
}
}
if (error) {
return std::unexpected{filesystem_error(
"enumerate published versions", versionsRoot, error)};
}
#endif
return versions;
}
[[nodiscard]] Void::Result::Result<void>
quarantine_and_remove(const std::filesystem::path& versionsRoot,
std::string_view versionName)
{
static std::atomic<std::uint64_t> counter{0};
const auto quarantineName =
std::format(".prune.{}.{}", versionName,
counter.fetch_add(1, std::memory_order_relaxed));
#ifndef _WIN32
auto directory = open_real_directory(versionsRoot);
if (!directory) {
return std::unexpected{directory.error()};
}
const std::string sourceName{versionName};
if (::renameat(directory->get(), sourceName.c_str(),
directory->get(), quarantineName.c_str()) != 0) {
return Void::Result::fail(
std::format("VersionStore: quarantine version '{}': {}",
versionName, std::strerror(errno)));
}
if (auto removed =
remove_entry_no_follow(directory->get(), quarantineName,
versionsRoot / quarantineName);
!removed) {
return removed;
}
#else
const auto source = versionsRoot / versionName;
const auto quarantine = versionsRoot / quarantineName;
std::error_code error;
const auto status = std::filesystem::symlink_status(source, error);
if (error || std::filesystem::is_symlink(status) ||
!std::filesystem::is_directory(status)) {
return Void::Result::fail(std::format(
"VersionStore: version '{}' changed while pruning",
versionName));
}
std::filesystem::rename(source, quarantine, error);
if (error) {
return std::unexpected{
filesystem_error("quarantine version", source, error)};
}
std::filesystem::remove_all(quarantine, error);
if (error) {
return std::unexpected{filesystem_error(
"remove quarantined version", quarantine, error)};
}
#endif
(void)sync_directory(versionsRoot);
return {};
}
[[nodiscard]] Void::Result::Result<void>
cleanup_pruning_entries(const std::filesystem::path& versionsRoot)
{
#ifndef _WIN32
auto directory = open_real_directory(versionsRoot);
if (!directory) {
return std::unexpected{directory.error()};
}
auto entries = directory_entries(directory->get(), versionsRoot);
if (!entries) {
return std::unexpected{entries.error()};
}
for (const auto& name : *entries) {
if (!name.starts_with(".prune.")) {
continue;
}
if (auto removed = remove_entry_no_follow(
directory->get(), name, versionsRoot / name);
!removed) {
return removed;
}
}
#else
std::error_code error;
for (std::filesystem::directory_iterator
iterator{versionsRoot, error},
end;
!error && iterator != end;
iterator.increment(error)) {
if (!iterator->path().filename().string().starts_with(
".prune.")) {
continue;
}
const auto status = iterator->symlink_status(error);
if (error) {
break;
}
if (std::filesystem::is_symlink(status)) {
std::filesystem::remove(iterator->path(), error);
} else {
std::filesystem::remove_all(iterator->path(), error);
}
if (error) {
break;
}
}
if (error) {
return std::unexpected{filesystem_error(
"clean pruning quarantine", versionsRoot, error)};
}
#endif
(void)sync_directory(versionsRoot);
return {};
}
enum class HealthState : std::uint8_t {
published,
healthy,
failed,
retired,
};
struct HealthHistory {
std::map<std::string, HealthState, std::less<>> states;
std::vector<std::string> committedOrder;
std::map<std::string, std::uint64_t, std::less<>>
lastHealthyGeneration;
std::uint64_t generation{0};
};
constexpr std::uintmax_t maximumHealthHistorySize = 1024 * 1024;
constexpr std::uintmax_t healthHistoryCompactionThreshold =
(maximumHealthHistorySize * 3) / 4;
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
read_health_log(const std::filesystem::path& path)
{
#ifndef _WIN32
FileDescriptor descriptor{::open(
path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)};
if (descriptor.get() < 0) {
if (errno == ENOENT) {
return std::optional<std::string>{};
}
return Void::Result::fail(
std::format("VersionStore: open health history '{}': {}",
path.string(), std::strerror(errno)));
}
struct stat status{};
if (::fstat(descriptor.get(), &status) != 0) {
return Void::Result::fail(
std::format("VersionStore: inspect health history '{}': {}",
path.string(), std::strerror(errno)));
}
if (!S_ISREG(status.st_mode) || status.st_nlink != 1 ||
status.st_size < 0 ||
static_cast<std::uintmax_t>(status.st_size) >
maximumHealthHistorySize) {
return Void::Result::fail("VersionStore: health history must "
"be a bounded regular file");
}
std::string data(static_cast<std::size_t>(status.st_size), '\0');
std::size_t read = 0;
while (read < data.size()) {
const auto count = ::read(descriptor.get(), data.data() + read,
data.size() - read);
if (count < 0 && errno == EINTR) {
continue;
}
if (count <= 0) {
return Void::Result::fail(std::format(
"VersionStore: read health history '{}': {}",
path.string(),
count == 0 ? "unexpected end of file"
: std::strerror(errno)));
}
read += static_cast<std::size_t>(count);
}
return std::optional<std::string>{std::move(data)};
#else
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (error == std::errc::no_such_file_or_directory ||
status.type() == std::filesystem::file_type::not_found) {
return std::optional<std::string>{};
}
if (error || std::filesystem::is_symlink(status) ||
!std::filesystem::is_regular_file(status)) {
return Void::Result::fail(
"VersionStore: health history must be a regular file");
}
const auto size = std::filesystem::file_size(path, error);
if (error || size > maximumHealthHistorySize) {
return Void::Result::fail(
"VersionStore: health history exceeds its size limit");
}
auto data = read_file(path);
if (!data) {
return std::unexpected{data.error()};
}
return std::optional<std::string>{std::move(*data)};
#endif
}
[[nodiscard]] Void::Result::Result<HealthHistory>
read_health_history(const std::filesystem::path& root)
{
auto data = read_health_log(root / "health.log");
if (!data) {
return std::unexpected{data.error()};
}
HealthHistory history;
if (!*data) {
return history;
}
std::size_t offset = 0;
while (offset < (*data)->size()) {
const auto end = (*data)->find('\n', offset);
if (end == std::string::npos) {
return Void::Result::fail(
"VersionStore: health history has a partial record");
}
const std::string_view line{(*data)->data() + offset,
end - offset};
offset = end + 1;
if (line.size() < 3 || line[1] != ' ') {
return Void::Result::fail(
"VersionStore: health history record is invalid");
}
const auto versionText = line.substr(2);
auto version = Semver::parse_strict(versionText);
if (!version || version->to_string() != versionText) {
return Void::Result::fail(
"VersionStore: health history version is invalid");
}
const auto name = version->to_string();
++history.generation;
switch (line.front()) {
case 'P':
history.states[name] = HealthState::published;
std::erase(history.committedOrder, name);
break;
case 'H':
history.states[name] = HealthState::healthy;
std::erase(history.committedOrder, name);
history.committedOrder.push_back(name);
history.lastHealthyGeneration[name] =
history.generation;
break;
case 'F':
if (history.states[name] != HealthState::healthy) {
history.states[name] = HealthState::failed;
}
break;
case 'D':
history.states[name] = HealthState::retired;
std::erase(history.committedOrder, name);
break;
default:
return Void::Result::fail(
"VersionStore: health history event is invalid");
}
}
return history;
}
[[nodiscard]] Void::Result::Result<std::string>
compacted_health_snapshot(const std::filesystem::path& root,
const HealthHistory& history)
{
auto published = published_versions(root / "versions");
if (!published) {
return std::unexpected{published.error()};
}
std::sort(published->begin(), published->end());
std::set<std::string, std::less<>> publishedNames;
for (const auto& version : *published) {
publishedNames.insert(version.to_string());
}
std::string snapshot;
std::set<std::string, std::less<>> emittedHealthy;
for (const auto& name : history.committedOrder) {
const auto state = history.states.find(name);
if (!publishedNames.contains(name) ||
state == history.states.end() ||
state->second != HealthState::healthy) {
continue;
}
snapshot += std::format("H {}\n", name);
emittedHealthy.insert(name);
}
for (const auto& version : *published) {
const auto name = version.to_string();
const auto state = history.states.find(name);
if (state == history.states.end()) {
continue;
}
char event = '\0';
switch (state->second) {
case HealthState::published:
event = 'P';
break;
case HealthState::healthy:
if (!emittedHealthy.contains(name)) {
event = 'H';
}
break;
case HealthState::failed:
event = 'F';
break;
case HealthState::retired:
event = 'D';
break;
}
if (event != '\0') {
snapshot += std::format("{} {}\n", event, name);
}
}
if (snapshot.size() > maximumHealthHistorySize) {
return Void::Result::fail("VersionStore: compacted health "
"history exceeds its size limit");
}
return snapshot;
}
[[nodiscard]] Void::Result::Result<void>
compact_health_history_if_needed(const std::filesystem::path& root)
{
auto data = read_health_log(root / "health.log");
if (!data) {
return std::unexpected{data.error()};
}
if (!*data || (*data)->size() <= healthHistoryCompactionThreshold) {
return {};
}
auto pending = read_activation_journal(root);
if (!pending) {
return std::unexpected{pending.error()};
}
if (*pending) {
return {};
}
auto history = read_health_history(root);
if (!history) {
return std::unexpected{history.error()};
}
auto snapshot = compacted_health_snapshot(root, *history);
if (!snapshot) {
return std::unexpected{snapshot.error()};
}
return durable_write(root / "health.log", *snapshot, true);
}
[[nodiscard]] Void::Result::Result<void>
append_health_event(const std::filesystem::path& root, char event,
std::string_view versionName)
{
if (event != 'P' && event != 'H' && event != 'F' && event != 'D') {
return Void::Result::fail(
"VersionStore: invalid health history event");
}
const auto parsed = Semver::parse_strict(versionName);
if (!parsed || parsed->to_string() != versionName) {
return Void::Result::fail(
"VersionStore: invalid health history version");
}
if (auto compacted = compact_health_history_if_needed(root);
!compacted) {
return compacted;
}
auto data = read_health_log(root / "health.log");
if (!data) {
return std::unexpected{data.error()};
}
const auto line = std::format("{} {}\n", event, versionName);
std::string snapshot = *data ? std::move(**data) : std::string{};
if (snapshot.size() + line.size() > maximumHealthHistorySize) {
return Void::Result::fail(
"VersionStore: health history is not appendable");
}
snapshot += line;
return durable_write(root / "health.log", snapshot, true);
}
[[nodiscard]] Void::Result::Result<void>
mark_healthy(const std::filesystem::path& root,
const Semver::Version& version)
{
auto history = read_health_history(root);
if (!history) {
return std::unexpected{history.error()};
}
const auto name = version.to_string();
if (const auto found = history->states.find(name);
found != history->states.end() &&
found->second == HealthState::healthy) {
return {};
}
return append_health_event(root, 'H', name);
}
[[nodiscard]] Void::Result::Result<bool>
activation_commit_recorded(const std::filesystem::path& root,
const PendingActivation& pending)
{
// A snapshot rename that was visible after an earlier
// directory-fsync failure is not yet a durable marker. Successfully
// syncing the store directory here makes the currently visible
// snapshot durable before it is allowed to decide the activation.
if (auto synced = sync_directory(root); !synced) {
return std::unexpected{synced.error()};
}
auto history = read_health_history(root);
if (!history) {
return std::unexpected{history.error()};
}
const auto found = history->lastHealthyGeneration.find(
pending.candidateVersion.to_string());
return found != history->lastHealthyGeneration.end() &&
found->second > pending.healthGeneration;
}
void mark_failed_if_unhealthy(const std::filesystem::path& root,
const Semver::Version& version)
{
auto history = read_health_history(root);
if (!history) {
return;
}
const auto name = version.to_string();
if (const auto found = history->states.find(name);
found != history->states.end() &&
found->second == HealthState::healthy) {
return;
}
(void)append_health_event(root, 'F', name);
}
/// Remove the activation journal at the logical transition commit
/// point. Once unlink succeeds (or the journal is already absent),
/// callers must observe the operation as complete. Returning a later
/// directory-fsync error would invite an opposite transition even
/// though its compensation record no longer exists. A best-effort fsync
/// still narrows the crash window without making the live result
/// ambiguous.
[[nodiscard]] Void::Result::Result<void>
finish_activation_transition(const std::filesystem::path& root)
{
const auto journal = root / "activation.json";
std::error_code error;
(void)std::filesystem::remove(journal, error);
if (error) {
return std::unexpected{filesystem_error(
"remove activation journal", journal, error)};
}
(void)sync_directory(root);
return {};
}
[[nodiscard]] Void::Result::Result<std::string>
version_name(const Semver::Version& version)
{
const auto name = version.to_string();
const auto parsed = Semver::parse_strict(name);
if (!parsed || parsed->to_string() != name) {
return Void::Result::fail(
"VersionStore: invalid semantic version");
}
return name;
}
} // namespace
VersionStore::VersionStore(std::filesystem::path root)
: m_root(std::move(root))
{
}
Void::Result::Result<void> VersionStore::initialize()
{
if (auto created = ensure_real_directory(m_root); !created) {
return created;
}
if (auto created = ensure_real_directory(m_root / "versions");
!created) {
return created;
}
if (auto created = ensure_real_directory(m_root / "staging");
!created) {
return created;
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
return sync_directory(m_root);
}
Void::Result::Result<std::filesystem::path>
VersionStore::prepare(const Semver::Version& version)
{
if (auto initialized = initialize(); !initialized) {
return std::unexpected{initialized.error()};
}
auto name = version_name(version);
if (!name) {
return std::unexpected{name.error()};
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
static std::atomic<std::uint64_t> counter{0};
for (int attempt = 0; attempt < 32; ++attempt) {
const auto nonce =
static_cast<std::uint64_t>(std::chrono::steady_clock::now()
.time_since_epoch()
.count()) ^
counter.fetch_add(1, std::memory_order_relaxed);
const auto candidate =
m_root / "staging" /
std::format("{}.stage.{:016x}", *name, nonce);
std::error_code error;
if (std::filesystem::create_directory(candidate, error)) {
if (auto synced = sync_directory(m_root / "staging"); !synced) {
return std::unexpected{synced.error()};
}
return candidate;
}
if (error && error != std::errc::file_exists) {
return std::unexpected{filesystem_error(
"create staging directory", candidate, error)};
}
}
return Void::Result::fail(
"VersionStore: could not allocate a staging directory");
}
Void::Result::Result<void>
VersionStore::publish(const Semver::Version& version,
const std::filesystem::path& stagingDirectory)
{
auto name = version_name(version);
if (!name) {
return std::unexpected{name.error()};
}
for (const auto& path :
{m_root, m_root / "staging", m_root / "versions"}) {
if (auto checked = require_real_directory(path); !checked) {
return checked;
}
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
std::error_code error;
const auto stagingStatus =
std::filesystem::symlink_status(stagingDirectory, error);
if (error || std::filesystem::is_symlink(stagingStatus) ||
!std::filesystem::is_directory(stagingStatus)) {
return Void::Result::fail(
"VersionStore: staging path must be a real directory");
}
const auto canonicalStaging =
std::filesystem::canonical(stagingDirectory, error);
if (error) {
return std::unexpected{filesystem_error("resolve staging directory",
stagingDirectory, error)};
}
const auto canonicalStagingRoot =
std::filesystem::canonical(m_root / "staging", error);
if (error || canonicalStaging.parent_path() != canonicalStagingRoot) {
return Void::Result::fail(
"VersionStore: staging directory must be an immediate child of "
"the store staging directory");
}
const auto destination = versionPath(version);
const bool destinationExists =
std::filesystem::exists(destination, error);
if (error) {
return std::unexpected{filesystem_error("inspect published version",
destination, error)};
}
if (destinationExists) {
return Void::Result::fail(std::format(
"VersionStore: version '{}' is already published", *name));
}
if (auto recorded = append_health_event(m_root, 'P', *name);
!recorded) {
return recorded;
}
std::filesystem::rename(canonicalStaging, destination, error);
if (error) {
return std::unexpected{
filesystem_error("publish version", destination, error)};
}
return sync_directory(m_root / "versions");
}
Void::Result::Result<void>
VersionStore::activate(const Semver::Version& version)
{
auto name = version_name(version);
if (!name) {
return std::unexpected{name.error()};
}
for (const auto& path : {m_root, m_root / "versions"}) {
if (auto checked = require_real_directory(path); !checked) {
return checked;
}
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
if (auto checked = require_published_real_directory(m_root, *name);
!checked) {
return checked;
}
auto existingActivation = pendingActivation();
if (!existingActivation) {
return std::unexpected{existingActivation.error()};
}
if (*existingActivation) {
return Void::Result::fail(
"VersionStore: another activation is pending");
}
if (auto compacted = compact_health_history_if_needed(m_root);
!compacted) {
return compacted;
}
auto previous = currentVersion();
if (!previous) {
return std::unexpected{previous.error()};
}
auto health = read_health_history(m_root);
if (!health) {
return std::unexpected{health.error()};
}
std::string previousJson = "null";
if (*previous) {
previousJson = std::format("\"{}\"", (*previous)->to_string());
}
const auto journal =
std::format("{{\"schemaVersion\":1,\"previousVersion\":{},"
"\"candidateVersion\":\"{}\","
"\"healthGeneration\":\"{}\"}}",
previousJson, *name, health->generation);
if (auto written = durable_write(m_root / "activation.json", journal);
!written) {
return written;
}
return atomic_link(m_root / "current",
std::filesystem::path{"versions"} / *name);
}
Void::Result::Result<void> VersionStore::commit()
{
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
auto pending = pendingActivation();
if (!pending) {
return std::unexpected{pending.error()};
}
if (!*pending) {
auto current = currentVersion();
if (!current) {
return std::unexpected{current.error()};
}
if (*current) {
return mark_healthy(m_root, **current);
}
return {};
}
auto current = currentVersion();
if (!current) {
return std::unexpected{current.error()};
}
if (!*current || **current != (*pending)->candidateVersion) {
return Void::Result::fail("VersionStore: active version does not "
"match pending candidate");
}
auto alreadyCommitted = activation_commit_recorded(m_root, **pending);
if (!alreadyCommitted) {
return std::unexpected{alreadyCommitted.error()};
}
if (*alreadyCommitted) {
(void)finish_activation_transition(m_root);
return {};
}
const auto candidateName = (*pending)->candidateVersion.to_string();
if (auto recorded = append_health_event(m_root, 'H', candidateName);
!recorded) {
// A write or fsync may fail after the complete marker became
// visible. Re-read it before declaring the activation reversible.
auto visible = activation_commit_recorded(m_root, **pending);
if (!visible || !*visible) {
return std::unexpected{recorded.error()};
}
}
// The healthy event above is the durable commit point. Journal cleanup
// can be retried idempotently and cannot turn the operation back into a
// rollback-safe failure.
(void)finish_activation_transition(m_root);
return {};
}
Void::Result::Result<void> VersionStore::rollback()
{
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
auto pending = pendingActivation();
if (!pending) {
return std::unexpected{pending.error()};
}
if (!*pending) {
return {};
}
auto committed = activation_commit_recorded(m_root, **pending);
if (!committed) {
return std::unexpected{committed.error()};
}
if (*committed) {
auto current = currentVersion();
if (!current) {
return std::unexpected{current.error()};
}
if (!*current || **current != (*pending)->candidateVersion) {
return Void::Result::fail("VersionStore: committed activation "
"does not match current");
}
(void)finish_activation_transition(m_root);
return {};
}
if ((*pending)->previousVersion) {
const auto previousName = (*pending)->previousVersion->to_string();
if (auto checked =
require_published_real_directory(m_root, previousName);
!checked) {
return checked;
}
if (auto linked = atomic_link(m_root / "current",
std::filesystem::path{"versions"} /
previousName);
!linked) {
return linked;
}
} else {
std::error_code error;
std::filesystem::remove(m_root / "current", error);
if (error) {
return std::unexpected{filesystem_error(
"remove current link", m_root / "current", error)};
}
if (auto synced = sync_directory(m_root); !synced) {
return synced;
}
}
if (auto transitioned = finish_activation_transition(m_root);
!transitioned) {
return transitioned;
}
mark_failed_if_unhealthy(m_root, (*pending)->candidateVersion);
return {};
}
Void::Result::Result<void> VersionStore::reconcile() { return rollback(); }
Void::Result::Result<void>
VersionStore::recordHealthy(const Semver::Version& version)
{
auto name = version_name(version);
if (!name) {
return std::unexpected{name.error()};
}
for (const auto& path : {m_root, m_root / "versions"}) {
if (auto checked = require_real_directory(path); !checked) {
return checked;
}
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
auto pending = pendingActivation();
if (!pending) {
return std::unexpected{pending.error()};
}
if (*pending) {
return Void::Result::fail("VersionStore: recordHealthy cannot "
"commit an internal activation");
}
if (auto checked = require_published_real_directory(m_root, *name);
!checked) {
return checked;
}
return append_health_event(m_root, 'H', *name);
}
Void::Result::Result<void>
VersionStore::recordFailed(const Semver::Version& version)
{
auto name = version_name(version);
if (!name) {
return std::unexpected{name.error()};
}
for (const auto& path : {m_root, m_root / "versions"}) {
if (auto checked = require_real_directory(path); !checked) {
return checked;
}
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
if (auto checked = require_published_real_directory(m_root, *name);
!checked) {
return checked;
}
auto history = read_health_history(m_root);
if (!history) {
return std::unexpected{history.error()};
}
if (const auto found = history->states.find(*name);
found != history->states.end() &&
found->second == HealthState::healthy) {
return {};
}
return append_health_event(m_root, 'F', *name);
}
Void::Result::Result<std::vector<Semver::Version>>
VersionStore::healthyPublishedVersions() const
{
for (const auto& path : {m_root, m_root / "versions"}) {
if (auto checked = require_real_directory(path); !checked) {
return std::unexpected{checked.error()};
}
}
auto lock = FileLock::acquireShared(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
auto history = read_health_history(m_root);
if (!history) {
return std::unexpected{history.error()};
}
auto published = published_versions(m_root / "versions");
if (!published) {
return std::unexpected{published.error()};
}
std::set<std::string, std::less<>> publishedNames;
for (const auto& version : *published) {
publishedNames.insert(version.to_string());
}
std::vector<Semver::Version> healthy;
for (auto iterator = history->committedOrder.rbegin();
iterator != history->committedOrder.rend();
++iterator) {
const auto state = history->states.find(*iterator);
if (!publishedNames.contains(*iterator) ||
state == history->states.end() ||
state->second != HealthState::healthy) {
continue;
}
auto version = Semver::parse_strict(*iterator);
if (!version) {
return Void::Result::fail(
"VersionStore: healthy history version is invalid");
}
healthy.push_back(std::move(*version));
}
return healthy;
}
Void::Result::Result<std::vector<Semver::Version>>
VersionStore::prune(std::size_t retainedPreviousVersions)
{
for (const auto& path : {m_root, m_root / "versions"}) {
if (auto checked = require_real_directory(path); !checked) {
return std::unexpected{checked.error()};
}
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
if (auto cleaned = cleanup_pruning_entries(m_root / "versions");
!cleaned) {
return std::unexpected{cleaned.error()};
}
auto current = currentVersion();
if (!current) {
return std::unexpected{current.error()};
}
auto pending = pendingActivation();
if (!pending) {
return std::unexpected{pending.error()};
}
auto history = read_health_history(m_root);
if (!history) {
return std::unexpected{history.error()};
}
auto published = published_versions(m_root / "versions");
if (!published) {
return std::unexpected{published.error()};
}
std::sort(published->begin(), published->end(),
std::greater<Semver::Version>{});
std::set<std::string, std::less<>> publishedNames;
for (const auto& version : *published) {
publishedNames.insert(version.to_string());
}
std::set<std::string, std::less<>> retained;
std::optional<std::string> currentName;
if (*current) {
currentName = (**current).to_string();
retained.insert(*currentName);
}
if (*pending) {
retained.insert((*pending)->candidateVersion.to_string());
if ((*pending)->previousVersion) {
retained.insert((*pending)->previousVersion->to_string());
}
}
std::size_t retainedPrevious = 0;
for (auto iterator = history->committedOrder.rbegin();
iterator != history->committedOrder.rend() &&
retainedPrevious < retainedPreviousVersions;
++iterator) {
const auto state = history->states.find(*iterator);
if (publishedNames.contains(*iterator) &&
state != history->states.end() &&
state->second == HealthState::healthy &&
(!currentName || *iterator != *currentName) &&
!retained.contains(*iterator)) {
retained.insert(*iterator);
++retainedPrevious;
}
}
std::vector<Semver::Version> removed;
for (const auto& version : *published) {
const auto name = version.to_string();
if (retained.contains(name)) {
continue;
}
const auto state = history->states.find(name);
if (state == history->states.end() ||
(state->second != HealthState::healthy &&
state->second != HealthState::failed &&
state->second != HealthState::retired)) {
continue;
}
if (state->second != HealthState::retired) {
if (auto recorded = append_health_event(m_root, 'D', name);
!recorded) {
return std::unexpected{recorded.error()};
}
}
if (auto pruned = quarantine_and_remove(m_root / "versions", name);
!pruned) {
return std::unexpected{pruned.error()};
}
removed.push_back(version);
}
return removed;
}
Void::Result::Result<std::optional<Semver::Version>>
VersionStore::currentVersion() const
{
std::error_code error;
const auto status =
std::filesystem::symlink_status(m_root / "current", error);
if (error == std::errc::no_such_file_or_directory ||
status.type() == std::filesystem::file_type::not_found) {
return std::optional<Semver::Version>{};
}
if (error || !std::filesystem::is_symlink(status)) {
return Void::Result::fail(
"VersionStore: current is not a valid symlink");
}
const auto target =
std::filesystem::read_symlink(m_root / "current", error);
if (error || target.parent_path() != "versions") {
return Void::Result::fail(
"VersionStore: current symlink target is invalid");
}
auto version = Semver::parse_strict(target.filename().string());
if (!version) {
return Void::Result::fail(
"VersionStore: current target is not SemVer");
}
if (auto checked =
require_published_real_directory(m_root, version->to_string());
!checked) {
return std::unexpected{checked.error()};
}
return std::optional<Semver::Version>{std::move(*version)};
}
Void::Result::Result<std::optional<PendingActivation>>
VersionStore::pendingActivation() const
{
auto data = read_activation_journal(m_root);
if (!data) {
return std::unexpected{data.error()};
}
if (!*data) {
return std::optional<PendingActivation>{};
}
auto document = Json::parse(**data);
if (!document || !document->is_object() ||
document->get_num("schemaVersion") != 1) {
return Void::Result::fail(
"VersionStore: activation journal is invalid");
}
const auto* candidateValue = document->find("candidateVersion");
if (!candidateValue || !candidateValue->is_string()) {
return Void::Result::fail(
"VersionStore: activation candidate is missing");
}
auto candidate = Semver::parse_strict(candidateValue->as_string());
if (!candidate) {
return Void::Result::fail(
"VersionStore: activation candidate is invalid");
}
PendingActivation pending{.candidateVersion = std::move(*candidate)};
const auto* generationValue = document->find("healthGeneration");
if (generationValue == nullptr || !generationValue->is_string()) {
return Void::Result::fail(
"VersionStore: activation health generation is required");
}
const auto generationText = generationValue->as_string();
std::uint64_t generation = 0;
const auto [end, parseError] = std::from_chars(
generationText.data(),
generationText.data() + generationText.size(), generation);
if (parseError != std::errc{} ||
end != generationText.data() + generationText.size()) {
return Void::Result::fail(
"VersionStore: activation health generation is invalid");
}
pending.healthGeneration = generation;
if (const auto* previousValue = document->find("previousVersion");
previousValue && !previousValue->is_null()) {
if (!previousValue->is_string()) {
return Void::Result::fail(
"VersionStore: previous version is invalid");
}
auto previous = Semver::parse_strict(previousValue->as_string());
if (!previous) {
return Void::Result::fail(
"VersionStore: previous version is invalid");
}
pending.previousVersion = std::move(*previous);
}
return std::optional<PendingActivation>{std::move(pending)};
}
const std::filesystem::path& VersionStore::root() const noexcept
{
return m_root;
}
std::filesystem::path
VersionStore::versionPath(const Semver::Version& version) const
{
return m_root / "versions" / version.to_string();
}
} // namespace Void::Update