Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6002c1996 | ||
|
|
706383e13f | ||
|
|
81e1d54ac3 | ||
|
|
f57b508b0a | ||
|
|
b381d682c8 | ||
|
|
8c576fdcbf | ||
|
|
63eecc32c7 | ||
|
|
86bde8b172 | ||
|
|
a0e4bfa941 | ||
|
|
6c5c2dcd93 | ||
|
|
86510f99f0 | ||
|
|
a5f21c6374 | ||
|
|
2474292462 | ||
|
|
34cfd9cb39 | ||
|
|
72733e2b93 | ||
|
|
dc18d64b18 | ||
|
|
caebb7f7f1 | ||
|
|
df2ed107e2 | ||
|
|
e8565c6857 | ||
|
|
2c6e4eab82 | ||
|
|
359e0630c7 | ||
|
|
025d97c6f6 | ||
|
|
08038000cc | ||
|
|
ba49098798 | ||
|
|
60860d167a | ||
|
|
5a076cd8f2 | ||
|
|
82c3558524 | ||
|
|
3953891511 | ||
|
|
ba3c5a6734 | ||
|
|
00eefe0521 | ||
|
|
b062e759ba | ||
|
|
dddcc2b2f0 | ||
|
|
7d0ed43f76 | ||
|
|
acd4ff40f0 | ||
|
|
f100b4c89e | ||
|
|
4f67fd2b93 | ||
|
|
2e8afc471b | ||
|
|
f3176c2b54 | ||
|
|
a4851c2c20 | ||
|
|
f2b002eb26 | ||
|
|
afd4d99a2d | ||
|
|
37c3cd4383 | ||
|
|
d30384d981 | ||
|
|
51ceb081ac | ||
|
|
7b0fea6095 |
No files matched your search
@@ -265,6 +265,43 @@ function(void_fetch_dependency DEP_NAME)
|
|||||||
endif()
|
endif()
|
||||||
return()
|
return()
|
||||||
endif()
|
endif()
|
||||||
|
if(DEP_NAME STREQUAL "Lua")
|
||||||
|
if(TARGET Lua::Lua)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
# Prefer a system Lua 5.4 development package.
|
||||||
|
find_package(Lua 5.4 QUIET)
|
||||||
|
if(LUA_FOUND)
|
||||||
|
add_library(Lua::Lua INTERFACE IMPORTED)
|
||||||
|
set_property(TARGET Lua::Lua PROPERTY
|
||||||
|
INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}")
|
||||||
|
set_property(TARGET Lua::Lua PROPERTY
|
||||||
|
INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}")
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
message(STATUS "[Void] Lua 5.4 not found - falling back to FetchContent")
|
||||||
|
FetchContent_Declare(Lua
|
||||||
|
URL https://www.lua.org/ftp/lua-5.4.9.tar.gz
|
||||||
|
URL_HASH SHA256=2335b6c582a52654f94612bf10d2f4672805d05329aa6568b1d8cd9e5c6fb8e6
|
||||||
|
SYSTEM
|
||||||
|
)
|
||||||
|
FetchContent_MakeAvailable(Lua)
|
||||||
|
file(GLOB _void_lua_sources "${lua_SOURCE_DIR}/src/*.c")
|
||||||
|
list(REMOVE_ITEM _void_lua_sources
|
||||||
|
"${lua_SOURCE_DIR}/src/lua.c"
|
||||||
|
"${lua_SOURCE_DIR}/src/luac.c")
|
||||||
|
add_library(void_lua STATIC ${_void_lua_sources})
|
||||||
|
set_target_properties(void_lua PROPERTIES
|
||||||
|
POSITION_INDEPENDENT_CODE ON
|
||||||
|
C_STANDARD 99
|
||||||
|
SYSTEM TRUE)
|
||||||
|
target_include_directories(void_lua SYSTEM PUBLIC
|
||||||
|
"${lua_SOURCE_DIR}/src")
|
||||||
|
add_library(Lua::Lua ALIAS void_lua)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
# FIXME: Add if needed external
|
# FIXME: Add if needed external
|
||||||
# if(DEP_NAME STREQUAL "glaze")
|
# if(DEP_NAME STREQUAL "glaze")
|
||||||
# if(NOT glaze_POPULATED)
|
# if(NOT glaze_POPULATED)
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Math/Vec.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cmath>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Algorithms
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Integer cell index in the voxel grid.
|
||||||
|
struct GridCell {
|
||||||
|
std::int64_t x{0};
|
||||||
|
std::int64_t y{0};
|
||||||
|
std::int64_t z{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const GridCell&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool operator==(const GridCell&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class GridAxis : std::uint8_t {
|
||||||
|
none = 0,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
z,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Face crossed when entering a cell.
|
||||||
|
///
|
||||||
|
/// `sign` is the direction of travel along `axis`: `+1` means the ray crossed
|
||||||
|
/// the lower boundary (entered through the cell's negative face), `-1` means
|
||||||
|
/// it crossed the upper boundary. `axis == none` is the starting cell.
|
||||||
|
struct GridFace {
|
||||||
|
GridAxis axis{GridAxis::none};
|
||||||
|
int sign{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const GridFace&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GridRayOptions {
|
||||||
|
/// Maximum number of cells yielded, including the start cell.
|
||||||
|
std::size_t max_steps{1024};
|
||||||
|
/// Maximum ray parameter for entering a cell. The start cell (t = 0) is
|
||||||
|
/// always yielded; a later cell is yielded only when its entry t is
|
||||||
|
/// `<= max_distance`.
|
||||||
|
double max_distance{std::numeric_limits<double>::infinity()};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GridRayVisit {
|
||||||
|
GridCell cell;
|
||||||
|
GridFace face;
|
||||||
|
/// Ray parameter at which the cell was entered (0 for the start cell).
|
||||||
|
double t{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class GridRayStatus : std::uint8_t {
|
||||||
|
/// More cells may be produced.
|
||||||
|
running = 0,
|
||||||
|
exhausted_steps,
|
||||||
|
exhausted_distance,
|
||||||
|
/// The direction was exactly (0, 0, 0); the start cell was still yielded.
|
||||||
|
zero_direction,
|
||||||
|
nonfinite_input,
|
||||||
|
/// A cell index would leave the int64 range.
|
||||||
|
out_of_range,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded 3D grid traversal (Amanatides-Woo DDA) over integer cells.
|
||||||
|
///
|
||||||
|
/// Policy:
|
||||||
|
/// - The start cell is `floor(origin)` per axis, so a coordinate exactly on a
|
||||||
|
/// boundary belongs to the cell on the positive side.
|
||||||
|
/// - Zero direction components never cross that axis (axis-parallel rays work).
|
||||||
|
/// - At simultaneous axis crossings (edge/corner ties) the axis with the lowest
|
||||||
|
/// index is stepped first: x, then y, then z. The traversal may therefore
|
||||||
|
/// visit the intermediate edge/corner cell; each visit reports the face it
|
||||||
|
/// crossed to enter.
|
||||||
|
/// - Nonfinite origin/direction is rejected before any visit. An all-zero
|
||||||
|
/// direction yields the start cell once and then reports `zero_direction`.
|
||||||
|
/// - The work is bounded by `max_steps` and `max_distance`.
|
||||||
|
class GridRayIterator
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
GridRayIterator(Void::Math::Vec3d origin,
|
||||||
|
Void::Math::Vec3d direction,
|
||||||
|
GridRayOptions options = {})
|
||||||
|
: options_(options)
|
||||||
|
{
|
||||||
|
if (!std::isfinite(origin.x) || !std::isfinite(origin.y) ||
|
||||||
|
!std::isfinite(origin.z) || !std::isfinite(direction.x) ||
|
||||||
|
!std::isfinite(direction.y) ||
|
||||||
|
!std::isfinite(direction.z) ||
|
||||||
|
std::isnan(options.max_distance)) {
|
||||||
|
status_ = GridRayStatus::nonfinite_input;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const double origin_axis[3] = {origin.x, origin.y, origin.z};
|
||||||
|
const double direction_axis[3] = {direction.x, direction.y,
|
||||||
|
direction.z};
|
||||||
|
bool any_direction = false;
|
||||||
|
for (int axis = 0; axis < 3; ++axis) {
|
||||||
|
const double coordinate = std::floor(origin_axis[axis]);
|
||||||
|
if (coordinate <
|
||||||
|
static_cast<double>(
|
||||||
|
std::numeric_limits<std::int64_t>::min()) ||
|
||||||
|
coordinate >
|
||||||
|
static_cast<double>(
|
||||||
|
std::numeric_limits<std::int64_t>::max())) {
|
||||||
|
status_ = GridRayStatus::out_of_range;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cell_[axis] = static_cast<std::int64_t>(coordinate);
|
||||||
|
|
||||||
|
const double direction_value = direction_axis[axis];
|
||||||
|
if (direction_value == 0.0) {
|
||||||
|
step_[axis] = 0;
|
||||||
|
t_max_[axis] =
|
||||||
|
std::numeric_limits<double>::infinity();
|
||||||
|
t_delta_[axis] =
|
||||||
|
std::numeric_limits<double>::infinity();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
any_direction = true;
|
||||||
|
step_[axis] = direction_value > 0.0 ? 1 : -1;
|
||||||
|
const double boundary =
|
||||||
|
step_[axis] > 0
|
||||||
|
? static_cast<double>(cell_[axis]) + 1.0
|
||||||
|
: static_cast<double>(cell_[axis]);
|
||||||
|
t_max_[axis] =
|
||||||
|
(boundary - origin_axis[axis]) / direction_value;
|
||||||
|
t_delta_[axis] =
|
||||||
|
1.0 / std::abs(direction_value);
|
||||||
|
}
|
||||||
|
zero_direction_ = !any_direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<GridRayVisit> next()
|
||||||
|
{
|
||||||
|
if (status_ != GridRayStatus::running) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (!started_) {
|
||||||
|
if (options_.max_steps == 0) {
|
||||||
|
status_ = GridRayStatus::exhausted_steps;
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
started_ = true;
|
||||||
|
visited_ = 1;
|
||||||
|
const GridRayVisit visit{.cell = GridCell{cell_[0], cell_[1],
|
||||||
|
cell_[2]},
|
||||||
|
.face = {},
|
||||||
|
.t = 0.0};
|
||||||
|
if (zero_direction_) {
|
||||||
|
status_ = GridRayStatus::zero_direction;
|
||||||
|
} else if (visited_ >= options_.max_steps) {
|
||||||
|
status_ = GridRayStatus::exhausted_steps;
|
||||||
|
}
|
||||||
|
return visit;
|
||||||
|
}
|
||||||
|
|
||||||
|
int axis = 0;
|
||||||
|
if (t_max_[1] < t_max_[axis]) {
|
||||||
|
axis = 1;
|
||||||
|
}
|
||||||
|
if (t_max_[2] < t_max_[axis]) {
|
||||||
|
axis = 2;
|
||||||
|
}
|
||||||
|
const double t = t_max_[axis];
|
||||||
|
if (t > options_.max_distance) {
|
||||||
|
status_ = GridRayStatus::exhausted_distance;
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if ((step_[axis] > 0 &&
|
||||||
|
cell_[axis] == std::numeric_limits<std::int64_t>::max()) ||
|
||||||
|
(step_[axis] < 0 &&
|
||||||
|
cell_[axis] == std::numeric_limits<std::int64_t>::min())) {
|
||||||
|
status_ = GridRayStatus::out_of_range;
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
cell_[axis] += step_[axis];
|
||||||
|
t_max_[axis] += t_delta_[axis];
|
||||||
|
++visited_;
|
||||||
|
const GridRayVisit visit{
|
||||||
|
.cell = GridCell{cell_[0], cell_[1], cell_[2]},
|
||||||
|
.face = GridFace{
|
||||||
|
.axis = axis == 0 ? GridAxis::x
|
||||||
|
: axis == 1 ? GridAxis::y : GridAxis::z,
|
||||||
|
.sign = step_[axis]},
|
||||||
|
.t = t};
|
||||||
|
if (visited_ >= options_.max_steps) {
|
||||||
|
status_ = GridRayStatus::exhausted_steps;
|
||||||
|
}
|
||||||
|
return visit;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] GridRayStatus status() const noexcept
|
||||||
|
{
|
||||||
|
return status_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] GridCell cell() const noexcept
|
||||||
|
{
|
||||||
|
return GridCell{cell_[0], cell_[1], cell_[2]};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
GridRayOptions options_;
|
||||||
|
std::array<std::int64_t, 3> cell_{};
|
||||||
|
std::array<int, 3> step_{};
|
||||||
|
std::array<double, 3> t_max_{};
|
||||||
|
std::array<double, 3> t_delta_{};
|
||||||
|
GridRayStatus status_{GridRayStatus::running};
|
||||||
|
std::size_t visited_{0};
|
||||||
|
bool started_{false};
|
||||||
|
bool zero_direction_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GridRaycastResult {
|
||||||
|
std::optional<GridRayVisit> hit;
|
||||||
|
GridRayStatus status{GridRayStatus::running};
|
||||||
|
std::size_t visited{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Traverse until `occupied(cell)` is true, then return that cell and the face
|
||||||
|
/// it was entered through (the start cell reports `GridFace{}`).
|
||||||
|
template <typename Occupancy>
|
||||||
|
[[nodiscard]] GridRaycastResult
|
||||||
|
raycast_grid(Void::Math::Vec3d origin,
|
||||||
|
Void::Math::Vec3d direction,
|
||||||
|
Occupancy&& occupied,
|
||||||
|
GridRayOptions options = {})
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{origin, direction, options};
|
||||||
|
GridRaycastResult result;
|
||||||
|
while (const auto visit = iterator.next()) {
|
||||||
|
++result.visited;
|
||||||
|
if (occupied(visit->cell)) {
|
||||||
|
result.hit = *visit;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.status = iterator.status();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Algorithms
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Algorithms
|
||||||
|
{
|
||||||
|
|
||||||
|
enum class ReadSetStatus : std::uint8_t {
|
||||||
|
/// A new key/revision pair was recorded.
|
||||||
|
recorded = 0,
|
||||||
|
/// The same key with the same revision was already recorded.
|
||||||
|
unchanged,
|
||||||
|
/// The same key was observed with a different revision.
|
||||||
|
conflicting,
|
||||||
|
/// The entry bound is reached; nothing was recorded.
|
||||||
|
capacity_exceeded,
|
||||||
|
/// The key is empty.
|
||||||
|
invalid_key,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ReadSetValidation : std::uint8_t {
|
||||||
|
valid = 0,
|
||||||
|
/// A recorded key is missing or has a different revision.
|
||||||
|
invalidated,
|
||||||
|
/// The validating view belongs to another epoch.
|
||||||
|
epoch_changed,
|
||||||
|
/// A conflicting observation was reported; the set cannot be published.
|
||||||
|
conflicted,
|
||||||
|
/// An observation was rejected for capacity; the set is incomplete.
|
||||||
|
incomplete,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ReadSetLimits {
|
||||||
|
std::size_t max_entries{256};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded set of distinct key/revision pairs consulted while computing a
|
||||||
|
/// result, qualified by an epoch.
|
||||||
|
///
|
||||||
|
/// Repeated reads of one unchanged key consume one entry. Observing the same
|
||||||
|
/// key with a different revision is reported as a conflict, and an entry over
|
||||||
|
/// the bound as capacity exhaustion; `validate` refuses to report a conflicted
|
||||||
|
/// or incomplete set as valid so a result cannot be published from it.
|
||||||
|
///
|
||||||
|
/// Validation compares the recorded set against a stable read view supplied by
|
||||||
|
/// the caller (a revision lookup per key plus the view's epoch). An epoch
|
||||||
|
/// change invalidates the set even when every numeric revision matches. Keys
|
||||||
|
/// not in the set (unrelated edits) do not affect the result.
|
||||||
|
class RevisionReadSet
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Limits = ReadSetLimits;
|
||||||
|
|
||||||
|
explicit RevisionReadSet(std::uint64_t epoch, Limits limits = {})
|
||||||
|
: epoch_(epoch)
|
||||||
|
, limits_(limits)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint64_t epoch() const noexcept { return epoch_; }
|
||||||
|
|
||||||
|
[[nodiscard]] ReadSetStatus observe(std::string key,
|
||||||
|
std::uint64_t revision)
|
||||||
|
{
|
||||||
|
if (key.empty()) {
|
||||||
|
return ReadSetStatus::invalid_key;
|
||||||
|
}
|
||||||
|
if (const auto found = entries_.find(key);
|
||||||
|
found != entries_.end()) {
|
||||||
|
if (found->second == revision) {
|
||||||
|
return ReadSetStatus::unchanged;
|
||||||
|
}
|
||||||
|
conflicted_ = true;
|
||||||
|
return ReadSetStatus::conflicting;
|
||||||
|
}
|
||||||
|
if (entries_.size() >= limits_.max_entries) {
|
||||||
|
incomplete_ = true;
|
||||||
|
return ReadSetStatus::capacity_exceeded;
|
||||||
|
}
|
||||||
|
entries_.emplace(std::move(key), revision);
|
||||||
|
return ReadSetStatus::recorded;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool contains(std::string_view key) const
|
||||||
|
{
|
||||||
|
return entries_.contains(std::string{key});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<std::uint64_t>
|
||||||
|
revision_of(std::string_view key) const
|
||||||
|
{
|
||||||
|
const auto found = entries_.find(std::string{key});
|
||||||
|
if (found == entries_.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t size() const noexcept
|
||||||
|
{
|
||||||
|
return entries_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool conflicted() const noexcept { return conflicted_; }
|
||||||
|
[[nodiscard]] bool incomplete() const noexcept { return incomplete_; }
|
||||||
|
|
||||||
|
/// Recorded observations, sorted by key.
|
||||||
|
[[nodiscard]] const std::map<std::string, std::uint64_t>&
|
||||||
|
entries() const noexcept
|
||||||
|
{
|
||||||
|
return entries_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate against a stable read view.
|
||||||
|
///
|
||||||
|
/// `lookup(key)` returns the current revision of `key`, or `nullopt`
|
||||||
|
/// when it no longer exists. `view_epoch` is the epoch of the view.
|
||||||
|
template <typename Lookup>
|
||||||
|
[[nodiscard]] ReadSetValidation
|
||||||
|
validate(std::uint64_t view_epoch, Lookup&& lookup) const
|
||||||
|
{
|
||||||
|
if (view_epoch != epoch_) {
|
||||||
|
return ReadSetValidation::epoch_changed;
|
||||||
|
}
|
||||||
|
if (conflicted_) {
|
||||||
|
return ReadSetValidation::conflicted;
|
||||||
|
}
|
||||||
|
if (incomplete_) {
|
||||||
|
return ReadSetValidation::incomplete;
|
||||||
|
}
|
||||||
|
for (const auto& [key, revision] : entries_) {
|
||||||
|
const auto current = lookup(key);
|
||||||
|
if (!current.has_value() || *current != revision) {
|
||||||
|
return ReadSetValidation::invalidated;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ReadSetValidation::valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::uint64_t epoch_{0};
|
||||||
|
Limits limits_{};
|
||||||
|
std::map<std::string, std::uint64_t> entries_;
|
||||||
|
bool conflicted_{false};
|
||||||
|
bool incomplete_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Algorithms
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <deque>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Async
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Bounded work queue whose admission is conditioned on an exact retained
|
||||||
|
/// publication token.
|
||||||
|
///
|
||||||
|
/// A producer validates a publication (and may retain its value elsewhere),
|
||||||
|
/// then submits work with that token. Comparison against the current token and
|
||||||
|
/// the capacity reservation happen under one lock, so a replacement published
|
||||||
|
/// between validation and submission is detected: the work is not moved and
|
||||||
|
/// the queue is unchanged.
|
||||||
|
///
|
||||||
|
/// Refusal outcomes are distinct: `publication_changed`, `saturated` and
|
||||||
|
/// `closed` (checked in that order). The payload is moved only when the result
|
||||||
|
/// is `admitted`. Admitted work is popped exactly once.
|
||||||
|
///
|
||||||
|
/// Thread-safe.
|
||||||
|
template <typename Work, typename Token = std::uint64_t>
|
||||||
|
class PublicationGatedQueue
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
struct Limits {
|
||||||
|
std::size_t capacity{64};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Status : std::uint8_t {
|
||||||
|
admitted = 0,
|
||||||
|
/// The current token differs from the expected one.
|
||||||
|
publication_changed,
|
||||||
|
/// The queue is at capacity.
|
||||||
|
saturated,
|
||||||
|
/// The queue no longer accepts submissions.
|
||||||
|
closed,
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit PublicationGatedQueue(Token initial,
|
||||||
|
Limits limits = Limits{})
|
||||||
|
: token_(std::move(initial))
|
||||||
|
, limits_(limits)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
PublicationGatedQueue(const PublicationGatedQueue&) = delete;
|
||||||
|
PublicationGatedQueue& operator=(const PublicationGatedQueue&) =
|
||||||
|
delete;
|
||||||
|
|
||||||
|
/// Publish a replacement token. Returns false once closed.
|
||||||
|
bool publish(Token next)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (closed_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
token_ = std::move(next);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Token current() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return token_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Admit `work` only if `expected` is still the current publication and
|
||||||
|
/// capacity is available. `work` is moved only on `admitted`.
|
||||||
|
[[nodiscard]] Status try_submit(const Token& expected, Work&& work)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (closed_) {
|
||||||
|
return Status::closed;
|
||||||
|
}
|
||||||
|
if (!(token_ == expected)) {
|
||||||
|
return Status::publication_changed;
|
||||||
|
}
|
||||||
|
if (queue_.size() >= limits_.capacity) {
|
||||||
|
return Status::saturated;
|
||||||
|
}
|
||||||
|
queue_.push_back(std::move(work));
|
||||||
|
return Status::admitted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove one admitted item, if any.
|
||||||
|
[[nodiscard]] std::optional<Work> try_pop()
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (queue_.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
Work work = std::move(queue_.front());
|
||||||
|
queue_.pop_front();
|
||||||
|
return work;
|
||||||
|
}
|
||||||
|
|
||||||
|
void close()
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
closed_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool closed() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return closed_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t size() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return queue_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Limits limits() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return limits_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
Token token_;
|
||||||
|
Limits limits_{};
|
||||||
|
std::deque<Work> queue_;
|
||||||
|
bool closed_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Async
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Containers
|
||||||
|
{
|
||||||
|
|
||||||
|
using LedgerQuantity = std::uint64_t;
|
||||||
|
using LedgerAccountKey = std::string;
|
||||||
|
using LedgerOperationId = std::string;
|
||||||
|
|
||||||
|
struct LedgerDebit {
|
||||||
|
LedgerAccountKey account;
|
||||||
|
LedgerQuantity quantity{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const LedgerDebit&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool operator==(const LedgerDebit&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class LedgerStatus : std::uint8_t {
|
||||||
|
committed = 0,
|
||||||
|
/// The operation already committed; the recorded outcome is returned.
|
||||||
|
replayed,
|
||||||
|
insufficient_balance,
|
||||||
|
capacity_exhausted,
|
||||||
|
overflow,
|
||||||
|
unknown_operation,
|
||||||
|
unknown_account,
|
||||||
|
/// Operation id reused with a different request or a forbidden phase.
|
||||||
|
invalid_state,
|
||||||
|
/// A released reservation cannot be delivered.
|
||||||
|
released,
|
||||||
|
limit_exceeded,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ReservationPhase : std::uint8_t {
|
||||||
|
held = 0,
|
||||||
|
delivered,
|
||||||
|
released,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LedgerResult {
|
||||||
|
LedgerStatus status{LedgerStatus::unknown_operation};
|
||||||
|
ReservationPhase phase{ReservationPhase::held};
|
||||||
|
LedgerOperationId operation;
|
||||||
|
|
||||||
|
[[nodiscard]] bool committed() const noexcept
|
||||||
|
{
|
||||||
|
return status == LedgerStatus::committed ||
|
||||||
|
status == LedgerStatus::replayed;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const LedgerResult&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LedgerLimits {
|
||||||
|
std::size_t max_accounts{1024};
|
||||||
|
std::size_t max_operations{4096};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// In-memory, restorable account ledger with atomic multi-account
|
||||||
|
/// reservations and repeatable transfers.
|
||||||
|
///
|
||||||
|
/// Accounts are caller-keyed and carry an owner, a balance and a capacity.
|
||||||
|
/// `reserve` debits one or more accounts atomically into a held reservation;
|
||||||
|
/// `transfer` gives the reserved quantity to a destination account (the next
|
||||||
|
/// owner); `release` returns it to the sources without changing ownership.
|
||||||
|
///
|
||||||
|
/// Every committed phase is recorded under its operation id, so repeating the
|
||||||
|
/// same request returns the recorded outcome instead of applying it twice.
|
||||||
|
/// The state is a plain value: `save()` can be persisted and `restore()`d, and
|
||||||
|
/// a replay after restoring a partially completed transfer still applies once.
|
||||||
|
/// Failed attempts (insufficient balance, capacity, overflow) change nothing
|
||||||
|
/// and are not recorded, so they can be retried after conditions change.
|
||||||
|
///
|
||||||
|
/// Single-threaded by contract; callers synchronize concurrent access.
|
||||||
|
class AccountLedger
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Limits = LedgerLimits;
|
||||||
|
|
||||||
|
struct AccountState {
|
||||||
|
std::string owner;
|
||||||
|
LedgerQuantity balance{0};
|
||||||
|
LedgerQuantity capacity{
|
||||||
|
std::numeric_limits<LedgerQuantity>::max()};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const AccountState&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const AccountState&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OperationState {
|
||||||
|
/// Normalized (aggregated and sorted) debits of the reservation.
|
||||||
|
std::vector<LedgerDebit> sources;
|
||||||
|
ReservationPhase phase{ReservationPhase::held};
|
||||||
|
LedgerAccountKey destination;
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const OperationState&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const OperationState&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
std::map<LedgerAccountKey, AccountState> accounts;
|
||||||
|
std::map<LedgerOperationId, OperationState> operations;
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const State&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const State&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit AccountLedger(Limits limits = Limits{}) : limits_(limits) {}
|
||||||
|
|
||||||
|
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
|
||||||
|
|
||||||
|
[[nodiscard]] bool create_account(const LedgerAccountKey& key,
|
||||||
|
std::string owner,
|
||||||
|
LedgerQuantity balance = 0,
|
||||||
|
LedgerQuantity capacity =
|
||||||
|
std::numeric_limits<
|
||||||
|
LedgerQuantity>::max())
|
||||||
|
{
|
||||||
|
if (balance > capacity ||
|
||||||
|
accounts_.size() >= limits_.max_accounts ||
|
||||||
|
accounts_.contains(key)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
accounts_.emplace(key,
|
||||||
|
AccountState{.owner = std::move(owner),
|
||||||
|
.balance = balance,
|
||||||
|
.capacity = capacity});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool set_capacity(const LedgerAccountKey& key,
|
||||||
|
LedgerQuantity capacity)
|
||||||
|
{
|
||||||
|
const auto found = accounts_.find(key);
|
||||||
|
if (found == accounts_.end() ||
|
||||||
|
found->second.balance > capacity) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
found->second.capacity = capacity;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<AccountState>
|
||||||
|
account(const LedgerAccountKey& key) const
|
||||||
|
{
|
||||||
|
const auto found = accounts_.find(key);
|
||||||
|
if (found == accounts_.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sum of all balances plus quantities held in reservations.
|
||||||
|
[[nodiscard]] LedgerQuantity total() const
|
||||||
|
{
|
||||||
|
LedgerQuantity sum = 0;
|
||||||
|
for (const auto& [key, account] : accounts_) {
|
||||||
|
(void)key;
|
||||||
|
sum += account.balance;
|
||||||
|
}
|
||||||
|
for (const auto& [id, operation] : operations_) {
|
||||||
|
(void)id;
|
||||||
|
if (operation.phase == ReservationPhase::held) {
|
||||||
|
for (const auto& debit : operation.sources) {
|
||||||
|
sum += debit.quantity;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t account_count() const noexcept
|
||||||
|
{
|
||||||
|
return accounts_.size();
|
||||||
|
}
|
||||||
|
[[nodiscard]] std::size_t operation_count() const noexcept
|
||||||
|
{
|
||||||
|
return operations_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Atomically debit every source into a held reservation.
|
||||||
|
[[nodiscard]] LedgerResult
|
||||||
|
reserve(const LedgerOperationId& operation,
|
||||||
|
std::vector<LedgerDebit> debits)
|
||||||
|
{
|
||||||
|
for (const auto& debit : debits) {
|
||||||
|
if (debit.account.empty() || debit.quantity == 0) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::invalid_state,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto normalized = normalize(std::move(debits));
|
||||||
|
if (!normalized.has_value()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::overflow,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto existing = operations_.find(operation);
|
||||||
|
existing != operations_.end()) {
|
||||||
|
if (existing->second.sources != *normalized) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::invalid_state,
|
||||||
|
.phase = existing->second.phase,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
return LedgerResult{.status = LedgerStatus::replayed,
|
||||||
|
.phase = existing->second.phase,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (operations_.size() >= limits_.max_operations) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::limit_exceeded,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& debit : *normalized) {
|
||||||
|
const auto found = accounts_.find(debit.account);
|
||||||
|
if (found == accounts_.end()) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = LedgerStatus::unknown_account,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.balance < debit.quantity) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = LedgerStatus::insufficient_balance,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// All preconditions hold: apply every debit.
|
||||||
|
for (const auto& debit : *normalized) {
|
||||||
|
accounts_.at(debit.account).balance -= debit.quantity;
|
||||||
|
}
|
||||||
|
operations_.emplace(operation,
|
||||||
|
OperationState{.sources = std::move(*normalized),
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.destination = {}});
|
||||||
|
return LedgerResult{.status = LedgerStatus::committed,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return a held reservation to its sources. Ownership is unchanged.
|
||||||
|
[[nodiscard]] LedgerResult release(const LedgerOperationId& operation)
|
||||||
|
{
|
||||||
|
const auto found = operations_.find(operation);
|
||||||
|
if (found == operations_.end()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::unknown_operation,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::released) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::replayed,
|
||||||
|
.phase = ReservationPhase::released,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::delivered) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = LedgerStatus::invalid_state,
|
||||||
|
.phase = ReservationPhase::delivered,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
for (const auto& debit : found->second.sources) {
|
||||||
|
accounts_.at(debit.account).balance += debit.quantity;
|
||||||
|
}
|
||||||
|
found->second.phase = ReservationPhase::released;
|
||||||
|
return LedgerResult{.status = LedgerStatus::committed,
|
||||||
|
.phase = ReservationPhase::released,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deliver a held reservation to `destination` (the next owner).
|
||||||
|
/// On capacity/overflow failure nothing changes and the reservation
|
||||||
|
/// stays held, so the caller can retry or release it.
|
||||||
|
[[nodiscard]] LedgerResult
|
||||||
|
transfer(const LedgerOperationId& operation,
|
||||||
|
const LedgerAccountKey& destination)
|
||||||
|
{
|
||||||
|
const auto found = operations_.find(operation);
|
||||||
|
if (found == operations_.end()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::unknown_operation,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::released) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::released,
|
||||||
|
.phase = ReservationPhase::released,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::delivered) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = found->second.destination == destination
|
||||||
|
? LedgerStatus::replayed
|
||||||
|
: LedgerStatus::invalid_state,
|
||||||
|
.phase = ReservationPhase::delivered,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto target = accounts_.find(destination);
|
||||||
|
if (target == accounts_.end()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::unknown_account,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
LedgerQuantity quantity = 0;
|
||||||
|
for (const auto& debit : found->second.sources) {
|
||||||
|
if (debit.quantity >
|
||||||
|
std::numeric_limits<LedgerQuantity>::max() - quantity) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::overflow,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
quantity += debit.quantity;
|
||||||
|
}
|
||||||
|
if (quantity >
|
||||||
|
target->second.capacity - target->second.balance) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::capacity_exhausted,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
target->second.balance += quantity;
|
||||||
|
found->second.phase = ReservationPhase::delivered;
|
||||||
|
found->second.destination = destination;
|
||||||
|
return LedgerResult{.status = LedgerStatus::committed,
|
||||||
|
.phase = ReservationPhase::delivered,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] State save() const
|
||||||
|
{
|
||||||
|
return State{.accounts = accounts_, .operations = operations_};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebuild a ledger from `save()` output. Rejects states that violate
|
||||||
|
/// the limits or the balance/capacity and reservation invariants.
|
||||||
|
[[nodiscard]] static std::optional<AccountLedger>
|
||||||
|
restore(State state, Limits limits = Limits{})
|
||||||
|
{
|
||||||
|
if (state.accounts.size() > limits.max_accounts ||
|
||||||
|
state.operations.size() > limits.max_operations) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
for (const auto& [key, account] : state.accounts) {
|
||||||
|
(void)key;
|
||||||
|
if (account.balance > account.capacity) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& [id, operation] : state.operations) {
|
||||||
|
(void)id;
|
||||||
|
if (operation.sources.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
for (const auto& debit : operation.sources) {
|
||||||
|
if (!state.accounts.contains(debit.account)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (operation.phase == ReservationPhase::delivered &&
|
||||||
|
!state.accounts.contains(operation.destination)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AccountLedger ledger{limits};
|
||||||
|
ledger.accounts_ = std::move(state.accounts);
|
||||||
|
ledger.operations_ = std::move(state.operations);
|
||||||
|
return ledger;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
[[nodiscard]] static std::optional<std::vector<LedgerDebit>>
|
||||||
|
normalize(std::vector<LedgerDebit> debits)
|
||||||
|
{
|
||||||
|
std::map<LedgerAccountKey, LedgerQuantity> aggregated;
|
||||||
|
for (const auto& debit : debits) {
|
||||||
|
LedgerQuantity& sum = aggregated[debit.account];
|
||||||
|
if (debit.quantity >
|
||||||
|
std::numeric_limits<LedgerQuantity>::max() - sum) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
sum += debit.quantity;
|
||||||
|
}
|
||||||
|
std::vector<LedgerDebit> normalized;
|
||||||
|
normalized.reserve(aggregated.size());
|
||||||
|
for (auto& [account, quantity] : aggregated) {
|
||||||
|
normalized.push_back(
|
||||||
|
LedgerDebit{.account = std::move(account),
|
||||||
|
.quantity = quantity});
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
Limits limits_{};
|
||||||
|
std::map<LedgerAccountKey, AccountState> accounts_;
|
||||||
|
std::map<LedgerOperationId, OperationState> operations_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Containers
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <span>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Containers
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Finite sparse 3D page table with revision-checked atomic edit batches.
|
||||||
|
///
|
||||||
|
/// Cells are grouped into fixed `PageSize`-cubed pages. Pages are allocated on
|
||||||
|
/// demand (a missing page reads as `empty` with revision 0) and bounded by
|
||||||
|
/// `Limits::max_pages`. `apply` validates every precondition, budget and
|
||||||
|
/// revision before touching the table; on failure nothing changes.
|
||||||
|
///
|
||||||
|
/// Batch semantics:
|
||||||
|
/// - Duplicate cell addresses in one batch are rejected.
|
||||||
|
/// - An edit whose value equals the current cell does not allocate a page and
|
||||||
|
/// does not bump a revision.
|
||||||
|
/// - `expected_revision` is checked against the page revision at batch start
|
||||||
|
/// (0 for a missing page).
|
||||||
|
/// - A changed page whose revision is already the maximum fails the batch.
|
||||||
|
/// - The result lists changed pages sorted by page identity with their new
|
||||||
|
/// revisions.
|
||||||
|
///
|
||||||
|
/// Single-threaded by contract; callers synchronize concurrent access.
|
||||||
|
template <typename Cell, std::size_t PageSize = 32> class SparsePageTable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
static_assert(PageSize > 0);
|
||||||
|
|
||||||
|
static constexpr std::size_t kPageSize = PageSize;
|
||||||
|
static constexpr std::size_t kCellsPerPage =
|
||||||
|
PageSize * PageSize * PageSize;
|
||||||
|
|
||||||
|
using Revision = std::uint64_t;
|
||||||
|
|
||||||
|
struct PageId {
|
||||||
|
std::int64_t x{0};
|
||||||
|
std::int64_t y{0};
|
||||||
|
std::int64_t z{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const PageId&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const PageId&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CellAddress {
|
||||||
|
std::int64_t x{0};
|
||||||
|
std::int64_t y{0};
|
||||||
|
std::int64_t z{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const CellAddress&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const CellAddress&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Edit {
|
||||||
|
CellAddress address;
|
||||||
|
Cell value;
|
||||||
|
std::optional<Revision> expected_revision{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const Edit&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Limits {
|
||||||
|
std::size_t max_pages{1024};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class EditStatus : std::uint8_t {
|
||||||
|
committed = 0,
|
||||||
|
/// A page's expected revision did not match the current one.
|
||||||
|
stale_revision,
|
||||||
|
/// A changed page already has the maximum revision.
|
||||||
|
revision_exhausted,
|
||||||
|
/// The batch would allocate more pages than the budget allows.
|
||||||
|
page_budget_exceeded,
|
||||||
|
/// The same cell address appears twice in the batch.
|
||||||
|
duplicate_edit,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ChangedPage {
|
||||||
|
PageId page;
|
||||||
|
Revision revision{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const ChangedPage&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct EditResult {
|
||||||
|
EditStatus status{EditStatus::committed};
|
||||||
|
std::vector<ChangedPage> changed{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool committed() const noexcept
|
||||||
|
{
|
||||||
|
return status == EditStatus::committed;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PageState {
|
||||||
|
PageId page;
|
||||||
|
Revision revision{0};
|
||||||
|
std::array<Cell, kCellsPerPage> cells{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const PageState&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
std::vector<PageState> pages;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const State&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit SparsePageTable(Limits limits = Limits{},
|
||||||
|
Cell empty = Cell{})
|
||||||
|
: limits_(limits)
|
||||||
|
, empty_(std::move(empty))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
|
||||||
|
[[nodiscard]] const Cell& empty_value() const noexcept
|
||||||
|
{
|
||||||
|
return empty_;
|
||||||
|
}
|
||||||
|
[[nodiscard]] std::size_t page_count() const noexcept
|
||||||
|
{
|
||||||
|
return pages_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cell value; a missing page yields `empty_value()`.
|
||||||
|
[[nodiscard]] Cell get(CellAddress address) const
|
||||||
|
{
|
||||||
|
const auto [id, offset] = locate(address);
|
||||||
|
const auto found = pages_.find(id);
|
||||||
|
if (found == pages_.end()) {
|
||||||
|
return empty_;
|
||||||
|
}
|
||||||
|
return found->second.cells[offset];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Page revision, or `nullopt` when the page is not allocated.
|
||||||
|
[[nodiscard]] std::optional<Revision>
|
||||||
|
page_revision(PageId page) const
|
||||||
|
{
|
||||||
|
const auto found = pages_.find(page);
|
||||||
|
if (found == pages_.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second.revision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply all edits or none.
|
||||||
|
[[nodiscard]] EditResult apply(std::span<const Edit> edits)
|
||||||
|
{
|
||||||
|
if (edits.empty()) {
|
||||||
|
return EditResult{};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::set<CellAddress> seen;
|
||||||
|
std::map<PageId, std::vector<const Edit*>> grouped;
|
||||||
|
for (const auto& edit : edits) {
|
||||||
|
if (!seen.insert(edit.address).second) {
|
||||||
|
return EditResult{.status =
|
||||||
|
EditStatus::duplicate_edit};
|
||||||
|
}
|
||||||
|
grouped[page_of(edit.address)].push_back(&edit);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::map<PageId, bool> changes;
|
||||||
|
std::size_t new_pages = 0;
|
||||||
|
for (const auto& [id, page_edits] : grouped) {
|
||||||
|
const auto found = pages_.find(id);
|
||||||
|
const Page* page =
|
||||||
|
found == pages_.end() ? nullptr : &found->second;
|
||||||
|
const Revision revision = page == nullptr ? 0
|
||||||
|
: page->revision;
|
||||||
|
for (const Edit* edit : page_edits) {
|
||||||
|
if (edit->expected_revision.has_value() &&
|
||||||
|
*edit->expected_revision != revision) {
|
||||||
|
return EditResult{
|
||||||
|
.status = EditStatus::stale_revision};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bool changed = false;
|
||||||
|
for (const Edit* edit : page_edits) {
|
||||||
|
const auto offset = offset_of(edit->address);
|
||||||
|
const Cell& current =
|
||||||
|
page == nullptr ? empty_ : page->cells[offset];
|
||||||
|
if (!(current == edit->value)) {
|
||||||
|
changed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (revision ==
|
||||||
|
std::numeric_limits<Revision>::max()) {
|
||||||
|
return EditResult{
|
||||||
|
.status = EditStatus::revision_exhausted};
|
||||||
|
}
|
||||||
|
changes.emplace(id, true);
|
||||||
|
if (page == nullptr) {
|
||||||
|
++new_pages;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pages_.size() + new_pages > limits_.max_pages) {
|
||||||
|
return EditResult{.status =
|
||||||
|
EditStatus::page_budget_exceeded};
|
||||||
|
}
|
||||||
|
|
||||||
|
EditResult result;
|
||||||
|
for (const auto& [id, changed] : changes) {
|
||||||
|
(void)changed;
|
||||||
|
auto& page = pages_[id];
|
||||||
|
for (const Edit* edit : grouped.at(id)) {
|
||||||
|
page.cells[offset_of(edit->address)] = edit->value;
|
||||||
|
}
|
||||||
|
++page.revision;
|
||||||
|
result.changed.push_back(
|
||||||
|
ChangedPage{.page = id, .revision = page.revision});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] State save() const
|
||||||
|
{
|
||||||
|
State state;
|
||||||
|
state.pages.reserve(pages_.size());
|
||||||
|
for (const auto& [id, page] : pages_) {
|
||||||
|
state.pages.push_back(PageState{
|
||||||
|
.page = id, .revision = page.revision, .cells = page.cells});
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore saved pages. Rejects duplicate page ids, more pages than the
|
||||||
|
/// limit, or a page with no revision left for an edit.
|
||||||
|
[[nodiscard]] static std::optional<SparsePageTable>
|
||||||
|
restore(State state, Limits limits = Limits{},
|
||||||
|
Cell empty = Cell{})
|
||||||
|
{
|
||||||
|
if (state.pages.size() > limits.max_pages) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
SparsePageTable table{limits, std::move(empty)};
|
||||||
|
for (auto& saved : state.pages) {
|
||||||
|
if (!table.pages_
|
||||||
|
.emplace(saved.page,
|
||||||
|
Page{.cells = saved.cells,
|
||||||
|
.revision = saved.revision})
|
||||||
|
.second) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Page {
|
||||||
|
std::array<Cell, kCellsPerPage> cells{};
|
||||||
|
Revision revision{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] static std::pair<std::int64_t, std::size_t>
|
||||||
|
split(std::int64_t coordinate)
|
||||||
|
{
|
||||||
|
constexpr auto size = static_cast<std::int64_t>(PageSize);
|
||||||
|
std::int64_t page = coordinate / size;
|
||||||
|
std::int64_t offset = coordinate % size;
|
||||||
|
if (offset < 0) {
|
||||||
|
--page;
|
||||||
|
offset += size;
|
||||||
|
}
|
||||||
|
return {page, static_cast<std::size_t>(offset)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static PageId page_of(CellAddress address)
|
||||||
|
{
|
||||||
|
return PageId{.x = split(address.x).first,
|
||||||
|
.y = split(address.y).first,
|
||||||
|
.z = split(address.z).first};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static std::size_t offset_of(CellAddress address)
|
||||||
|
{
|
||||||
|
const auto [px, ox] = split(address.x);
|
||||||
|
const auto [py, oy] = split(address.y);
|
||||||
|
const auto [pz, oz] = split(address.z);
|
||||||
|
(void)px;
|
||||||
|
(void)py;
|
||||||
|
(void)pz;
|
||||||
|
return (oz * PageSize + oy) * PageSize + ox;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static std::pair<PageId, std::size_t>
|
||||||
|
locate(CellAddress address)
|
||||||
|
{
|
||||||
|
return {page_of(address), offset_of(address)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Limits limits_{};
|
||||||
|
Cell empty_{};
|
||||||
|
std::map<PageId, Page> pages_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Containers
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Identity of a published snapshot: an epoch (session/domain) and a revision
|
||||||
|
/// that increases within that epoch.
|
||||||
|
struct PublicationVersion {
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
std::uint64_t revision{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const PublicationVersion&) const noexcept =
|
||||||
|
default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const PublicationVersion&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Single-writer, multi-reader publication of immutable values.
|
||||||
|
///
|
||||||
|
/// A producer prepares a complete immutable value and calls `publish` with its
|
||||||
|
/// version; readers call `acquire` and keep the returned `Snapshot` alive for
|
||||||
|
/// as long as they need a coherent view. Publishing swaps one fully built state
|
||||||
|
/// atomically: a reader sees either the previous or the next snapshot, never a
|
||||||
|
/// mixture, and a retained snapshot stays valid across any number of later
|
||||||
|
/// publications.
|
||||||
|
///
|
||||||
|
/// `publish` is compare-and-publish: when `expected_epoch` is supplied it must
|
||||||
|
/// equal the current epoch, and the new version must advance the current one
|
||||||
|
/// (higher epoch, or same epoch with a higher revision). A rejected publish
|
||||||
|
/// leaves the last good publication untouched, so a failed preparation that
|
||||||
|
/// never calls `publish` cannot corrupt readers.
|
||||||
|
///
|
||||||
|
/// The value is released when the publication and the last reader holding it
|
||||||
|
/// drop their snapshots.
|
||||||
|
template <typename T> class Publication
|
||||||
|
{
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
std::shared_ptr<const T> value;
|
||||||
|
PublicationVersion version;
|
||||||
|
};
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Value = T;
|
||||||
|
|
||||||
|
/// Retained, immutable view of one publication.
|
||||||
|
class Snapshot
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
Snapshot() noexcept = default;
|
||||||
|
|
||||||
|
[[nodiscard]] explicit operator bool() const noexcept
|
||||||
|
{
|
||||||
|
return state_ != nullptr && state_->value != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const T& operator*() const noexcept
|
||||||
|
{
|
||||||
|
return *state_->value;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const T* operator->() const noexcept
|
||||||
|
{
|
||||||
|
return state_->value.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const T* get() const noexcept
|
||||||
|
{
|
||||||
|
return state_ != nullptr ? state_->value.get()
|
||||||
|
: nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] PublicationVersion version() const noexcept
|
||||||
|
{
|
||||||
|
return state_ != nullptr ? state_->version
|
||||||
|
: PublicationVersion{};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
friend class Publication;
|
||||||
|
|
||||||
|
explicit Snapshot(std::shared_ptr<const State> state) noexcept
|
||||||
|
: state_(std::move(state))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<const State> state_{};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class PublishStatus : std::uint8_t {
|
||||||
|
published = 0,
|
||||||
|
/// The supplied or expected epoch is obsolete.
|
||||||
|
stale_epoch,
|
||||||
|
/// Same epoch, but the revision does not advance.
|
||||||
|
stale_revision,
|
||||||
|
/// The value is null.
|
||||||
|
invalid_value,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PublishResult {
|
||||||
|
PublishStatus status{PublishStatus::invalid_value};
|
||||||
|
PublicationVersion version{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool published() const noexcept
|
||||||
|
{
|
||||||
|
return status == PublishStatus::published;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit Publication(std::shared_ptr<const T> initial,
|
||||||
|
PublicationVersion version = {})
|
||||||
|
: current_{std::make_shared<State>(
|
||||||
|
State{std::move(initial), version})}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
Publication(const Publication&) = delete;
|
||||||
|
Publication& operator=(const Publication&) = delete;
|
||||||
|
|
||||||
|
/// Current snapshot; the returned handle keeps the value alive.
|
||||||
|
[[nodiscard]] Snapshot acquire() const
|
||||||
|
{
|
||||||
|
return Snapshot{
|
||||||
|
current_.load(std::memory_order_acquire)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] PublicationVersion version() const
|
||||||
|
{
|
||||||
|
return current_.load(std::memory_order_acquire)->version;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint64_t epoch() const
|
||||||
|
{
|
||||||
|
return version().epoch;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The version that `publish_next` would use: same epoch, next revision.
|
||||||
|
[[nodiscard]] PublicationVersion next_version() const
|
||||||
|
{
|
||||||
|
PublicationVersion next = version();
|
||||||
|
++next.revision;
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Publish `value` as `next`, optionally requiring `expected_epoch`.
|
||||||
|
///
|
||||||
|
/// The whole state (value and version) is swapped with one atomic
|
||||||
|
/// compare-exchange; on rejection nothing changes.
|
||||||
|
[[nodiscard]] PublishResult
|
||||||
|
publish(std::shared_ptr<const T> value,
|
||||||
|
PublicationVersion next,
|
||||||
|
std::optional<std::uint64_t> expected_epoch = std::nullopt)
|
||||||
|
{
|
||||||
|
if (value == nullptr) {
|
||||||
|
return PublishResult{.status = PublishStatus::invalid_value,
|
||||||
|
.version = version()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<State> current =
|
||||||
|
current_.load(std::memory_order_acquire);
|
||||||
|
for (;;) {
|
||||||
|
const PublicationVersion& observed = current->version;
|
||||||
|
if (expected_epoch.has_value() &&
|
||||||
|
*expected_epoch != observed.epoch) {
|
||||||
|
return PublishResult{.status = PublishStatus::stale_epoch,
|
||||||
|
.version = observed};
|
||||||
|
}
|
||||||
|
if (next.epoch < observed.epoch) {
|
||||||
|
return PublishResult{.status = PublishStatus::stale_epoch,
|
||||||
|
.version = observed};
|
||||||
|
}
|
||||||
|
if (next.epoch == observed.epoch &&
|
||||||
|
next.revision <= observed.revision) {
|
||||||
|
return PublishResult{
|
||||||
|
.status = PublishStatus::stale_revision,
|
||||||
|
.version = observed};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<State> desired =
|
||||||
|
std::make_shared<State>(State{value, next});
|
||||||
|
if (current_.compare_exchange_weak(
|
||||||
|
current,
|
||||||
|
std::move(desired),
|
||||||
|
std::memory_order_acq_rel,
|
||||||
|
std::memory_order_acquire)) {
|
||||||
|
return PublishResult{.status = PublishStatus::published,
|
||||||
|
.version = next};
|
||||||
|
}
|
||||||
|
// `current` now holds the state that won the race; retry the
|
||||||
|
// validation and the exchange against it.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience for the common case: same epoch, next revision.
|
||||||
|
[[nodiscard]] PublishResult
|
||||||
|
publish_next(std::shared_ptr<const T> value,
|
||||||
|
std::optional<std::uint64_t> expected_epoch =
|
||||||
|
std::nullopt)
|
||||||
|
{
|
||||||
|
return publish(std::move(value), next_version(), expected_epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a new epoch at revision 0, optionally requiring the previous
|
||||||
|
/// epoch.
|
||||||
|
[[nodiscard]] PublishResult
|
||||||
|
publish_epoch(std::shared_ptr<const T> value,
|
||||||
|
std::uint64_t epoch,
|
||||||
|
std::optional<std::uint64_t> expected_epoch =
|
||||||
|
std::nullopt)
|
||||||
|
{
|
||||||
|
return publish(std::move(value),
|
||||||
|
PublicationVersion{.epoch = epoch, .revision = 0},
|
||||||
|
expected_epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::atomic<std::shared_ptr<State>> current_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Core
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <limits>
|
||||||
|
#include <optional>
|
||||||
|
|
||||||
|
namespace Void::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
enum class SequenceErrorKind : std::uint8_t {
|
||||||
|
/// The requested id or batch does not fit in the remaining range.
|
||||||
|
exhausted = 0,
|
||||||
|
/// A batch of zero ids was requested.
|
||||||
|
zero_count,
|
||||||
|
/// The supplied saved state is not a valid sequence state.
|
||||||
|
invalid_state,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SequenceError {
|
||||||
|
SequenceErrorKind kind{SequenceErrorKind::exhausted};
|
||||||
|
/// How many ids were still available when the request failed.
|
||||||
|
std::uint64_t available{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Instance-owned, restorable id sequence with checked exhaustion.
|
||||||
|
///
|
||||||
|
/// Unlike `Void::Counted::SeqId<Tag>` (one process-wide atomic per tag), each
|
||||||
|
/// `IdSequence` owns its own state. It can be copied at a completed boundary,
|
||||||
|
/// saved and restored, and several instances (e.g. two worlds in one process)
|
||||||
|
/// allocate independently.
|
||||||
|
///
|
||||||
|
/// Ids start at 1. A removed record never gives its id back: the high-water
|
||||||
|
/// mark only moves forward, including across save/restore. `next()` and
|
||||||
|
/// `next_batch()` return `exhausted` *before* changing state when the request
|
||||||
|
/// does not fit, so a failed allocation leaves both the sequence and any
|
||||||
|
/// application record untouched.
|
||||||
|
///
|
||||||
|
/// `Rep` is the fixed-width representation used in saved state (default
|
||||||
|
/// `std::uint64_t`), making cross-platform saves reproducible. `Tag` keeps
|
||||||
|
/// unrelated id domains from being confused at compile time.
|
||||||
|
///
|
||||||
|
/// The class is not thread-safe; callers synchronize concurrent access to one
|
||||||
|
/// instance.
|
||||||
|
template <typename Tag = void, typename Rep = std::uint64_t> class IdSequence
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using value_type = Rep;
|
||||||
|
|
||||||
|
/// Serializable position. `exhausted` distinguishes "max is still
|
||||||
|
/// available" (`next == max`) from "max was already handed out".
|
||||||
|
struct State {
|
||||||
|
value_type next{1};
|
||||||
|
bool exhausted{false};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const State&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const State&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Batch {
|
||||||
|
value_type first{0};
|
||||||
|
value_type count{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr IdSequence() noexcept = default;
|
||||||
|
|
||||||
|
explicit constexpr IdSequence(value_type first) noexcept
|
||||||
|
: state_{.next = first == 0 ? value_type{1} : first}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Allocate one id.
|
||||||
|
[[nodiscard]] std::expected<value_type, SequenceError> next()
|
||||||
|
{
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return fail(SequenceErrorKind::exhausted);
|
||||||
|
}
|
||||||
|
const value_type id = state_.next;
|
||||||
|
if (id == maximum()) {
|
||||||
|
state_.exhausted = true;
|
||||||
|
} else {
|
||||||
|
state_.next = static_cast<value_type>(id + 1);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reserve a contiguous batch atomically: either all `count` ids are
|
||||||
|
/// reserved or none are.
|
||||||
|
[[nodiscard]] std::expected<Batch, SequenceError>
|
||||||
|
next_batch(std::size_t count)
|
||||||
|
{
|
||||||
|
if (count == 0) {
|
||||||
|
return fail(SequenceErrorKind::zero_count);
|
||||||
|
}
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return fail(SequenceErrorKind::exhausted);
|
||||||
|
}
|
||||||
|
const auto remaining = static_cast<std::uintmax_t>(available());
|
||||||
|
if (static_cast<std::uintmax_t>(count) > remaining) {
|
||||||
|
return fail(SequenceErrorKind::exhausted);
|
||||||
|
}
|
||||||
|
const value_type first = state_.next;
|
||||||
|
const auto step = static_cast<value_type>(count);
|
||||||
|
if (static_cast<std::uintmax_t>(step) == remaining) {
|
||||||
|
state_.exhausted = true;
|
||||||
|
} else {
|
||||||
|
state_.next = static_cast<value_type>(first + step);
|
||||||
|
}
|
||||||
|
return Batch{.first = first, .count = step};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many ids can still be allocated.
|
||||||
|
[[nodiscard]] value_type available() const noexcept
|
||||||
|
{
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return static_cast<value_type>(maximum() - state_.next + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool exhausted() const noexcept
|
||||||
|
{
|
||||||
|
return state_.exhausted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next id that would be handed out (or max once exhausted).
|
||||||
|
[[nodiscard]] value_type peek() const noexcept { return state_.next; }
|
||||||
|
|
||||||
|
/// Highest id ever handed out (0 before the first allocation).
|
||||||
|
[[nodiscard]] value_type high_water() const noexcept
|
||||||
|
{
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return maximum();
|
||||||
|
}
|
||||||
|
return state_.next == 1 ? value_type{0}
|
||||||
|
: static_cast<value_type>(state_.next - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] State state() const noexcept { return state_; }
|
||||||
|
|
||||||
|
/// Restore a saved state. Rejects non-canonical or impossible states;
|
||||||
|
/// on success the sequence continues exactly after the saved position.
|
||||||
|
[[nodiscard]] static std::expected<IdSequence, SequenceError>
|
||||||
|
restore(State state)
|
||||||
|
{
|
||||||
|
if (state.next == 0) {
|
||||||
|
return std::unexpected{SequenceError{
|
||||||
|
.kind = SequenceErrorKind::invalid_state, .available = 0}};
|
||||||
|
}
|
||||||
|
if (state.exhausted && state.next != maximum()) {
|
||||||
|
return std::unexpected{SequenceError{
|
||||||
|
.kind = SequenceErrorKind::invalid_state,
|
||||||
|
.available = 0}};
|
||||||
|
}
|
||||||
|
IdSequence sequence;
|
||||||
|
sequence.state_ = state;
|
||||||
|
return sequence;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static constexpr value_type maximum() noexcept
|
||||||
|
{
|
||||||
|
return std::numeric_limits<value_type>::max();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
[[nodiscard]] std::unexpected<SequenceError>
|
||||||
|
fail(SequenceErrorKind kind) const
|
||||||
|
{
|
||||||
|
return std::unexpected{SequenceError{
|
||||||
|
.kind = kind,
|
||||||
|
.available = static_cast<std::uint64_t>(available())}};
|
||||||
|
}
|
||||||
|
|
||||||
|
State state_{};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Core
|
||||||
@@ -298,6 +298,47 @@ template <std::integral T>
|
|||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Euclidean quotient and remainder for a strictly positive divisor:
|
||||||
|
/// `a == quotient * divisor + remainder` and `0 <= remainder < divisor`.
|
||||||
|
template <std::integral T> struct EuclideanDivision {
|
||||||
|
T quotient{};
|
||||||
|
T remainder{};
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr bool
|
||||||
|
operator==(const EuclideanDivision&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Checked Euclidean division. Unlike C++ integer division (which truncates
|
||||||
|
/// toward zero), this floors toward negative infinity so the remainder is
|
||||||
|
/// always nonnegative, e.g. (-1, 32) -> (-1, 31).
|
||||||
|
///
|
||||||
|
/// `divisor == 0` reports `DivisionByZero`; a negative divisor reports
|
||||||
|
/// `InvalidInput`. The signed minimum is handled without negating it, so no
|
||||||
|
/// intermediate overflows.
|
||||||
|
template <std::integral T>
|
||||||
|
[[nodiscard]] constexpr std::expected<EuclideanDivision<T>, Error>
|
||||||
|
checked_euclidean_div(T a, T divisor) noexcept
|
||||||
|
{
|
||||||
|
if (divisor == T{0}) {
|
||||||
|
return std::unexpected{Error::DivisionByZero};
|
||||||
|
}
|
||||||
|
if constexpr (std::is_signed_v<T>) {
|
||||||
|
if (divisor < T{0}) {
|
||||||
|
return std::unexpected{Error::InvalidInput};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T quotient = static_cast<T>(a / divisor);
|
||||||
|
T remainder = static_cast<T>(a % divisor);
|
||||||
|
if constexpr (std::is_signed_v<T>) {
|
||||||
|
if (remainder < T{0}) {
|
||||||
|
// Truncated division rounded toward zero: step one page down.
|
||||||
|
quotient = static_cast<T>(quotient - T{1});
|
||||||
|
remainder = static_cast<T>(remainder + divisor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return EuclideanDivision<T>{.quotient = quotient, .remainder = remainder};
|
||||||
|
}
|
||||||
|
|
||||||
template <std::integral T>
|
template <std::integral T>
|
||||||
[[nodiscard]] constexpr std::expected<T, Error>
|
[[nodiscard]] constexpr std::expected<T, Error>
|
||||||
checked_neg(T a) noexcept
|
checked_neg(T a) noexcept
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <compare>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <limits>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <span>
|
#include <span>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Random
|
namespace Void::Random
|
||||||
@@ -57,6 +62,91 @@ public:
|
|||||||
while (n--) operator()();
|
while (n--) operator()();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Versioned deterministic state ────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Algorithm identity for saved-stream metadata. The state schema is
|
||||||
|
/// versioned separately so a future algorithm change cannot silently
|
||||||
|
/// reinterpret old saves.
|
||||||
|
static constexpr std::string_view algorithm = "xoshiro256**";
|
||||||
|
static constexpr std::uint32_t state_version = 1;
|
||||||
|
|
||||||
|
/// Portable state: version plus the four words in xoshiro order s0..s3.
|
||||||
|
/// Consumers choose their own wire format (endianness, framing); this
|
||||||
|
/// struct defines only the identity and word order.
|
||||||
|
struct State {
|
||||||
|
std::uint32_t version{state_version};
|
||||||
|
std::array<std::uint64_t, 4> words{};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const State&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool operator==(const State&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class StateErrorKind : std::uint8_t {
|
||||||
|
unknown_version = 0,
|
||||||
|
/// Xoshiro's all-zero state is absorbing and therefore invalid.
|
||||||
|
invalid_state,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct StateError {
|
||||||
|
StateErrorKind kind{StateErrorKind::invalid_state};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const StateError&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] State state() const noexcept
|
||||||
|
{
|
||||||
|
return State{.version = state_version,
|
||||||
|
.words = {s_[0], s_[1], s_[2], s_[3]}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace the stream with `state` only if it is valid. On failure the
|
||||||
|
/// current stream is unchanged (the caller can keep drawing).
|
||||||
|
[[nodiscard]] std::expected<void, StateError> restore(State state) noexcept
|
||||||
|
{
|
||||||
|
if (state.version != state_version) {
|
||||||
|
return std::unexpected{StateError{StateErrorKind::unknown_version}};
|
||||||
|
}
|
||||||
|
if (state.words[0] == 0 && state.words[1] == 0 &&
|
||||||
|
state.words[2] == 0 && state.words[3] == 0) {
|
||||||
|
return std::unexpected{StateError{StateErrorKind::invalid_state}};
|
||||||
|
}
|
||||||
|
s_[0] = state.words[0];
|
||||||
|
s_[1] = state.words[1];
|
||||||
|
s_[2] = state.words[2];
|
||||||
|
s_[3] = state.words[3];
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static std::expected<Xoshiro256, StateError>
|
||||||
|
from_state(State state) noexcept
|
||||||
|
{
|
||||||
|
Xoshiro256 rng;
|
||||||
|
if (auto restored = rng.restore(state); !restored.has_value()) {
|
||||||
|
return std::unexpected{restored.error()};
|
||||||
|
}
|
||||||
|
return rng;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uniform integer in [0, bound) by rejection sampling (unbiased).
|
||||||
|
///
|
||||||
|
/// Zero-bound policy: `bound == 0` and `bound == 1` return 0 without
|
||||||
|
/// consuming any randomness, so callers need not special-case them and a
|
||||||
|
/// saved stream stays aligned.
|
||||||
|
[[nodiscard]] std::uint64_t bounded(std::uint64_t bound) noexcept
|
||||||
|
{
|
||||||
|
if (bound <= 1) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// 2^64 mod bound: values below it are rejected to remove modulo bias.
|
||||||
|
const std::uint64_t threshold = (0ULL - bound) % bound;
|
||||||
|
for (;;) {
|
||||||
|
const std::uint64_t value = operator()();
|
||||||
|
if (value >= threshold) {
|
||||||
|
return value % bound;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static constexpr std::uint64_t rotl(std::uint64_t x, int k) noexcept
|
static constexpr std::uint64_t rotl(std::uint64_t x, int k) noexcept
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Messaging
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Epoch-scoped idempotency ledger for host request dispatch.
|
||||||
|
///
|
||||||
|
/// A key is `(epoch, trusted client, request id)`. The ledger records the
|
||||||
|
/// caller-defined payload of the first admission and, once the operation
|
||||||
|
/// finishes, its caller-defined result (including a rejected outcome). An exact
|
||||||
|
/// repeat returns the recorded result instead of executing again; reusing the
|
||||||
|
/// key with a different payload, or after its epoch became obsolete, fails
|
||||||
|
/// before any side effect.
|
||||||
|
///
|
||||||
|
/// Capacity, admission and archival:
|
||||||
|
/// - Entries are never evicted within an epoch. When `capacity` is reached new
|
||||||
|
/// keys are rejected with `capacity_exceeded`; the caller can retry later or
|
||||||
|
/// raise the capacity. Completed entries keep occupying a slot so a delayed
|
||||||
|
/// retry can still be answered.
|
||||||
|
/// - Advancing the epoch clears every entry. Requests from an older (or
|
||||||
|
/// future) epoch are then rejected as `stale_epoch`, so an old request number
|
||||||
|
/// can never execute a second time after memory cleanup.
|
||||||
|
template <typename Payload,
|
||||||
|
typename Result,
|
||||||
|
typename PayloadEqual = std::equal_to<Payload>>
|
||||||
|
class RequestLedger
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
struct Key {
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
std::string client;
|
||||||
|
std::uint64_t request_id{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const Key&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const Key&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Status : std::uint8_t {
|
||||||
|
/// First admission: the caller may execute and must record a result.
|
||||||
|
admitted = 0,
|
||||||
|
/// Exact repeat of a completed request; `result` is the recorded one.
|
||||||
|
replay,
|
||||||
|
/// Exact repeat while the operation is still in flight.
|
||||||
|
in_progress,
|
||||||
|
/// Same key, different payload: reject before side effects.
|
||||||
|
payload_conflict,
|
||||||
|
/// The key's epoch is not the current epoch.
|
||||||
|
stale_epoch,
|
||||||
|
/// The ledger is full; nothing was admitted.
|
||||||
|
capacity_exceeded,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Decision {
|
||||||
|
Status status{Status::capacity_exceeded};
|
||||||
|
std::optional<Result> result{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Snapshot {
|
||||||
|
std::size_t size{0};
|
||||||
|
std::size_t capacity{0};
|
||||||
|
std::size_t in_flight{0};
|
||||||
|
std::size_t completed{0};
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit RequestLedger(std::size_t capacity = 1024,
|
||||||
|
std::uint64_t epoch = 0,
|
||||||
|
PayloadEqual equal = {})
|
||||||
|
: capacity_(capacity)
|
||||||
|
, epoch_(epoch)
|
||||||
|
, equal_(std::move(equal))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
RequestLedger(const RequestLedger&) = delete;
|
||||||
|
RequestLedger& operator=(const RequestLedger&) = delete;
|
||||||
|
|
||||||
|
/// Admit or classify `key` with `payload`.
|
||||||
|
[[nodiscard]] Decision check(const Key& key, const Payload& payload)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (key.epoch != epoch_) {
|
||||||
|
return Decision{.status = Status::stale_epoch};
|
||||||
|
}
|
||||||
|
const auto found = entries_.find(key);
|
||||||
|
if (found != entries_.end()) {
|
||||||
|
if (!equal_(found->second.payload, payload)) {
|
||||||
|
return Decision{.status = Status::payload_conflict};
|
||||||
|
}
|
||||||
|
if (found->second.result.has_value()) {
|
||||||
|
return Decision{.status = Status::replay,
|
||||||
|
.result = found->second.result};
|
||||||
|
}
|
||||||
|
return Decision{.status = Status::in_progress};
|
||||||
|
}
|
||||||
|
if (entries_.size() >= capacity_) {
|
||||||
|
return Decision{.status = Status::capacity_exceeded};
|
||||||
|
}
|
||||||
|
entries_.emplace(key, Entry{.payload = payload, .result = {}});
|
||||||
|
return Decision{.status = Status::admitted};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record the outcome for an admitted key. Returns false when the key is
|
||||||
|
/// unknown, belongs to another epoch or already has a result (results
|
||||||
|
/// are never overwritten).
|
||||||
|
[[nodiscard]] bool record(const Key& key, Result result)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (key.epoch != epoch_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto found = entries_.find(key);
|
||||||
|
if (found == entries_.end() || found->second.result.has_value()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
found->second.result = std::move(result);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Advance to `next` and clear all entries. Only a strictly newer epoch
|
||||||
|
/// is accepted; returns false otherwise.
|
||||||
|
[[nodiscard]] bool advance_epoch(std::uint64_t next)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (next <= epoch_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
epoch_ = next;
|
||||||
|
entries_.clear();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint64_t epoch() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return epoch_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Snapshot snapshot() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
Snapshot out{.size = entries_.size(),
|
||||||
|
.capacity = capacity_,
|
||||||
|
.epoch = epoch_};
|
||||||
|
for (const auto& [key, entry] : entries_) {
|
||||||
|
(void)key;
|
||||||
|
if (entry.result.has_value()) {
|
||||||
|
++out.completed;
|
||||||
|
} else {
|
||||||
|
++out.in_flight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Entry {
|
||||||
|
Payload payload;
|
||||||
|
std::optional<Result> result;
|
||||||
|
};
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::map<Key, Entry> entries_;
|
||||||
|
std::size_t capacity_{1024};
|
||||||
|
std::uint64_t epoch_{0};
|
||||||
|
PayloadEqual equal_{};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Messaging
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Script/Types.hpp>
|
||||||
|
|
||||||
|
#include <expected>
|
||||||
|
#include <functional>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Script
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Host function: receives integer arguments, returns an integer or an error
|
||||||
|
/// message. It must not commit externally visible state itself; the evaluator
|
||||||
|
/// records each call in `Result::host_calls` so the caller can commit after a
|
||||||
|
/// successful evaluation.
|
||||||
|
using HostFunction = std::function<std::expected<Integer, std::string>(
|
||||||
|
std::span<const Integer>)>;
|
||||||
|
|
||||||
|
struct Host {
|
||||||
|
std::string name;
|
||||||
|
HostFunction function;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded Lua text evaluator.
|
||||||
|
///
|
||||||
|
/// Each `evaluate` call creates a fresh, isolated Lua state, applies the
|
||||||
|
/// allocator, instruction and host-call limits, exposes the integer-keyed
|
||||||
|
/// inputs as `input[key]`, registers the host functions as globals, and runs
|
||||||
|
/// the chunk with a protected call. Only integer return values are accepted
|
||||||
|
/// and collected into an owned result. On failure the state is discarded, so
|
||||||
|
/// inputs and the caller's host state are untouched; a later valid evaluation
|
||||||
|
/// starts clean.
|
||||||
|
class LuaEvaluator
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit LuaEvaluator(Limits limits = Limits{},
|
||||||
|
std::vector<Host> hosts = {})
|
||||||
|
: limits_(limits)
|
||||||
|
, hosts_(std::move(hosts))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
|
||||||
|
|
||||||
|
[[nodiscard]] std::expected<Result, Error>
|
||||||
|
evaluate(std::string_view source,
|
||||||
|
std::span<const Input> inputs = {}) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
Limits limits_;
|
||||||
|
std::vector<Host> hosts_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Script
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Script
|
||||||
|
{
|
||||||
|
|
||||||
|
using Integer = std::int64_t;
|
||||||
|
|
||||||
|
enum class ErrorKind : std::uint8_t {
|
||||||
|
compile = 0,
|
||||||
|
runtime,
|
||||||
|
allocator_limit,
|
||||||
|
instruction_limit,
|
||||||
|
host_call_limit,
|
||||||
|
result_limit,
|
||||||
|
host_error,
|
||||||
|
invalid_input,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Error {
|
||||||
|
ErrorKind kind{ErrorKind::runtime};
|
||||||
|
std::string message;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const Error&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Limits {
|
||||||
|
/// Total bytes the VM may allocate (including the state and libraries).
|
||||||
|
std::size_t max_allocator_bytes{1ULL * 1024ULL * 1024ULL};
|
||||||
|
/// VM instructions before evaluation is aborted.
|
||||||
|
std::size_t max_instructions{100'000};
|
||||||
|
/// Host function invocations before evaluation is aborted.
|
||||||
|
std::size_t max_host_calls{1'000};
|
||||||
|
/// Maximum number of integer results collected.
|
||||||
|
std::size_t max_result_integers{1'024};
|
||||||
|
/// Maximum number of integer-keyed inputs.
|
||||||
|
std::size_t max_inputs{256};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Integer-keyed input exposed to the script as `input[key]`.
|
||||||
|
struct Input {
|
||||||
|
Integer key{0};
|
||||||
|
Integer value{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const Input&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// One host function call observed during a successful evaluation. The caller
|
||||||
|
/// may commit these effects after `evaluate` returns; the evaluator itself
|
||||||
|
/// never commits host state.
|
||||||
|
struct HostInvocation {
|
||||||
|
std::string host;
|
||||||
|
std::vector<Integer> arguments;
|
||||||
|
Integer result{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const HostInvocation&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Owned result of a successful evaluation.
|
||||||
|
struct Result {
|
||||||
|
/// Integer values returned by the chunk, in order.
|
||||||
|
std::vector<Integer> integers;
|
||||||
|
/// Host calls made by the script, in order.
|
||||||
|
std::vector<HostInvocation> host_calls;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Script
|
||||||
@@ -0,0 +1,406 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
#ifndef WIN32_LEAN_AND_MEAN
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#endif
|
||||||
|
#ifndef NOMINMAX
|
||||||
|
#define NOMINMAX
|
||||||
|
#endif
|
||||||
|
#include <mmsystem.h>
|
||||||
|
#include <windows.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Void::System
|
||||||
|
{
|
||||||
|
|
||||||
|
using PcmSample = std::int16_t;
|
||||||
|
|
||||||
|
struct PcmFormat {
|
||||||
|
std::uint32_t sample_rate{44100};
|
||||||
|
std::uint16_t channels{2};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const PcmFormat&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Owned PCM sample data. The device keeps it alive for as long as a voice
|
||||||
|
/// references it; callers may release their handle right after submission.
|
||||||
|
struct PcmBuffer {
|
||||||
|
PcmFormat format;
|
||||||
|
std::vector<PcmSample> samples;
|
||||||
|
|
||||||
|
[[nodiscard]] std::chrono::microseconds duration() const noexcept
|
||||||
|
{
|
||||||
|
const std::uint64_t frames =
|
||||||
|
format.channels == 0
|
||||||
|
? 0
|
||||||
|
: samples.size() / format.channels;
|
||||||
|
if (format.sample_rate == 0) {
|
||||||
|
return std::chrono::microseconds{0};
|
||||||
|
}
|
||||||
|
return std::chrono::microseconds{
|
||||||
|
static_cast<std::int64_t>(frames) * 1'000'000 /
|
||||||
|
format.sample_rate};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class AudioStatus : std::uint8_t {
|
||||||
|
ok = 0,
|
||||||
|
/// No output device is available; the caller can continue silently.
|
||||||
|
device_unavailable,
|
||||||
|
voice_limit,
|
||||||
|
invalid_buffer,
|
||||||
|
backend_error,
|
||||||
|
closed,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AudioError {
|
||||||
|
AudioStatus status{AudioStatus::backend_error};
|
||||||
|
std::string message;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const AudioError&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class VoiceState : std::uint8_t {
|
||||||
|
playing = 0,
|
||||||
|
stopped,
|
||||||
|
finished,
|
||||||
|
unknown,
|
||||||
|
};
|
||||||
|
|
||||||
|
using VoiceId = std::uint64_t;
|
||||||
|
|
||||||
|
struct AudioLimits {
|
||||||
|
std::size_t max_voices{8};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded PCM playback with owned samples and explicit voice lifetimes.
|
||||||
|
///
|
||||||
|
/// `play` transfers a shared handle to the device; the caller may drop its
|
||||||
|
/// handle immediately and the samples stay alive until the voice is stopped,
|
||||||
|
/// finishes or the device closes. `stop` ends a voice (including a loop),
|
||||||
|
/// `state` reports and reaps finished voices, and the destructor tears every
|
||||||
|
/// voice down. A missing device is reported as `device_unavailable` so an
|
||||||
|
/// application can continue without audio; `open_silent` provides the same
|
||||||
|
/// lifetime semantics without a device (used for tests and headless runs).
|
||||||
|
///
|
||||||
|
/// Thread-safe.
|
||||||
|
class AudioDevice
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
static std::expected<AudioDevice, AudioError>
|
||||||
|
open(AudioLimits limits = {})
|
||||||
|
{
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->limits = limits;
|
||||||
|
#ifdef _WIN32
|
||||||
|
impl->silent = false;
|
||||||
|
#else
|
||||||
|
impl->silent = true;
|
||||||
|
#endif
|
||||||
|
return AudioDevice{std::move(impl)};
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::expected<AudioDevice, AudioError>
|
||||||
|
open_silent(AudioLimits limits = {})
|
||||||
|
{
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->limits = limits;
|
||||||
|
impl->silent = true;
|
||||||
|
return AudioDevice{std::move(impl)};
|
||||||
|
}
|
||||||
|
|
||||||
|
AudioDevice(AudioDevice&&) noexcept = default;
|
||||||
|
AudioDevice& operator=(AudioDevice&&) noexcept = default;
|
||||||
|
|
||||||
|
AudioDevice(const AudioDevice&) = delete;
|
||||||
|
AudioDevice& operator=(const AudioDevice&) = delete;
|
||||||
|
|
||||||
|
~AudioDevice() { close(); }
|
||||||
|
|
||||||
|
[[nodiscard]] bool available() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{impl_->mutex};
|
||||||
|
return !impl_->closed && impl_->available;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Submit owned samples. On success the device owns a reference; on
|
||||||
|
/// failure the caller's handle is untouched.
|
||||||
|
[[nodiscard]] std::expected<VoiceId, AudioError>
|
||||||
|
play(std::shared_ptr<const PcmBuffer> buffer, bool loop = false)
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
reap(impl);
|
||||||
|
if (impl.closed) {
|
||||||
|
return std::unexpected{
|
||||||
|
AudioError{AudioStatus::closed, "audio device is closed"}};
|
||||||
|
}
|
||||||
|
if (!impl.available) {
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::device_unavailable,
|
||||||
|
"no audio output device"}};
|
||||||
|
}
|
||||||
|
if (buffer == nullptr || buffer->format.channels == 0 ||
|
||||||
|
buffer->samples.empty()) {
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::invalid_buffer, "empty PCM buffer"}};
|
||||||
|
}
|
||||||
|
if (impl.voices.size() >= impl.limits.max_voices) {
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::voice_limit, "voice limit reached"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Voice voice;
|
||||||
|
voice.id = impl.next_id++;
|
||||||
|
voice.buffer = std::move(buffer);
|
||||||
|
voice.loop = loop;
|
||||||
|
voice.state = VoiceState::playing;
|
||||||
|
voice.started = std::chrono::steady_clock::now();
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (!impl.silent) {
|
||||||
|
if (const auto error = start_win32(voice); !error.has_value()) {
|
||||||
|
return std::unexpected{error.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
const VoiceId id = voice.id;
|
||||||
|
impl.voices.emplace(id, std::move(voice));
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop a voice (including a loop) and release its samples.
|
||||||
|
bool stop(VoiceId id)
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
const auto found = impl.voices.find(id);
|
||||||
|
if (found == impl.voices.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
found->second.state = VoiceState::stopped;
|
||||||
|
release(impl, found->second);
|
||||||
|
impl.voices.erase(found);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Current state; finished voices are reaped and their samples
|
||||||
|
/// released.
|
||||||
|
[[nodiscard]] VoiceState state(VoiceId id)
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
const auto found = impl.voices.find(id);
|
||||||
|
if (found == impl.voices.end()) {
|
||||||
|
return VoiceState::unknown;
|
||||||
|
}
|
||||||
|
Voice& voice = found->second;
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (!impl.silent) {
|
||||||
|
service_win32(voice);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (voice.state == VoiceState::playing && !voice.loop &&
|
||||||
|
std::chrono::steady_clock::now() - voice.started >=
|
||||||
|
voice.buffer->duration()) {
|
||||||
|
voice.state = VoiceState::finished;
|
||||||
|
}
|
||||||
|
const VoiceState result = voice.state;
|
||||||
|
if (result == VoiceState::finished ||
|
||||||
|
result == VoiceState::stopped) {
|
||||||
|
release(impl, voice);
|
||||||
|
impl.voices.erase(found);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t active_voices()
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
reap(impl);
|
||||||
|
return impl.voices.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
void close()
|
||||||
|
{
|
||||||
|
if (impl_ == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
for (auto& [id, voice] : impl.voices) {
|
||||||
|
(void)id;
|
||||||
|
stop_backend(voice);
|
||||||
|
voice.buffer.reset();
|
||||||
|
}
|
||||||
|
impl.voices.clear();
|
||||||
|
impl.closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Voice {
|
||||||
|
VoiceId id{0};
|
||||||
|
std::shared_ptr<const PcmBuffer> buffer;
|
||||||
|
bool loop{false};
|
||||||
|
VoiceState state{VoiceState::playing};
|
||||||
|
std::chrono::steady_clock::time_point started{};
|
||||||
|
#ifdef _WIN32
|
||||||
|
HWAVEOUT wave{};
|
||||||
|
WAVEHDR header{};
|
||||||
|
WAVEFORMATEX format{};
|
||||||
|
bool prepared{false};
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Impl {
|
||||||
|
mutable std::mutex mutex;
|
||||||
|
AudioLimits limits{};
|
||||||
|
std::unordered_map<VoiceId, Voice> voices;
|
||||||
|
VoiceId next_id{1};
|
||||||
|
bool silent{true};
|
||||||
|
bool available{true};
|
||||||
|
bool closed{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit AudioDevice(std::unique_ptr<Impl> impl)
|
||||||
|
: impl_(std::move(impl))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
static void release(Impl& impl, Voice& voice)
|
||||||
|
{
|
||||||
|
(void)impl;
|
||||||
|
#ifdef _WIN32
|
||||||
|
stop_backend(voice);
|
||||||
|
#endif
|
||||||
|
voice.buffer.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reap voices that finished. Silent non-loop voices finish after
|
||||||
|
/// their duration; looping voices stay until stopped.
|
||||||
|
static void reap(Impl& impl)
|
||||||
|
{
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
for (auto iterator = impl.voices.begin();
|
||||||
|
iterator != impl.voices.end();) {
|
||||||
|
Voice& voice = iterator->second;
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (!impl.silent) {
|
||||||
|
service_win32(voice);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (voice.state == VoiceState::playing && !voice.loop &&
|
||||||
|
now - voice.started >= voice.buffer->duration()) {
|
||||||
|
voice.state = VoiceState::finished;
|
||||||
|
}
|
||||||
|
if (voice.state == VoiceState::finished ||
|
||||||
|
voice.state == VoiceState::stopped) {
|
||||||
|
release(impl, voice);
|
||||||
|
iterator = impl.voices.erase(iterator);
|
||||||
|
} else {
|
||||||
|
++iterator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
static std::expected<void, AudioError> start_win32(Voice& voice)
|
||||||
|
{
|
||||||
|
voice.format.wFormatTag = WAVE_FORMAT_PCM;
|
||||||
|
voice.format.nChannels =
|
||||||
|
static_cast<WORD>(voice.buffer->format.channels);
|
||||||
|
voice.format.nSamplesPerSec =
|
||||||
|
static_cast<DWORD>(voice.buffer->format.sample_rate);
|
||||||
|
voice.format.wBitsPerSample = 16;
|
||||||
|
voice.format.nBlockAlign =
|
||||||
|
static_cast<WORD>(voice.format.nChannels * 2);
|
||||||
|
voice.format.nAvgBytesPerSec =
|
||||||
|
voice.format.nSamplesPerSec * voice.format.nBlockAlign;
|
||||||
|
voice.format.cbSize = 0;
|
||||||
|
|
||||||
|
const MMRESULT opened = ::waveOutOpen(
|
||||||
|
&voice.wave, WAVE_MAPPER, &voice.format, 0, 0,
|
||||||
|
CALLBACK_NULL);
|
||||||
|
if (opened != MMSYSERR_NOERROR) {
|
||||||
|
voice.wave = nullptr;
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::device_unavailable,
|
||||||
|
"waveOutOpen failed"}};
|
||||||
|
}
|
||||||
|
voice.header = WAVEHDR{};
|
||||||
|
voice.header.lpData =
|
||||||
|
reinterpret_cast<LPSTR>(
|
||||||
|
const_cast<PcmSample*>(voice.buffer->samples.data()));
|
||||||
|
voice.header.dwBufferLength = static_cast<DWORD>(
|
||||||
|
voice.buffer->samples.size() * sizeof(PcmSample));
|
||||||
|
if (::waveOutPrepareHeader(voice.wave, &voice.header,
|
||||||
|
sizeof(WAVEHDR)) !=
|
||||||
|
MMSYSERR_NOERROR) {
|
||||||
|
::waveOutClose(voice.wave);
|
||||||
|
voice.wave = nullptr;
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::backend_error,
|
||||||
|
"waveOutPrepareHeader failed"}};
|
||||||
|
}
|
||||||
|
voice.prepared = true;
|
||||||
|
if (::waveOutWrite(voice.wave, &voice.header, sizeof(WAVEHDR)) !=
|
||||||
|
MMSYSERR_NOERROR) {
|
||||||
|
stop_backend(voice);
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::backend_error, "waveOutWrite failed"}};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
static void service_win32(Voice& voice)
|
||||||
|
{
|
||||||
|
if (voice.wave == nullptr ||
|
||||||
|
(voice.header.dwFlags & WHDR_DONE) == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (voice.loop) {
|
||||||
|
// Re-queue the same prepared header for another pass.
|
||||||
|
voice.header.dwFlags &= ~WHDR_DONE;
|
||||||
|
(void)::waveOutWrite(voice.wave, &voice.header,
|
||||||
|
sizeof(WAVEHDR));
|
||||||
|
} else {
|
||||||
|
voice.state = VoiceState::finished;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void stop_backend(Voice& voice)
|
||||||
|
{
|
||||||
|
if (voice.wave != nullptr) {
|
||||||
|
(void)::waveOutReset(voice.wave);
|
||||||
|
if (voice.prepared) {
|
||||||
|
(void)::waveOutUnprepareHeader(
|
||||||
|
voice.wave, &voice.header, sizeof(WAVEHDR));
|
||||||
|
voice.prepared = false;
|
||||||
|
}
|
||||||
|
(void)::waveOutClose(voice.wave);
|
||||||
|
voice.wave = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
static void stop_backend(Voice&) {}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
std::unique_ptr<Impl> impl_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::System
|
||||||
+549
-20
@@ -36,6 +36,14 @@
|
|||||||
#include <linux/fs.h>
|
#include <linux/fs.h>
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
#else
|
||||||
|
#ifndef WIN32_LEAN_AND_MEAN
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#endif
|
||||||
|
#ifndef NOMINMAX
|
||||||
|
#define NOMINMAX
|
||||||
|
#endif
|
||||||
|
#include <windows.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace Void::FileSystem
|
namespace Void::FileSystem
|
||||||
@@ -45,6 +53,38 @@ struct ReadFileOptions {
|
|||||||
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
|
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// How much `replace_file` guarantees before reporting success.
|
||||||
|
///
|
||||||
|
/// - `atomic_visibility`: publication is a single atomic directory-entry
|
||||||
|
/// replacement. A concurrent reader opens either the complete old file or the
|
||||||
|
/// complete new file, never a partial one. This survives an application
|
||||||
|
/// (process) crash: whatever rename already happened remains. It does *not*
|
||||||
|
/// promise that the new directory entry survives a power loss without a
|
||||||
|
/// subsequent `durable_sync`.
|
||||||
|
/// - `durable_sync`: additionally flushes the staged data before publication and
|
||||||
|
/// the parent directory after it. A successful return means the new contents
|
||||||
|
/// and their directory entry have reached stable storage (subject to the
|
||||||
|
/// device honoring flush requests).
|
||||||
|
///
|
||||||
|
/// Windows x64 notes:
|
||||||
|
/// - Staging uses an exclusively created (`CREATE_NEW`, share mode 0) temporary
|
||||||
|
/// file in the destination directory, so names never collide and no other
|
||||||
|
/// process can observe partial contents.
|
||||||
|
/// - Publication uses `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`. On NTFS this is
|
||||||
|
/// one atomic directory-entry replacement, so readers observe old-or-new.
|
||||||
|
/// - `durable_sync` adds `MOVEFILE_WRITE_THROUGH`, `FlushFileBuffers` on the
|
||||||
|
/// staged file, and `FlushFileBuffers` on the parent directory handle. If the
|
||||||
|
/// flush after the rename fails the result is `ReplacePhase::sync_parent`
|
||||||
|
/// with `visible_on_disk = true` and `durability_unknown = true`: the new file
|
||||||
|
/// is visible but may not survive power loss.
|
||||||
|
/// - Application crash vs power loss: a crash keeps the rename that already
|
||||||
|
/// happened (atomic_visibility is enough); power loss may lose it unless
|
||||||
|
/// durable_sync succeeded. Even durable_sync depends on the volume and its
|
||||||
|
/// filter drivers honoring flushes (NTFS does; some network/antivirus layers
|
||||||
|
/// do not).
|
||||||
|
/// - Replacing a destination that another process opened without
|
||||||
|
/// `FILE_SHARE_DELETE` fails in the rename phase and leaves the destination
|
||||||
|
/// intact.
|
||||||
enum class ReplaceDurability {
|
enum class ReplaceDurability {
|
||||||
atomic_visibility,
|
atomic_visibility,
|
||||||
durable_sync,
|
durable_sync,
|
||||||
@@ -110,7 +150,156 @@ namespace detail
|
|||||||
|
|
||||||
} // namespace detail
|
} // namespace detail
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
namespace detail
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Owning wrapper for a Win32 HANDLE (INVALID_HANDLE_VALUE is the empty state).
|
||||||
|
class OwnedHandle
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
OwnedHandle() noexcept = default;
|
||||||
|
explicit OwnedHandle(HANDLE handle) noexcept : handle_(handle) {}
|
||||||
|
~OwnedHandle() noexcept { reset(); }
|
||||||
|
|
||||||
|
OwnedHandle(const OwnedHandle&) = delete;
|
||||||
|
OwnedHandle& operator=(const OwnedHandle&) = delete;
|
||||||
|
|
||||||
|
OwnedHandle(OwnedHandle&& other) noexcept
|
||||||
|
: handle_(std::exchange(other.handle_, INVALID_HANDLE_VALUE))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
OwnedHandle& operator=(OwnedHandle&& other) noexcept
|
||||||
|
{
|
||||||
|
if (this != &other) {
|
||||||
|
reset();
|
||||||
|
handle_ = std::exchange(other.handle_, INVALID_HANDLE_VALUE);
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid() const noexcept
|
||||||
|
{
|
||||||
|
return handle_ != INVALID_HANDLE_VALUE && handle_ != nullptr;
|
||||||
|
}
|
||||||
|
[[nodiscard]] HANDLE get() const noexcept { return handle_; }
|
||||||
|
|
||||||
|
void reset(HANDLE handle = INVALID_HANDLE_VALUE) noexcept
|
||||||
|
{
|
||||||
|
const HANDLE old = std::exchange(handle_, handle);
|
||||||
|
if (old != INVALID_HANDLE_VALUE && old != nullptr) {
|
||||||
|
(void)::CloseHandle(old);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close explicitly, reporting whether CloseHandle succeeded.
|
||||||
|
[[nodiscard]] bool close() noexcept
|
||||||
|
{
|
||||||
|
const HANDLE old = std::exchange(handle_, INVALID_HANDLE_VALUE);
|
||||||
|
if (old == INVALID_HANDLE_VALUE || old == nullptr) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return ::CloseHandle(old) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
HANDLE handle_{INVALID_HANDLE_VALUE};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::string win32_message(DWORD error)
|
||||||
|
{
|
||||||
|
char* buffer = nullptr;
|
||||||
|
const DWORD length = ::FormatMessageA(
|
||||||
|
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
|
||||||
|
FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||||
|
nullptr,
|
||||||
|
error,
|
||||||
|
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||||
|
reinterpret_cast<char*>(&buffer),
|
||||||
|
0,
|
||||||
|
nullptr);
|
||||||
|
std::string message = (length != 0 && buffer != nullptr)
|
||||||
|
? std::string{buffer, length}
|
||||||
|
: std::string{"unknown error"};
|
||||||
|
if (buffer != nullptr) {
|
||||||
|
::LocalFree(buffer);
|
||||||
|
}
|
||||||
|
while (!message.empty() &&
|
||||||
|
(message.back() == '\n' || message.back() == '\r' ||
|
||||||
|
message.back() == ' ' || message.back() == '.')) {
|
||||||
|
message.pop_back();
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline Void::System::SystemErrorCode
|
||||||
|
map_win32_error(DWORD error) noexcept
|
||||||
|
{
|
||||||
|
switch (error) {
|
||||||
|
case ERROR_FILE_NOT_FOUND:
|
||||||
|
case ERROR_PATH_NOT_FOUND:
|
||||||
|
case ERROR_INVALID_DRIVE:
|
||||||
|
return Void::System::SystemErrorCode::not_found;
|
||||||
|
case ERROR_ACCESS_DENIED:
|
||||||
|
case ERROR_WRITE_PROTECT:
|
||||||
|
case ERROR_SHARING_VIOLATION:
|
||||||
|
case ERROR_LOCK_VIOLATION:
|
||||||
|
return Void::System::SystemErrorCode::permission_denied;
|
||||||
|
case ERROR_FILE_EXISTS:
|
||||||
|
case ERROR_ALREADY_EXISTS:
|
||||||
|
return Void::System::SystemErrorCode::already_exists;
|
||||||
|
case ERROR_INVALID_NAME:
|
||||||
|
case ERROR_INVALID_PARAMETER:
|
||||||
|
case ERROR_BAD_PATHNAME:
|
||||||
|
case ERROR_FILENAME_EXCED_RANGE:
|
||||||
|
return Void::System::SystemErrorCode::invalid_argument;
|
||||||
|
case ERROR_DISK_FULL:
|
||||||
|
case ERROR_HANDLE_DISK_FULL:
|
||||||
|
return Void::System::SystemErrorCode::limit_exceeded;
|
||||||
|
case ERROR_NOT_SUPPORTED:
|
||||||
|
case ERROR_CALL_NOT_IMPLEMENTED:
|
||||||
|
case ERROR_INVALID_FUNCTION:
|
||||||
|
return Void::System::SystemErrorCode::unsupported;
|
||||||
|
case ERROR_BUSY:
|
||||||
|
case ERROR_RETRY:
|
||||||
|
return Void::System::SystemErrorCode::busy;
|
||||||
|
case ERROR_OPERATION_ABORTED:
|
||||||
|
return Void::System::SystemErrorCode::cancelled;
|
||||||
|
case ERROR_TIMEOUT:
|
||||||
|
return Void::System::SystemErrorCode::timed_out;
|
||||||
|
case ERROR_NOT_ENOUGH_MEMORY:
|
||||||
|
case ERROR_OUTOFMEMORY:
|
||||||
|
return Void::System::SystemErrorCode::unavailable;
|
||||||
|
default:
|
||||||
|
return Void::System::SystemErrorCode::io_error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline Void::Result::Error make_win32_error(
|
||||||
|
Void::System::SystemErrorCode code, std::string_view what, DWORD error)
|
||||||
|
{
|
||||||
|
return Void::System::make_system_error(
|
||||||
|
code,
|
||||||
|
std::format("{} (win32={}: {})", what, error, win32_message(error)));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
#endif
|
||||||
|
|
||||||
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
|
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
|
||||||
|
///
|
||||||
|
/// The file is opened once and read through that single handle. The size is
|
||||||
|
/// checked before allocation and every chunk is checked again while reading,
|
||||||
|
/// so a file that grows after the initial size check still fails with
|
||||||
|
/// `limit_exceeded` and never returns partial contents.
|
||||||
|
///
|
||||||
|
/// Sharing: POSIX opens read-only; Windows opens with
|
||||||
|
/// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`, so another process
|
||||||
|
/// may append, rename or replace the path while a background read is pending.
|
||||||
|
/// The read continues from the already opened handle and sees one coherent
|
||||||
|
/// version of the file (the one that was opened), not a mixture with the
|
||||||
|
/// replacement. On both platforms the path is resolved once at open time.
|
||||||
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
||||||
read_file_bounded(const std::filesystem::path& path,
|
read_file_bounded(const std::filesystem::path& path,
|
||||||
ReadFileOptions options = {})
|
ReadFileOptions options = {})
|
||||||
@@ -177,11 +366,73 @@ namespace detail
|
|||||||
content.size());
|
content.size());
|
||||||
return content;
|
return content;
|
||||||
#else
|
#else
|
||||||
(void)path;
|
const HANDLE raw = ::CreateFileW(path.c_str(),
|
||||||
(void)options;
|
GENERIC_READ,
|
||||||
return std::unexpected{Void::System::make_system_error(
|
FILE_SHARE_READ | FILE_SHARE_WRITE |
|
||||||
Void::System::SystemErrorCode::unsupported,
|
FILE_SHARE_DELETE,
|
||||||
"FileSystem::read_file: unsupported platform")};
|
nullptr,
|
||||||
|
OPEN_EXISTING,
|
||||||
|
FILE_ATTRIBUTE_NORMAL,
|
||||||
|
nullptr);
|
||||||
|
if (raw == INVALID_HANDLE_VALUE) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "read_file: cannot open '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::read_file: cannot open '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
detail::OwnedHandle handle{raw};
|
||||||
|
|
||||||
|
LARGE_INTEGER size{};
|
||||||
|
if (::GetFileSizeEx(handle.get(), &size) != 0 && size.QuadPart >= 0 &&
|
||||||
|
static_cast<std::uint64_t>(size.QuadPart) > options.max_bytes) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})",
|
||||||
|
path.string(),
|
||||||
|
static_cast<std::uint64_t>(size.QuadPart),
|
||||||
|
options.max_bytes))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string content;
|
||||||
|
std::array<char, 8192> buffer{};
|
||||||
|
for (;;) {
|
||||||
|
DWORD read = 0;
|
||||||
|
if (::ReadFile(handle.get(),
|
||||||
|
buffer.data(),
|
||||||
|
static_cast<DWORD>(buffer.size()),
|
||||||
|
&read,
|
||||||
|
nullptr) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "read_file: I/O error reading '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::read_file: I/O error reading '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
if (read == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const auto count = static_cast<std::size_t>(read);
|
||||||
|
if (count > options.max_bytes - content.size()) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
std::format("FileSystem::read_file: '{}' exceeded limit ({})",
|
||||||
|
path.string(),
|
||||||
|
options.max_bytes))};
|
||||||
|
}
|
||||||
|
content.append(buffer.data(), count);
|
||||||
|
}
|
||||||
|
Void::Log::debug("FileSystem",
|
||||||
|
"read_file: '{}' ({} bytes)",
|
||||||
|
path.string(),
|
||||||
|
content.size());
|
||||||
|
return content;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,11 +484,58 @@ namespace detail
|
|||||||
}
|
}
|
||||||
return guard.close();
|
return guard.close();
|
||||||
#else
|
#else
|
||||||
(void)path;
|
const HANDLE raw = ::CreateFileW(path.c_str(),
|
||||||
(void)content;
|
GENERIC_WRITE,
|
||||||
return std::unexpected{Void::System::make_system_error(
|
FILE_SHARE_READ | FILE_SHARE_WRITE |
|
||||||
Void::System::SystemErrorCode::unsupported,
|
FILE_SHARE_DELETE,
|
||||||
"FileSystem::write_file: unsupported platform")};
|
nullptr,
|
||||||
|
CREATE_ALWAYS,
|
||||||
|
FILE_ATTRIBUTE_NORMAL,
|
||||||
|
nullptr);
|
||||||
|
if (raw == INVALID_HANDLE_VALUE) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "write_file: cannot open '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::write_file: cannot open '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
detail::OwnedHandle handle{raw};
|
||||||
|
|
||||||
|
std::size_t offset = 0;
|
||||||
|
while (offset < content.size()) {
|
||||||
|
const auto remaining = content.size() - offset;
|
||||||
|
constexpr std::size_t kMaxChunk = 0x4000'0000;
|
||||||
|
const DWORD chunk = static_cast<DWORD>(
|
||||||
|
remaining < kMaxChunk ? remaining : kMaxChunk);
|
||||||
|
DWORD written = 0;
|
||||||
|
if (::WriteFile(handle.get(),
|
||||||
|
content.data() + offset,
|
||||||
|
chunk,
|
||||||
|
&written,
|
||||||
|
nullptr) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "write_file: I/O error writing '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::write_file: I/O error writing '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
offset += written;
|
||||||
|
}
|
||||||
|
if (!handle.close()) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::write_file: close failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,16 +767,247 @@ namespace detail
|
|||||||
bytes.size());
|
bytes.size());
|
||||||
return {};
|
return {};
|
||||||
#else
|
#else
|
||||||
(void)path;
|
auto check_fault = [&](ReplacePhase phase,
|
||||||
(void)bytes;
|
bool visible,
|
||||||
(void)options;
|
bool unknown) -> std::optional<ReplaceFailure> {
|
||||||
return std::unexpected{ReplaceFailure{
|
if (options.fault_hook) {
|
||||||
Void::System::make_system_error(
|
if (const auto injected = options.fault_hook(phase)) {
|
||||||
Void::System::SystemErrorCode::unsupported,
|
return ReplaceFailure{
|
||||||
"FileSystem::replace_file: unsupported platform"),
|
Void::System::make_system_error(
|
||||||
ReplacePhase::validation,
|
unknown
|
||||||
false,
|
? Void::System::SystemErrorCode::durability_unknown
|
||||||
false}};
|
: Void::System::map_errno_to_system_code(*injected),
|
||||||
|
std::format("FileSystem::replace_file: injected fault for '{}'",
|
||||||
|
path.string()),
|
||||||
|
*injected),
|
||||||
|
phase,
|
||||||
|
visible,
|
||||||
|
unknown};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::validation, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path.empty() || !path.has_filename()) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"FileSystem::replace_file: empty path or missing filename"),
|
||||||
|
ReplacePhase::validation,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::filesystem::path parent =
|
||||||
|
path.parent_path().empty() ? std::filesystem::path{"."}
|
||||||
|
: path.parent_path();
|
||||||
|
const std::wstring target_name = path.filename().wstring();
|
||||||
|
if (target_name == L"." || target_name == L"..") {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"FileSystem::replace_file: invalid target filename"),
|
||||||
|
ReplacePhase::validation,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::create_stage, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path temp_path;
|
||||||
|
detail::OwnedHandle temp_handle;
|
||||||
|
DWORD last_err = 0;
|
||||||
|
for (int attempt = 0; attempt < 32; ++attempt) {
|
||||||
|
const auto entropy = detail::next_temp_entropy();
|
||||||
|
const std::string tail = std::format("{:016x}", entropy);
|
||||||
|
std::wstring name = L".";
|
||||||
|
name += target_name;
|
||||||
|
name += L".void_tmp_";
|
||||||
|
name.append(tail.begin(), tail.end());
|
||||||
|
temp_path = parent / name;
|
||||||
|
const HANDLE raw = ::CreateFileW(temp_path.c_str(),
|
||||||
|
GENERIC_WRITE,
|
||||||
|
0,
|
||||||
|
nullptr,
|
||||||
|
CREATE_NEW,
|
||||||
|
FILE_ATTRIBUTE_NORMAL,
|
||||||
|
nullptr);
|
||||||
|
if (raw != INVALID_HANDLE_VALUE) {
|
||||||
|
temp_handle.reset(raw);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
last_err = ::GetLastError();
|
||||||
|
if (last_err != ERROR_FILE_EXISTS && last_err != ERROR_ALREADY_EXISTS) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(last_err),
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: cannot create temp in '{}'",
|
||||||
|
parent.string()),
|
||||||
|
last_err),
|
||||||
|
ReplacePhase::create_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!temp_handle.valid()) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::already_exists,
|
||||||
|
"FileSystem::replace_file: exhausted temp names",
|
||||||
|
static_cast<int>(last_err)),
|
||||||
|
ReplacePhase::create_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cleanup_temp = true;
|
||||||
|
struct TempCleanup {
|
||||||
|
const std::filesystem::path* path{nullptr};
|
||||||
|
bool* active{nullptr};
|
||||||
|
~TempCleanup() noexcept
|
||||||
|
{
|
||||||
|
if (active != nullptr && *active && path != nullptr) {
|
||||||
|
(void)::DeleteFileW(path->c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} temp_guard{&temp_path, &cleanup_temp};
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::write_stage, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t offset = 0;
|
||||||
|
while (offset < bytes.size()) {
|
||||||
|
const auto remaining = bytes.size() - offset;
|
||||||
|
constexpr std::size_t kMaxChunk = 0x4000'0000;
|
||||||
|
const DWORD chunk = static_cast<DWORD>(
|
||||||
|
remaining < kMaxChunk ? remaining : kMaxChunk);
|
||||||
|
DWORD written = 0;
|
||||||
|
if (::WriteFile(temp_handle.get(),
|
||||||
|
bytes.data() + offset,
|
||||||
|
chunk,
|
||||||
|
&written,
|
||||||
|
nullptr) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: write failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::write_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
offset += written;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.durability == ReplaceDurability::durable_sync) {
|
||||||
|
if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
if (::FlushFileBuffers(temp_handle.get()) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
Void::System::SystemErrorCode::sync_failed,
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: stage flush failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::sync_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!temp_handle.close()) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: close failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::write_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::rename, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
DWORD move_flags = MOVEFILE_REPLACE_EXISTING;
|
||||||
|
if (options.durability == ReplaceDurability::durable_sync) {
|
||||||
|
move_flags |= MOVEFILE_WRITE_THROUGH;
|
||||||
|
}
|
||||||
|
if (::MoveFileExW(temp_path.c_str(), path.c_str(), move_flags) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::replace_file: rename failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::rename,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rename succeeded: target is now visible on disk; never delete target!
|
||||||
|
cleanup_temp = false;
|
||||||
|
|
||||||
|
if (options.durability == ReplaceDurability::durable_sync) {
|
||||||
|
if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
bool flushed = false;
|
||||||
|
DWORD err = 0;
|
||||||
|
const HANDLE dir_raw = ::CreateFileW(parent.c_str(),
|
||||||
|
GENERIC_READ,
|
||||||
|
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||||
|
nullptr,
|
||||||
|
OPEN_EXISTING,
|
||||||
|
FILE_FLAG_BACKUP_SEMANTICS,
|
||||||
|
nullptr);
|
||||||
|
if (dir_raw != INVALID_HANDLE_VALUE) {
|
||||||
|
detail::OwnedHandle dir_handle{dir_raw};
|
||||||
|
flushed = ::FlushFileBuffers(dir_handle.get()) != 0;
|
||||||
|
if (!flushed) {
|
||||||
|
err = ::GetLastError();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
err = ::GetLastError();
|
||||||
|
}
|
||||||
|
if (!flushed) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
Void::System::SystemErrorCode::durability_unknown,
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: parent dir flush failed after rename for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::sync_parent,
|
||||||
|
true,
|
||||||
|
true}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Log::debug("FileSystem",
|
||||||
|
"replace_file: '{}' committed ({} bytes)",
|
||||||
|
path.string(),
|
||||||
|
bytes.size());
|
||||||
|
return {};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <concepts>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <functional>
|
||||||
|
#include <mutex>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Testing
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Small synchronization gate for deterministic completion-order tests.
|
||||||
|
///
|
||||||
|
/// Participants call `arrive()` after a computation returned and can then
|
||||||
|
/// block in `wait_release()`. The test thread can wait for a number of
|
||||||
|
/// arrivals (`wait_for`) and release blocked participants explicitly, on
|
||||||
|
/// failure, or after a timeout. All waits are bounded.
|
||||||
|
class CompletionGate
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Clock = std::chrono::steady_clock;
|
||||||
|
|
||||||
|
CompletionGate() = default;
|
||||||
|
|
||||||
|
CompletionGate(const CompletionGate&) = delete;
|
||||||
|
CompletionGate& operator=(const CompletionGate&) = delete;
|
||||||
|
|
||||||
|
/// Record one completed invocation and wake `wait_for` waiters.
|
||||||
|
void arrive() noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
++arrivals_;
|
||||||
|
condition_.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t arrivals() const noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return arrivals_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait until at least `count` invocations arrived. Returns false on
|
||||||
|
/// timeout.
|
||||||
|
[[nodiscard]] bool wait_for(std::size_t count,
|
||||||
|
std::chrono::milliseconds timeout)
|
||||||
|
{
|
||||||
|
std::unique_lock lock{mutex_};
|
||||||
|
return condition_.wait_for(
|
||||||
|
lock, timeout, [&] { return arrivals_ >= count; });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unblock every current and future `wait_release` caller.
|
||||||
|
void release() noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
released_ = true;
|
||||||
|
condition_.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool released() const noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return released_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Block until `release()`; returns false on timeout so a failing test
|
||||||
|
/// can still finish.
|
||||||
|
[[nodiscard]] bool wait_release(std::chrono::milliseconds timeout)
|
||||||
|
{
|
||||||
|
std::unique_lock lock{mutex_};
|
||||||
|
return condition_.wait_for(lock, timeout,
|
||||||
|
[&] { return released_; });
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::condition_variable condition_;
|
||||||
|
std::size_t arrivals_{0};
|
||||||
|
bool released_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Callable adapter that runs an observer exactly once after a successful
|
||||||
|
/// invocation returns, and before the enclosing future is fulfilled.
|
||||||
|
///
|
||||||
|
/// The observer is *not* called when the callable throws; the exception is
|
||||||
|
/// forwarded unchanged. Void, value, reference and move-only results are
|
||||||
|
/// preserved. The observer itself must not throw; an exception from it
|
||||||
|
/// propagates instead of the result.
|
||||||
|
template <typename Fn, typename Observer> class ObservedCallable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
template <typename F, typename O>
|
||||||
|
ObservedCallable(F&& fn, O&& observer)
|
||||||
|
: fn_(std::forward<F>(fn))
|
||||||
|
, observer_(std::forward<O>(observer))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
requires std::invocable<Fn&, Args...>
|
||||||
|
decltype(auto) operator()(Args&&... args)
|
||||||
|
{
|
||||||
|
using Result = std::invoke_result_t<Fn&, Args...>;
|
||||||
|
if constexpr (std::is_void_v<Result>) {
|
||||||
|
std::invoke(fn_, std::forward<Args>(args)...);
|
||||||
|
std::invoke(observer_);
|
||||||
|
return;
|
||||||
|
} else if constexpr (std::is_reference_v<Result>) {
|
||||||
|
Result result =
|
||||||
|
std::invoke(fn_, std::forward<Args>(args)...);
|
||||||
|
std::invoke(observer_);
|
||||||
|
return std::forward<Result>(result);
|
||||||
|
} else {
|
||||||
|
Result result =
|
||||||
|
std::invoke(fn_, std::forward<Args>(args)...);
|
||||||
|
std::invoke(observer_);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
Fn fn_;
|
||||||
|
Observer observer_;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Fn, typename Observer>
|
||||||
|
[[nodiscard]] auto observe_completion(Fn&& fn, Observer&& observer)
|
||||||
|
{
|
||||||
|
return ObservedCallable<std::decay_t<Fn>, std::decay_t<Observer>>(
|
||||||
|
std::forward<Fn>(fn), std::forward<Observer>(observer));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Testing
|
||||||
@@ -0,0 +1,634 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/Text/Semver.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <format>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Update
|
||||||
|
{
|
||||||
|
|
||||||
|
inline constexpr std::size_t kDefaultMaxResolvedPackages = 64;
|
||||||
|
inline constexpr std::size_t kDefaultMaxResolvedEdges = 256;
|
||||||
|
inline constexpr std::size_t kDefaultMaxResolutionNodes = 100'000;
|
||||||
|
|
||||||
|
/// One dependency edge: the required package id and the accepted versions.
|
||||||
|
struct PackageDependency {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::VersionRange range;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Caller-supplied description of one installed package version.
|
||||||
|
///
|
||||||
|
/// Each entry in `capabilities` is *exclusive*: at most one resolved package
|
||||||
|
/// may provide a given capability. `content_digest` is opaque to the resolver
|
||||||
|
/// (for example `sha256:...`) but participates in the frozen identity.
|
||||||
|
struct PackageDescription {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::Version version;
|
||||||
|
std::string content_digest;
|
||||||
|
std::vector<std::string> capabilities;
|
||||||
|
std::vector<PackageDependency> dependencies;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Frozen identity of a resolved package.
|
||||||
|
///
|
||||||
|
/// Unlike `Void::Semver::Version::operator==`, equality (and ordering) here
|
||||||
|
/// includes SemVer build metadata and the content digest, so a rebuild that
|
||||||
|
/// only changes `+metadata` or the digest is never mistaken for the same
|
||||||
|
/// package even though its SemVer precedence is equal.
|
||||||
|
struct PackageIdentity {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::Version version;
|
||||||
|
std::string content_digest;
|
||||||
|
|
||||||
|
[[nodiscard]] std::strong_ordering
|
||||||
|
operator<=>(const PackageIdentity& other) const noexcept
|
||||||
|
{
|
||||||
|
if (const auto comparison = id <=> other.id; comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
// Precedence first, then build metadata, then digest: a total order.
|
||||||
|
if (const auto comparison = version <=> other.version;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
if (const auto comparison = version.build <=> other.version.build;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
return content_digest <=> other.content_digest;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const PackageIdentity& other) const noexcept
|
||||||
|
{
|
||||||
|
return (*this <=> other) == 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ResolvedPackage {
|
||||||
|
PackageIdentity identity;
|
||||||
|
std::vector<std::string> capabilities;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Resolution {
|
||||||
|
/// Sorted by frozen identity; capabilities are sorted and deduplicated.
|
||||||
|
std::vector<ResolvedPackage> packages;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ResolutionErrorKind : std::uint8_t {
|
||||||
|
invalid_request = 0,
|
||||||
|
missing_dependency,
|
||||||
|
incompatible_version,
|
||||||
|
cyclic_dependency,
|
||||||
|
ambiguous_package,
|
||||||
|
exclusive_capability_conflict,
|
||||||
|
limit_exceeded,
|
||||||
|
search_exhausted,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Actionable failure. `package` names the input package (or requested id) and
|
||||||
|
/// `field` the exact field, e.g. `dependencies[1].range`.
|
||||||
|
struct ResolutionDiagnostic {
|
||||||
|
ResolutionErrorKind kind{ResolutionErrorKind::invalid_request};
|
||||||
|
std::string package;
|
||||||
|
std::string field;
|
||||||
|
std::string related;
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ResolutionLimits {
|
||||||
|
std::size_t max_packages{kDefaultMaxResolvedPackages};
|
||||||
|
std::size_t max_edges{kDefaultMaxResolvedEdges};
|
||||||
|
std::size_t max_search_nodes{kDefaultMaxResolutionNodes};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ResolutionRequest {
|
||||||
|
std::span<const PackageDescription> installed;
|
||||||
|
/// Root package ids; each is resolved as `*`.
|
||||||
|
std::span<const std::string> selected;
|
||||||
|
ResolutionLimits limits{};
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace Detail
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Requirement {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::VersionRange range;
|
||||||
|
std::string requester;
|
||||||
|
std::string field;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator<(const Requirement& other) const noexcept
|
||||||
|
{
|
||||||
|
if (const auto comparison = id <=> other.id; comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison = requester <=> other.requester;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
return field < other.field;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SearchContext {
|
||||||
|
const std::map<std::string, std::vector<PackageDescription>>& available;
|
||||||
|
ResolutionLimits limits;
|
||||||
|
std::size_t nodes{0};
|
||||||
|
bool node_limit_hit{false};
|
||||||
|
std::optional<ResolutionDiagnostic> best;
|
||||||
|
std::size_t best_depth{0};
|
||||||
|
|
||||||
|
void record(ResolutionDiagnostic diagnostic, std::size_t depth)
|
||||||
|
{
|
||||||
|
const bool better = !best.has_value() || depth > best_depth ||
|
||||||
|
(depth == best_depth && diagnose_less(diagnostic, *best));
|
||||||
|
if (better) {
|
||||||
|
best = std::move(diagnostic);
|
||||||
|
best_depth = depth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool diagnose_less(const ResolutionDiagnostic& lhs,
|
||||||
|
const ResolutionDiagnostic& rhs) noexcept
|
||||||
|
{
|
||||||
|
if (const auto comparison =
|
||||||
|
static_cast<std::uint8_t>(lhs.kind) <=>
|
||||||
|
static_cast<std::uint8_t>(rhs.kind);
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison = lhs.package <=> rhs.package;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison = lhs.field <=> rhs.field; comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
return lhs.related < rhs.related;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
using Assignment = std::map<std::string, std::size_t>;
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::optional<ResolutionDiagnostic>
|
||||||
|
check_capabilities(const Assignment& assignment,
|
||||||
|
const SearchContext& context)
|
||||||
|
{
|
||||||
|
std::map<std::string, std::vector<std::string>> providers;
|
||||||
|
for (const auto& [id, index] : assignment) {
|
||||||
|
const auto& package = context.available.at(id)[index];
|
||||||
|
std::vector<std::string> capabilities = package.capabilities;
|
||||||
|
std::sort(capabilities.begin(), capabilities.end());
|
||||||
|
capabilities.erase(
|
||||||
|
std::unique(capabilities.begin(), capabilities.end()),
|
||||||
|
capabilities.end());
|
||||||
|
for (const auto& capability : capabilities) {
|
||||||
|
providers[capability].push_back(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& [capability, owners] : providers) {
|
||||||
|
if (owners.size() > 1) {
|
||||||
|
return ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::exclusive_capability_conflict,
|
||||||
|
.package = owners[0],
|
||||||
|
.field = "capabilities",
|
||||||
|
.related = owners[1],
|
||||||
|
.message = std::format(
|
||||||
|
"exclusive capability '{}' is provided by both '{}' and '{}'",
|
||||||
|
capability,
|
||||||
|
owners[0],
|
||||||
|
owners[1])};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::optional<ResolutionDiagnostic>
|
||||||
|
check_cycle(const Assignment& assignment, const SearchContext& context)
|
||||||
|
{
|
||||||
|
std::map<std::string, int> color; // 0 unseen, 1 on stack, 2 done
|
||||||
|
std::vector<std::string> stack;
|
||||||
|
|
||||||
|
const std::function<std::optional<ResolutionDiagnostic>(
|
||||||
|
const std::string&)>
|
||||||
|
visit = [&](const std::string& id)
|
||||||
|
-> std::optional<ResolutionDiagnostic> {
|
||||||
|
color[id] = 1;
|
||||||
|
stack.push_back(id);
|
||||||
|
const auto& package =
|
||||||
|
context.available.at(id)[assignment.at(id)];
|
||||||
|
std::vector<std::string> dependencies;
|
||||||
|
for (const auto& dependency : package.dependencies) {
|
||||||
|
if (assignment.contains(dependency.id)) {
|
||||||
|
dependencies.push_back(dependency.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::sort(dependencies.begin(), dependencies.end());
|
||||||
|
dependencies.erase(std::unique(dependencies.begin(),
|
||||||
|
dependencies.end()),
|
||||||
|
dependencies.end());
|
||||||
|
for (const auto& dependency : dependencies) {
|
||||||
|
if (color[dependency] == 1) {
|
||||||
|
std::string path;
|
||||||
|
const auto begin =
|
||||||
|
std::find(stack.begin(), stack.end(), dependency);
|
||||||
|
for (auto it = begin; it != stack.end(); ++it) {
|
||||||
|
path += *it;
|
||||||
|
path += " -> ";
|
||||||
|
}
|
||||||
|
path += dependency;
|
||||||
|
return ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::cyclic_dependency,
|
||||||
|
.package = dependency,
|
||||||
|
.field = "dependencies",
|
||||||
|
.related = path,
|
||||||
|
.message =
|
||||||
|
std::format("cyclic dependency detected: {}", path)};
|
||||||
|
}
|
||||||
|
if (color[dependency] == 0) {
|
||||||
|
if (auto diagnostic = visit(dependency)) {
|
||||||
|
return diagnostic;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stack.pop_back();
|
||||||
|
color[id] = 2;
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const auto& [id, index] : assignment) {
|
||||||
|
(void)index;
|
||||||
|
if (color[id] == 0) {
|
||||||
|
if (auto diagnostic = visit(id)) {
|
||||||
|
return diagnostic;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline bool
|
||||||
|
solve(const Assignment& assignment,
|
||||||
|
std::vector<Requirement> pending,
|
||||||
|
SearchContext& context,
|
||||||
|
Assignment& solution)
|
||||||
|
{
|
||||||
|
if (context.node_limit_hit) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (++context.nodes > context.limits.max_search_nodes) {
|
||||||
|
context.node_limit_hit = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (assignment.size() > context.limits.max_packages) {
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::limit_exceeded,
|
||||||
|
.field = "limits.max_packages",
|
||||||
|
.message = std::format(
|
||||||
|
"resolved package count exceeds the limit of {}",
|
||||||
|
context.limits.max_packages)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t edges = 0;
|
||||||
|
for (const auto& [id, index] : assignment) {
|
||||||
|
edges += context.available.at(id)[index].dependencies.size();
|
||||||
|
}
|
||||||
|
if (edges > context.limits.max_edges) {
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::limit_exceeded,
|
||||||
|
.field = "limits.max_edges",
|
||||||
|
.message = std::format(
|
||||||
|
"resolved dependency edge count exceeds the limit of {}",
|
||||||
|
context.limits.max_edges)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pending.empty()) {
|
||||||
|
if (auto diagnostic = check_capabilities(assignment, context)) {
|
||||||
|
context.record(std::move(*diagnostic), assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (auto diagnostic = check_cycle(assignment, context)) {
|
||||||
|
context.record(std::move(*diagnostic), assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
solution = assignment;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto next = std::min_element(pending.begin(), pending.end());
|
||||||
|
const Requirement requirement = *next;
|
||||||
|
pending.erase(next);
|
||||||
|
|
||||||
|
const auto found = context.available.find(requirement.id);
|
||||||
|
if (found == context.available.end()) {
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::missing_dependency,
|
||||||
|
.package = requirement.requester.empty()
|
||||||
|
? requirement.id
|
||||||
|
: requirement.requester,
|
||||||
|
.field = requirement.field,
|
||||||
|
.related = requirement.id,
|
||||||
|
.message = std::format(
|
||||||
|
"required package '{}' is not installed", requirement.id)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto existing = assignment.find(requirement.id);
|
||||||
|
existing != assignment.end()) {
|
||||||
|
const auto& package = found->second[existing->second];
|
||||||
|
if (requirement.range.contains(package.version)) {
|
||||||
|
return solve(assignment, std::move(pending), context, solution);
|
||||||
|
}
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::incompatible_version,
|
||||||
|
.package = requirement.requester.empty()
|
||||||
|
? requirement.id
|
||||||
|
: requirement.requester,
|
||||||
|
.field = requirement.field,
|
||||||
|
.related = requirement.id,
|
||||||
|
.message = std::format(
|
||||||
|
"selected '{}' version {} does not satisfy the requested range",
|
||||||
|
requirement.id,
|
||||||
|
package.version.to_string())},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool any_candidate = false;
|
||||||
|
for (std::size_t index = 0; index < found->second.size(); ++index) {
|
||||||
|
const auto& package = found->second[index];
|
||||||
|
if (!requirement.range.contains(package.version)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
any_candidate = true;
|
||||||
|
Assignment next_assignment = assignment;
|
||||||
|
next_assignment.emplace(requirement.id, index);
|
||||||
|
std::vector<Requirement> next_pending = pending;
|
||||||
|
for (std::size_t dependency_index = 0;
|
||||||
|
dependency_index < package.dependencies.size();
|
||||||
|
++dependency_index) {
|
||||||
|
const auto& dependency = package.dependencies[dependency_index];
|
||||||
|
next_pending.push_back(Requirement{
|
||||||
|
.id = dependency.id,
|
||||||
|
.range = dependency.range,
|
||||||
|
.requester = package.id,
|
||||||
|
.field = std::format("dependencies[{}].range",
|
||||||
|
dependency_index)});
|
||||||
|
}
|
||||||
|
if (solve(next_assignment,
|
||||||
|
std::move(next_pending),
|
||||||
|
context,
|
||||||
|
solution)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (context.node_limit_hit) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::incompatible_version,
|
||||||
|
.package = requirement.requester.empty() ? requirement.id
|
||||||
|
: requirement.requester,
|
||||||
|
.field = requirement.field,
|
||||||
|
.related = requirement.id,
|
||||||
|
.message = any_candidate
|
||||||
|
? std::format(
|
||||||
|
"no candidate for '{}' is consistent with the rest of the dependency set",
|
||||||
|
requirement.id)
|
||||||
|
: std::format(
|
||||||
|
"no installed version of '{}' satisfies the requested range",
|
||||||
|
requirement.id)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
|
/// Resolve `request.selected` and their transitive dependencies into an exact,
|
||||||
|
/// deterministic package set.
|
||||||
|
///
|
||||||
|
/// The result is invariant under permutation of `installed` and `selected`.
|
||||||
|
/// Candidates are tried in descending SemVer precedence (ties broken by build
|
||||||
|
/// metadata and digest) and requirements are processed in a canonical order.
|
||||||
|
/// Caller-supplied content digests and versions are retained verbatim; no
|
||||||
|
/// game-specific schema is assumed.
|
||||||
|
[[nodiscard]] inline Void::Result::Result<Resolution, ResolutionDiagnostic>
|
||||||
|
resolve_packages(const ResolutionRequest& request)
|
||||||
|
{
|
||||||
|
using namespace Detail;
|
||||||
|
|
||||||
|
if (request.limits.max_packages == 0 ||
|
||||||
|
request.limits.max_edges == 0 ||
|
||||||
|
request.limits.max_search_nodes == 0) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = "limits",
|
||||||
|
.message = "resolution limits must be non-zero"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deterministic canonical input order: everything downstream is
|
||||||
|
// permutation-invariant.
|
||||||
|
std::vector<PackageDescription> installed{request.installed.begin(),
|
||||||
|
request.installed.end()};
|
||||||
|
std::sort(installed.begin(),
|
||||||
|
installed.end(),
|
||||||
|
[](const PackageDescription& lhs, const PackageDescription& rhs) {
|
||||||
|
const PackageIdentity left{lhs.id, lhs.version,
|
||||||
|
lhs.content_digest};
|
||||||
|
const PackageIdentity right{rhs.id, rhs.version,
|
||||||
|
rhs.content_digest};
|
||||||
|
return left < right;
|
||||||
|
});
|
||||||
|
|
||||||
|
std::map<std::string, std::vector<PackageDescription>> available;
|
||||||
|
for (const auto& package : installed) {
|
||||||
|
if (package.id.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = "id",
|
||||||
|
.message = "package id must not be empty"}};
|
||||||
|
}
|
||||||
|
if (package.content_digest.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.package = package.id,
|
||||||
|
.field = "content_digest",
|
||||||
|
.message = "package content digest must not be empty"}};
|
||||||
|
}
|
||||||
|
for (std::size_t index = 0; index < package.capabilities.size();
|
||||||
|
++index) {
|
||||||
|
if (package.capabilities[index].empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.package = package.id,
|
||||||
|
.field = std::format("capabilities[{}]", index),
|
||||||
|
.message = "capability name must not be empty"}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (std::size_t index = 0; index < package.dependencies.size();
|
||||||
|
++index) {
|
||||||
|
if (package.dependencies[index].id.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.package = package.id,
|
||||||
|
.field =
|
||||||
|
std::format("dependencies[{}].id", index),
|
||||||
|
.message = "dependency id must not be empty"}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
available[package.id].push_back(package);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject ambiguous inputs: same id and equal SemVer precedence but a
|
||||||
|
// different frozen identity (build metadata or digest).
|
||||||
|
for (auto& [id, candidates] : available) {
|
||||||
|
std::sort(candidates.begin(),
|
||||||
|
candidates.end(),
|
||||||
|
[](const PackageDescription& lhs,
|
||||||
|
const PackageDescription& rhs) {
|
||||||
|
if (const auto comparison = rhs.version <=> lhs.version;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison =
|
||||||
|
rhs.version.build <=> lhs.version.build;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
return rhs.content_digest < lhs.content_digest;
|
||||||
|
});
|
||||||
|
for (std::size_t index = 1; index < candidates.size(); ++index) {
|
||||||
|
const auto& previous = candidates[index - 1];
|
||||||
|
const auto& current = candidates[index];
|
||||||
|
if ((previous.version <=> current.version) == 0 &&
|
||||||
|
!(PackageIdentity{previous.id, previous.version,
|
||||||
|
previous.content_digest} ==
|
||||||
|
PackageIdentity{current.id, current.version,
|
||||||
|
current.content_digest})) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::ambiguous_package,
|
||||||
|
.package = id,
|
||||||
|
.field = "version",
|
||||||
|
.related = current.content_digest,
|
||||||
|
.message = std::format(
|
||||||
|
"ambiguous installed '{}': {} and {} have equal SemVer precedence but different build metadata or digest",
|
||||||
|
id,
|
||||||
|
previous.version.to_string(),
|
||||||
|
current.version.to_string())}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Identical frozen identities are the same package: keep one.
|
||||||
|
candidates.erase(
|
||||||
|
std::unique(candidates.begin(),
|
||||||
|
candidates.end(),
|
||||||
|
[](const PackageDescription& lhs,
|
||||||
|
const PackageDescription& rhs) {
|
||||||
|
return PackageIdentity{
|
||||||
|
lhs.id, lhs.version,
|
||||||
|
lhs.content_digest} ==
|
||||||
|
PackageIdentity{
|
||||||
|
rhs.id, rhs.version,
|
||||||
|
rhs.content_digest};
|
||||||
|
}),
|
||||||
|
candidates.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto any_range = Void::Semver::VersionRange::parse("*");
|
||||||
|
if (!any_range.has_value()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = "range",
|
||||||
|
.message = "the always-matching range could not be constructed"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<Requirement> pending;
|
||||||
|
std::set<std::string> roots;
|
||||||
|
for (std::size_t index = 0; index < request.selected.size(); ++index) {
|
||||||
|
const auto& id = request.selected[index];
|
||||||
|
if (id.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = std::format("selected[{}]", index),
|
||||||
|
.message = "selected package id must not be empty"}};
|
||||||
|
}
|
||||||
|
if (!roots.insert(id).second) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
pending.push_back(Requirement{
|
||||||
|
.id = id,
|
||||||
|
.range = *any_range,
|
||||||
|
.requester = {},
|
||||||
|
.field = std::format("selected[{}]", index)});
|
||||||
|
}
|
||||||
|
|
||||||
|
SearchContext context{available, request.limits};
|
||||||
|
Assignment solution;
|
||||||
|
if (!solve(Assignment{}, std::move(pending), context, solution)) {
|
||||||
|
if (context.best.has_value()) {
|
||||||
|
return std::unexpected{std::move(*context.best)};
|
||||||
|
}
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = context.node_limit_hit
|
||||||
|
? ResolutionErrorKind::search_exhausted
|
||||||
|
: ResolutionErrorKind::incompatible_version,
|
||||||
|
.field = "limits.max_search_nodes",
|
||||||
|
.message = "resolution search did not produce a package set"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Resolution resolution;
|
||||||
|
resolution.packages.reserve(solution.size());
|
||||||
|
for (const auto& [id, index] : solution) {
|
||||||
|
const auto& package = available.at(id)[index];
|
||||||
|
std::vector<std::string> capabilities = package.capabilities;
|
||||||
|
std::sort(capabilities.begin(), capabilities.end());
|
||||||
|
capabilities.erase(
|
||||||
|
std::unique(capabilities.begin(), capabilities.end()),
|
||||||
|
capabilities.end());
|
||||||
|
resolution.packages.push_back(ResolvedPackage{
|
||||||
|
.identity = PackageIdentity{package.id,
|
||||||
|
package.version,
|
||||||
|
package.content_digest},
|
||||||
|
.capabilities = std::move(capabilities)});
|
||||||
|
}
|
||||||
|
return resolution;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience: build a dependency from an id and a SemVer range expression.
|
||||||
|
[[nodiscard]] inline std::optional<PackageDependency>
|
||||||
|
make_package_dependency(std::string id, std::string_view range)
|
||||||
|
{
|
||||||
|
auto parsed = Void::Semver::VersionRange::parse(range);
|
||||||
|
if (!parsed.has_value()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return PackageDependency{.id = std::move(id), .range = std::move(*parsed)};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Update
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
#include <Void/Script/Lua.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include <lauxlib.h>
|
||||||
|
#include <lua.h>
|
||||||
|
#include <lualib.h>
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace Void::Script
|
||||||
|
{
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Context {
|
||||||
|
const Limits* limits{nullptr};
|
||||||
|
const std::vector<Host>* hosts{nullptr};
|
||||||
|
std::size_t used_bytes{0};
|
||||||
|
std::size_t executed{0};
|
||||||
|
std::size_t hook_step{1};
|
||||||
|
std::size_t host_calls{0};
|
||||||
|
bool allocator_limit_hit{false};
|
||||||
|
bool instruction_limit_hit{false};
|
||||||
|
bool host_call_limit_hit{false};
|
||||||
|
std::string host_error;
|
||||||
|
std::vector<HostInvocation> invocations;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Context* context_of(lua_State* state)
|
||||||
|
{
|
||||||
|
return *static_cast<Context**>(lua_getextraspace(state));
|
||||||
|
}
|
||||||
|
|
||||||
|
void* limited_alloc(void* user, void* pointer, std::size_t old_size,
|
||||||
|
std::size_t new_size)
|
||||||
|
{
|
||||||
|
auto* context = static_cast<Context*>(user);
|
||||||
|
if (new_size == 0) {
|
||||||
|
if (pointer != nullptr) {
|
||||||
|
context->used_bytes -= old_size;
|
||||||
|
std::free(pointer);
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
const std::size_t current = pointer != nullptr ? old_size : 0;
|
||||||
|
if (new_size > current &&
|
||||||
|
new_size - current >
|
||||||
|
context->limits->max_allocator_bytes - context->used_bytes) {
|
||||||
|
context->allocator_limit_hit = true;
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
void* result = std::realloc(pointer, new_size);
|
||||||
|
if (result != nullptr) {
|
||||||
|
context->used_bytes = context->used_bytes - current + new_size;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void instruction_hook(lua_State* state, lua_Debug*)
|
||||||
|
{
|
||||||
|
Context* context = context_of(state);
|
||||||
|
context->executed += context->hook_step;
|
||||||
|
if (context->executed >= context->limits->max_instructions) {
|
||||||
|
context->instruction_limit_hit = true;
|
||||||
|
luaL_error(state, "instruction limit exceeded");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int host_trampoline(lua_State* state)
|
||||||
|
{
|
||||||
|
Context* context = context_of(state);
|
||||||
|
const int argument_count = lua_gettop(state);
|
||||||
|
std::vector<Integer> arguments;
|
||||||
|
arguments.reserve(static_cast<std::size_t>(argument_count));
|
||||||
|
for (int index = 1; index <= argument_count; ++index) {
|
||||||
|
int is_integer = 0;
|
||||||
|
const lua_Integer value =
|
||||||
|
lua_tointegerx(state, index, &is_integer);
|
||||||
|
if (is_integer == 0) {
|
||||||
|
return luaL_error(state, "host arguments must be integers");
|
||||||
|
}
|
||||||
|
arguments.push_back(static_cast<Integer>(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto host_index = static_cast<std::size_t>(
|
||||||
|
lua_tointeger(state, lua_upvalueindex(1)));
|
||||||
|
const Host& host = (*context->hosts)[host_index];
|
||||||
|
if (context->host_calls >= context->limits->max_host_calls) {
|
||||||
|
context->host_call_limit_hit = true;
|
||||||
|
return luaL_error(state, "host call limit exceeded");
|
||||||
|
}
|
||||||
|
++context->host_calls;
|
||||||
|
|
||||||
|
auto result = host.function(arguments);
|
||||||
|
if (!result.has_value()) {
|
||||||
|
context->host_error = result.error();
|
||||||
|
return luaL_error(state, "host '%s' failed: %s",
|
||||||
|
host.name.c_str(), result.error().c_str());
|
||||||
|
}
|
||||||
|
context->invocations.push_back(
|
||||||
|
HostInvocation{.host = host.name,
|
||||||
|
.arguments = std::move(arguments),
|
||||||
|
.result = *result});
|
||||||
|
lua_pushinteger(state, static_cast<lua_Integer>(*result));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string last_message(lua_State* state,
|
||||||
|
std::string_view fallback)
|
||||||
|
{
|
||||||
|
const char* message = lua_tostring(state, -1);
|
||||||
|
return message != nullptr ? std::string{message} : std::string{fallback};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::expected<Result, Error>
|
||||||
|
LuaEvaluator::evaluate(std::string_view source,
|
||||||
|
std::span<const Input> inputs) const
|
||||||
|
{
|
||||||
|
if (inputs.size() > limits_.max_inputs) {
|
||||||
|
return std::unexpected{Error{.kind = ErrorKind::invalid_input,
|
||||||
|
.message = "too many inputs"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Context context;
|
||||||
|
context.limits = &limits_;
|
||||||
|
context.hosts = &hosts_;
|
||||||
|
|
||||||
|
lua_State* state = lua_newstate(limited_alloc, &context);
|
||||||
|
if (state == nullptr) {
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::allocator_limit,
|
||||||
|
.message = "cannot create Lua state"}};
|
||||||
|
}
|
||||||
|
*static_cast<Context**>(lua_getextraspace(state)) = &context;
|
||||||
|
|
||||||
|
struct Library {
|
||||||
|
const char* name;
|
||||||
|
lua_CFunction open;
|
||||||
|
};
|
||||||
|
const Library libraries[] = {
|
||||||
|
{LUA_GNAME, luaopen_base},
|
||||||
|
{LUA_TABLIBNAME, luaopen_table},
|
||||||
|
{LUA_STRLIBNAME, luaopen_string},
|
||||||
|
{LUA_MATHLIBNAME, luaopen_math},
|
||||||
|
{LUA_COLIBNAME, luaopen_coroutine},
|
||||||
|
};
|
||||||
|
for (const auto& library : libraries) {
|
||||||
|
luaL_requiref(state, library.name, library.open, 1);
|
||||||
|
lua_pop(state, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
lua_createtable(state, 0, static_cast<int>(inputs.size()));
|
||||||
|
for (const auto& input : inputs) {
|
||||||
|
lua_pushinteger(state, static_cast<lua_Integer>(input.value));
|
||||||
|
lua_seti(state, -2, static_cast<lua_Integer>(input.key));
|
||||||
|
}
|
||||||
|
lua_setglobal(state, "input");
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < hosts_.size(); ++index) {
|
||||||
|
lua_pushinteger(state, static_cast<lua_Integer>(index));
|
||||||
|
lua_pushcclosure(state, host_trampoline, 1);
|
||||||
|
lua_setglobal(state, hosts_[index].name.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
context.hook_step =
|
||||||
|
std::clamp<std::size_t>(limits_.max_instructions, 1, 1000);
|
||||||
|
lua_sethook(state, instruction_hook, LUA_MASKCOUNT,
|
||||||
|
static_cast<int>(context.hook_step));
|
||||||
|
|
||||||
|
if (luaL_loadbufferx(state, source.data(), source.size(), "chunk", "t") !=
|
||||||
|
LUA_OK) {
|
||||||
|
std::string message = last_message(state, "compile error");
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::compile, .message = std::move(message)}};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK) {
|
||||||
|
std::string message = last_message(state, "runtime error");
|
||||||
|
ErrorKind kind = ErrorKind::runtime;
|
||||||
|
if (context.allocator_limit_hit) {
|
||||||
|
kind = ErrorKind::allocator_limit;
|
||||||
|
} else if (context.instruction_limit_hit) {
|
||||||
|
kind = ErrorKind::instruction_limit;
|
||||||
|
} else if (context.host_call_limit_hit) {
|
||||||
|
kind = ErrorKind::host_call_limit;
|
||||||
|
} else if (!context.host_error.empty()) {
|
||||||
|
kind = ErrorKind::host_error;
|
||||||
|
}
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = kind, .message = std::move(message)}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Result result;
|
||||||
|
const int result_count = lua_gettop(state);
|
||||||
|
for (int index = 1; index <= result_count; ++index) {
|
||||||
|
int is_integer = 0;
|
||||||
|
const lua_Integer value =
|
||||||
|
lua_tointegerx(state, index, &is_integer);
|
||||||
|
if (is_integer == 0) {
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::runtime,
|
||||||
|
.message = "script results must be integers"}};
|
||||||
|
}
|
||||||
|
if (result.integers.size() >= limits_.max_result_integers) {
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::result_limit,
|
||||||
|
.message = "result limit exceeded"}};
|
||||||
|
}
|
||||||
|
result.integers.push_back(static_cast<Integer>(value));
|
||||||
|
}
|
||||||
|
result.host_calls = std::move(context.invocations);
|
||||||
|
lua_close(state);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Script
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
void_add_module(Script
|
||||||
|
EXTERNAL_DEPS Lua::Lua
|
||||||
|
)
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
#include <Void/Algorithms/GridRay.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <set>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Algorithms::GridAxis;
|
||||||
|
using Void::Algorithms::GridCell;
|
||||||
|
using Void::Algorithms::GridFace;
|
||||||
|
using Void::Algorithms::GridRayIterator;
|
||||||
|
using Void::Algorithms::GridRayOptions;
|
||||||
|
using Void::Algorithms::GridRayStatus;
|
||||||
|
using Void::Algorithms::GridRayVisit;
|
||||||
|
using Void::Math::Vec3d;
|
||||||
|
|
||||||
|
[[nodiscard]] std::vector<GridRayVisit> take(GridRayIterator& iterator,
|
||||||
|
std::size_t count)
|
||||||
|
{
|
||||||
|
std::vector<GridRayVisit> visits;
|
||||||
|
for (std::size_t index = 0; index < count; ++index) {
|
||||||
|
auto visit = iterator.next();
|
||||||
|
if (!visit.has_value()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
visits.push_back(*visit);
|
||||||
|
}
|
||||||
|
return visits;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] GridCell cell(std::int64_t x, std::int64_t y, std::int64_t z)
|
||||||
|
{
|
||||||
|
return GridCell{.x = x, .y = y, .z = z};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_forward_corner_tie_order()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{31.5, 31.5, 31.5}, Vec3d{1, 1, 1},
|
||||||
|
GridRayOptions{.max_steps = 10}};
|
||||||
|
const auto visits = take(iterator, 5);
|
||||||
|
Void::Testing::require(visits.size() == 5);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(31, 31, 31));
|
||||||
|
Void::Testing::expect(visits[0].face == GridFace{});
|
||||||
|
Void::Testing::expect_eq(visits[0].t, 0.0);
|
||||||
|
|
||||||
|
// Exact corner tie: x first, then y, then z.
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(32, 31, 31));
|
||||||
|
Void::Testing::expect(visits[1].face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(visits[1].face.sign, 1);
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 0.5);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[2].cell == cell(32, 32, 31));
|
||||||
|
Void::Testing::expect(visits[2].face.axis == GridAxis::y);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[3].cell == cell(32, 32, 32));
|
||||||
|
Void::Testing::expect(visits[3].face.axis == GridAxis::z);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[4].cell == cell(33, 32, 32));
|
||||||
|
Void::Testing::expect(visits[4].face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(visits[4].t, 1.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_reverse_corner()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{32.5, 32.5, 32.5}, Vec3d{-1, -1, -1},
|
||||||
|
GridRayOptions{.max_steps = 10}};
|
||||||
|
const auto visits = take(iterator, 4);
|
||||||
|
Void::Testing::require(visits.size() == 4);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(32, 32, 32));
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(31, 32, 32));
|
||||||
|
Void::Testing::expect(visits[1].face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(visits[1].face.sign, -1);
|
||||||
|
Void::Testing::expect(visits[2].cell == cell(31, 31, 32));
|
||||||
|
Void::Testing::expect(visits[3].cell == cell(31, 31, 31));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_negative_origin()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{-0.5, -0.5, -0.5}, Vec3d{-1, -1, -1},
|
||||||
|
GridRayOptions{.max_steps = 10}};
|
||||||
|
const auto visits = take(iterator, 4);
|
||||||
|
Void::Testing::require(visits.size() == 4);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(-1, -1, -1));
|
||||||
|
Void::Testing::expect(visits[3].cell == cell(-2, -2, -2));
|
||||||
|
Void::Testing::expect_eq(visits[3].t, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_axis_parallel()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 4}};
|
||||||
|
const auto visits = take(iterator, 3);
|
||||||
|
Void::Testing::require(visits.size() == 3);
|
||||||
|
for (std::size_t index = 0; index < visits.size(); ++index) {
|
||||||
|
Void::Testing::expect(visits[index].cell ==
|
||||||
|
cell(static_cast<std::int64_t>(index), 0, 0));
|
||||||
|
Void::Testing::expect(visits[index].cell.y == 0);
|
||||||
|
Void::Testing::expect(visits[index].cell.z == 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_start_on_boundary()
|
||||||
|
{
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{32.0, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 2}};
|
||||||
|
const auto visits = take(iterator, 2);
|
||||||
|
Void::Testing::require(visits.size() == 2);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(32, 0, 0));
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(33, 0, 0));
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 1.0);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
// Exactly on the boundary moving negative: the point is assigned to
|
||||||
|
// the positive cell, then leaves it immediately at t == 0.
|
||||||
|
GridRayIterator iterator{Vec3d{32.0, 0.5, 0.5}, Vec3d{-1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 2}};
|
||||||
|
const auto visits = take(iterator, 2);
|
||||||
|
Void::Testing::require(visits.size() == 2);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(32, 0, 0));
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(31, 0, 0));
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 0.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_ending_exactly_on_boundary()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 10, .max_distance = 0.5}};
|
||||||
|
const auto visits = take(iterator, 2);
|
||||||
|
Void::Testing::require(visits.size() == 2);
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(1, 0, 0));
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 0.5);
|
||||||
|
Void::Testing::expect(!iterator.next().has_value());
|
||||||
|
Void::Testing::expect(iterator.status() ==
|
||||||
|
GridRayStatus::exhausted_distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_zero_direction_yields_start_once()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{2.5, 3.5, 4.5}, Vec3d{0, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 4}};
|
||||||
|
const auto visits = take(iterator, 4);
|
||||||
|
Void::Testing::require(visits.size() == 1);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(2, 3, 4));
|
||||||
|
Void::Testing::expect(iterator.status() == GridRayStatus::zero_direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_rejects_nonfinite_and_out_of_range()
|
||||||
|
{
|
||||||
|
GridRayIterator nan_origin{
|
||||||
|
Vec3d{std::numeric_limits<double>::quiet_NaN(), 0, 0},
|
||||||
|
Vec3d{1, 0, 0}};
|
||||||
|
Void::Testing::expect(!nan_origin.next().has_value());
|
||||||
|
Void::Testing::expect(nan_origin.status() ==
|
||||||
|
GridRayStatus::nonfinite_input);
|
||||||
|
|
||||||
|
GridRayIterator huge_origin{Vec3d{1e300, 0, 0}, Vec3d{1, 0, 0}};
|
||||||
|
Void::Testing::expect(!huge_origin.next().has_value());
|
||||||
|
Void::Testing::expect(huge_origin.status() ==
|
||||||
|
GridRayStatus::out_of_range);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_step_exhaustion()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 3}};
|
||||||
|
const auto visits = take(iterator, 10);
|
||||||
|
Void::Testing::expect_eq(visits.size(), std::size_t{3});
|
||||||
|
Void::Testing::expect(iterator.status() ==
|
||||||
|
GridRayStatus::exhausted_steps);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_raycast_first_occupied_and_chunk_order()
|
||||||
|
{
|
||||||
|
const std::set<GridCell> occupied{cell(2, 0, 0), cell(0, 0, 0)};
|
||||||
|
|
||||||
|
const auto query = [&occupied](const GridCell& value) {
|
||||||
|
return occupied.contains(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
auto first = Void::Algorithms::raycast_grid(
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0}, query);
|
||||||
|
Void::Testing::require(first.hit.has_value());
|
||||||
|
// The start cell is occupied and reports no entry face.
|
||||||
|
Void::Testing::expect(first.hit->cell == cell(0, 0, 0));
|
||||||
|
Void::Testing::expect(first.hit->face == GridFace{});
|
||||||
|
|
||||||
|
const auto query_without_start = [](const GridCell& value) {
|
||||||
|
return value == cell(2, 0, 0);
|
||||||
|
};
|
||||||
|
auto later = Void::Algorithms::raycast_grid(
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0}, query_without_start);
|
||||||
|
Void::Testing::require(later.hit.has_value());
|
||||||
|
Void::Testing::expect(later.hit->cell == cell(2, 0, 0));
|
||||||
|
Void::Testing::expect(later.hit->face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(later.hit->face.sign, 1);
|
||||||
|
Void::Testing::expect_eq(later.visited, std::size_t{3});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_raycast_miss_reports_status()
|
||||||
|
{
|
||||||
|
auto result = Void::Algorithms::raycast_grid(
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
[](const GridCell&) { return false; },
|
||||||
|
GridRayOptions{.max_steps = 4});
|
||||||
|
Void::Testing::expect(!result.hit.has_value());
|
||||||
|
Void::Testing::expect(result.visited == std::size_t{4});
|
||||||
|
Void::Testing::expect(result.status == GridRayStatus::exhausted_steps);
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
#include <Void/Algorithms/RevisionReadSet.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Algorithms::ReadSetStatus;
|
||||||
|
using Void::Algorithms::ReadSetValidation;
|
||||||
|
using Void::Algorithms::RevisionReadSet;
|
||||||
|
|
||||||
|
using View = std::map<std::string, std::uint64_t>;
|
||||||
|
|
||||||
|
[[nodiscard]] auto lookup(const View& view)
|
||||||
|
{
|
||||||
|
return [&view](const std::string& key) -> std::optional<std::uint64_t> {
|
||||||
|
const auto found = view.find(key);
|
||||||
|
if (found == view.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_deduplicates_unchanged_reads()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::unchanged);
|
||||||
|
Void::Testing::expect_eq(set.size(), std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(set.revision_of("chunk"), std::uint64_t{3});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_detects_conflicting_observations()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("chunk", 4) ==
|
||||||
|
ReadSetStatus::conflicting);
|
||||||
|
Void::Testing::expect(set.conflicted());
|
||||||
|
|
||||||
|
// The first observation is retained, but the set cannot be published.
|
||||||
|
Void::Testing::expect_eq(set.revision_of("chunk"), std::uint64_t{3});
|
||||||
|
const View view{{"chunk", 3}};
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::conflicted);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_reports_capacity_exhaustion()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1, RevisionReadSet::Limits{.max_entries = 2}};
|
||||||
|
Void::Testing::expect(set.observe("a", 1) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("b", 1) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("c", 1) ==
|
||||||
|
ReadSetStatus::capacity_exceeded);
|
||||||
|
Void::Testing::expect(set.incomplete());
|
||||||
|
Void::Testing::expect_eq(set.size(), std::size_t{2});
|
||||||
|
|
||||||
|
const View view{{"a", 1}, {"b", 1}, {"c", 1}};
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::incomplete);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_validates_against_stable_view()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("route", 10) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("support", 20) ==
|
||||||
|
ReadSetStatus::recorded);
|
||||||
|
|
||||||
|
View view{{"route", 10}, {"support", 20}};
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::valid);
|
||||||
|
|
||||||
|
// An unrelated edit does not invalidate the cached result.
|
||||||
|
view["unrelated"] = 99;
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::valid);
|
||||||
|
|
||||||
|
// A change to a consulted revision does.
|
||||||
|
view["support"] = 21;
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::invalidated);
|
||||||
|
|
||||||
|
// A missing consulted key does too.
|
||||||
|
view["support"] = 20;
|
||||||
|
view.erase("route");
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::invalidated);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_rejects_epoch_change_even_with_matching_revisions()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("route", 10) == ReadSetStatus::recorded);
|
||||||
|
const View view{{"route", 10}};
|
||||||
|
Void::Testing::expect(set.validate(2, lookup(view)) ==
|
||||||
|
ReadSetValidation::epoch_changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_failed_search_frontier_opening()
|
||||||
|
{
|
||||||
|
// A failed search consulted a closed frontier at revision 0.
|
||||||
|
RevisionReadSet set{7};
|
||||||
|
Void::Testing::expect(set.observe("frontier", 0) ==
|
||||||
|
ReadSetStatus::recorded);
|
||||||
|
View view{{"frontier", 0}};
|
||||||
|
Void::Testing::expect(set.validate(7, lookup(view)) ==
|
||||||
|
ReadSetValidation::valid);
|
||||||
|
|
||||||
|
// The frontier opens: the cached failure must not be reused.
|
||||||
|
view["frontier"] = 1;
|
||||||
|
Void::Testing::expect(set.validate(7, lookup(view)) ==
|
||||||
|
ReadSetValidation::invalidated);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_rejects_empty_key_and_sorts_entries()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("", 1) == ReadSetStatus::invalid_key);
|
||||||
|
Void::Testing::expect_eq(set.size(), std::size_t{0});
|
||||||
|
|
||||||
|
Void::Testing::expect(set.observe("b", 2) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("a", 1) == ReadSetStatus::recorded);
|
||||||
|
const auto& entries = set.entries();
|
||||||
|
Void::Testing::require(entries.size() == 2);
|
||||||
|
Void::Testing::expect_eq(entries.begin()->first, std::string{"a"});
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
#include <Void/Async/PublicationGatedQueue.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <future>
|
||||||
|
#include <memory>
|
||||||
|
#include <thread>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Token {
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
std::uint64_t revision{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const Token&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Token token(std::uint64_t epoch, std::uint64_t revision)
|
||||||
|
{
|
||||||
|
return Token{.epoch = epoch, .revision = revision};
|
||||||
|
}
|
||||||
|
|
||||||
|
using Queue =
|
||||||
|
Void::Async::PublicationGatedQueue<std::unique_ptr<int>, Token>;
|
||||||
|
using Status = Queue::Status;
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_rejects_stale_publication_without_moving()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1), Queue::Limits{.capacity = 4}};
|
||||||
|
Void::Testing::require(queue.publish(token(1, 2)));
|
||||||
|
|
||||||
|
auto payload = std::make_unique<int>(7);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(payload)) ==
|
||||||
|
Status::publication_changed);
|
||||||
|
// The payload was not moved and the queue is unchanged.
|
||||||
|
Void::Testing::require(payload != nullptr);
|
||||||
|
Void::Testing::expect_eq(*payload, 7);
|
||||||
|
Void::Testing::expect_eq(queue.size(), std::size_t{0});
|
||||||
|
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 2), std::move(payload)) ==
|
||||||
|
Status::admitted);
|
||||||
|
Void::Testing::expect(payload == nullptr);
|
||||||
|
Void::Testing::expect_eq(queue.size(), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_saturation_and_capacity_reuse()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1), Queue::Limits{.capacity = 1}};
|
||||||
|
auto first = std::make_unique<int>(1);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(first)) ==
|
||||||
|
Status::admitted);
|
||||||
|
|
||||||
|
auto second = std::make_unique<int>(2);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(second)) ==
|
||||||
|
Status::saturated);
|
||||||
|
Void::Testing::require(second != nullptr);
|
||||||
|
|
||||||
|
auto popped = queue.try_pop();
|
||||||
|
Void::Testing::require(popped.has_value());
|
||||||
|
Void::Testing::expect_eq(**popped, 1);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(second)) ==
|
||||||
|
Status::admitted);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_closed()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1)};
|
||||||
|
auto pending = std::make_unique<int>(3);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(pending)) ==
|
||||||
|
Status::admitted);
|
||||||
|
queue.close();
|
||||||
|
Void::Testing::expect(!queue.publish(token(1, 2)));
|
||||||
|
Void::Testing::expect(queue.closed());
|
||||||
|
|
||||||
|
auto rejected = std::make_unique<int>(4);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(rejected)) ==
|
||||||
|
Status::closed);
|
||||||
|
Void::Testing::require(rejected != nullptr);
|
||||||
|
|
||||||
|
// Already admitted work can still be drained.
|
||||||
|
auto popped = queue.try_pop();
|
||||||
|
Void::Testing::require(popped.has_value());
|
||||||
|
Void::Testing::expect_eq(**popped, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_admitted_work_finishes_once()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1)};
|
||||||
|
auto payload = std::make_unique<int>(9);
|
||||||
|
Void::Testing::require(queue.try_submit(token(1, 1), std::move(payload)) ==
|
||||||
|
Status::admitted);
|
||||||
|
|
||||||
|
auto first = queue.try_pop();
|
||||||
|
Void::Testing::require(first.has_value());
|
||||||
|
Void::Testing::expect_eq(**first, 9);
|
||||||
|
Void::Testing::expect(!queue.try_pop().has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_stale_submission_after_concurrent_publish()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1)};
|
||||||
|
std::promise<void> validated;
|
||||||
|
std::promise<void> published;
|
||||||
|
std::atomic<Status> status{Status::admitted};
|
||||||
|
std::unique_ptr<int> retained;
|
||||||
|
|
||||||
|
std::thread producer{[&] {
|
||||||
|
auto payload = std::make_unique<int>(5);
|
||||||
|
validated.set_value();
|
||||||
|
published.get_future().wait();
|
||||||
|
status = queue.try_submit(token(1, 1), std::move(payload));
|
||||||
|
retained = std::move(payload);
|
||||||
|
}};
|
||||||
|
|
||||||
|
validated.get_future().wait();
|
||||||
|
// Same epoch, newer revision: the producer's retained publication is
|
||||||
|
// obsolete before its submission.
|
||||||
|
Void::Testing::require(queue.publish(token(1, 2)));
|
||||||
|
published.set_value();
|
||||||
|
producer.join();
|
||||||
|
|
||||||
|
Void::Testing::expect(status.load() == Status::publication_changed);
|
||||||
|
Void::Testing::require(retained != nullptr);
|
||||||
|
Void::Testing::expect_eq(*retained, 5);
|
||||||
|
Void::Testing::expect_eq(queue.size(), std::size_t{0});
|
||||||
|
|
||||||
|
// A fresh producer can submit against the new publication.
|
||||||
|
auto fresh = std::make_unique<int>(6);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 2), std::move(fresh)) ==
|
||||||
|
Status::admitted);
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
#include <Void/Containers/AccountLedger.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <limits>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Containers::AccountLedger;
|
||||||
|
using Void::Containers::LedgerDebit;
|
||||||
|
using Void::Containers::LedgerQuantity;
|
||||||
|
using Void::Containers::LedgerStatus;
|
||||||
|
using Void::Containers::ReservationPhase;
|
||||||
|
|
||||||
|
[[nodiscard]] LedgerDebit debit(std::string account, LedgerQuantity quantity)
|
||||||
|
{
|
||||||
|
return LedgerDebit{.account = std::move(account), .quantity = quantity};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] LedgerQuantity balance(const AccountLedger& ledger,
|
||||||
|
const std::string& account)
|
||||||
|
{
|
||||||
|
return ledger.account(account)->balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_reserve_transfer_conserves_total()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10, 10));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0, 10));
|
||||||
|
|
||||||
|
auto reserved = ledger.reserve("op1", {debit("a", 4)});
|
||||||
|
Void::Testing::expect(reserved.status == LedgerStatus::committed);
|
||||||
|
Void::Testing::expect(reserved.phase == ReservationPhase::held);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{6});
|
||||||
|
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
|
||||||
|
|
||||||
|
auto delivered = ledger.transfer("op1", "b");
|
||||||
|
Void::Testing::expect(delivered.status == LedgerStatus::committed);
|
||||||
|
Void::Testing::expect(delivered.phase == ReservationPhase::delivered);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
|
||||||
|
Void::Testing::expect_eq(ledger.account("b")->owner, std::string{"bob"});
|
||||||
|
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
|
||||||
|
|
||||||
|
// Repeating the same delivery applies nothing twice.
|
||||||
|
auto replay = ledger.transfer("op1", "b");
|
||||||
|
Void::Testing::expect(replay.status == LedgerStatus::replayed);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
|
||||||
|
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
|
||||||
|
|
||||||
|
// A different destination for the same operation is a conflict.
|
||||||
|
auto conflict = ledger.transfer("op1", "a");
|
||||||
|
Void::Testing::expect(conflict.status == LedgerStatus::invalid_state);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_two_claimants_last_unit()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 1));
|
||||||
|
|
||||||
|
Void::Testing::expect(ledger.reserve("first", {debit("a", 1)}).status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
auto second = ledger.reserve("second", {debit("a", 1)});
|
||||||
|
Void::Testing::expect(second.status == LedgerStatus::insufficient_balance);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{0});
|
||||||
|
|
||||||
|
Void::Testing::expect(ledger.release("first").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{1});
|
||||||
|
Void::Testing::expect(ledger.reserve("second", {debit("a", 1)}).status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_multi_account_reservation_is_atomic()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 5));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 1));
|
||||||
|
|
||||||
|
auto failed = ledger.reserve("op", {debit("a", 3), debit("b", 2)});
|
||||||
|
Void::Testing::expect(failed.status == LedgerStatus::insufficient_balance);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{5});
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{1});
|
||||||
|
Void::Testing::expect_eq(ledger.operation_count(), std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_cancel_before_pickup()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 7));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 3)}).committed());
|
||||||
|
|
||||||
|
auto released = ledger.release("op");
|
||||||
|
Void::Testing::expect(released.status == LedgerStatus::committed);
|
||||||
|
Void::Testing::expect(released.phase == ReservationPhase::released);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
|
||||||
|
|
||||||
|
Void::Testing::expect(ledger.release("op").status == LedgerStatus::replayed);
|
||||||
|
Void::Testing::expect(ledger.transfer("op", "a").status ==
|
||||||
|
LedgerStatus::released);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_cancel_during_delivery()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 7));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0, 2));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 3)}).committed());
|
||||||
|
|
||||||
|
auto blocked = ledger.transfer("op", "b");
|
||||||
|
Void::Testing::expect(blocked.status == LedgerStatus::capacity_exhausted);
|
||||||
|
Void::Testing::expect(blocked.phase == ReservationPhase::held);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{0});
|
||||||
|
|
||||||
|
// The reservation is still held and can be cancelled.
|
||||||
|
Void::Testing::expect(ledger.release("op").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_replay_after_restore()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 4)}).committed());
|
||||||
|
|
||||||
|
const auto partially_completed = ledger.save();
|
||||||
|
|
||||||
|
auto restored = AccountLedger::restore(partially_completed);
|
||||||
|
Void::Testing::require(restored.has_value());
|
||||||
|
Void::Testing::expect(restored->transfer("op", "b").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(*restored, "b"), LedgerQuantity{4});
|
||||||
|
|
||||||
|
const auto delivered = restored->save();
|
||||||
|
auto after_delivery = AccountLedger::restore(delivered);
|
||||||
|
Void::Testing::require(after_delivery.has_value());
|
||||||
|
Void::Testing::expect(after_delivery->transfer("op", "b").status ==
|
||||||
|
LedgerStatus::replayed);
|
||||||
|
Void::Testing::expect_eq(balance(*after_delivery, "b"), LedgerQuantity{4});
|
||||||
|
|
||||||
|
// Restoring the earlier snapshot replays the delivery exactly once.
|
||||||
|
auto replay_world = AccountLedger::restore(partially_completed);
|
||||||
|
Void::Testing::require(replay_world.has_value());
|
||||||
|
Void::Testing::expect(replay_world->transfer("op", "b").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(*replay_world, "b"), LedgerQuantity{4});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_overflow_is_rejected()
|
||||||
|
{
|
||||||
|
constexpr auto kMax = std::numeric_limits<LedgerQuantity>::max();
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a1", "alice", kMax));
|
||||||
|
Void::Testing::require(ledger.create_account("a2", "alice", kMax));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0));
|
||||||
|
Void::Testing::require(
|
||||||
|
ledger.reserve("op", {debit("a1", kMax), debit("a2", kMax)})
|
||||||
|
.committed());
|
||||||
|
|
||||||
|
// The reserved total cannot be represented in one quantity.
|
||||||
|
auto overflowed = ledger.transfer("op", "b");
|
||||||
|
Void::Testing::expect(overflowed.status == LedgerStatus::overflow);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{0});
|
||||||
|
Void::Testing::expect(ledger.release("op").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_operation_id_conflict()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 1)}).committed());
|
||||||
|
|
||||||
|
auto conflict = ledger.reserve("op", {debit("a", 2)});
|
||||||
|
Void::Testing::expect(conflict.status == LedgerStatus::invalid_state);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{9});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_account_limits()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::expect(!ledger.create_account("a", "alice", 5, 4));
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 5, 10));
|
||||||
|
Void::Testing::expect(!ledger.create_account("a", "other", 0, 10));
|
||||||
|
Void::Testing::expect(!ledger.set_capacity("a", 4));
|
||||||
|
Void::Testing::require(ledger.set_capacity("a", 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_operation_limit()
|
||||||
|
{
|
||||||
|
AccountLedger ledger{AccountLedger::Limits{.max_accounts = 4,
|
||||||
|
.max_operations = 1}};
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10));
|
||||||
|
Void::Testing::require(ledger.reserve("one", {debit("a", 1)}).committed());
|
||||||
|
auto limited = ledger.reserve("two", {debit("a", 1)});
|
||||||
|
Void::Testing::expect(limited.status == LedgerStatus::limit_exceeded);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{9});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_restore_rejects_invalid_state()
|
||||||
|
{
|
||||||
|
AccountLedger::State bad_balance;
|
||||||
|
bad_balance.accounts.emplace(
|
||||||
|
"a", AccountLedger::AccountState{.owner = "alice",
|
||||||
|
.balance = 5,
|
||||||
|
.capacity = 4});
|
||||||
|
Void::Testing::expect(!AccountLedger::restore(bad_balance).has_value());
|
||||||
|
|
||||||
|
AccountLedger::State dangling_operation;
|
||||||
|
dangling_operation.accounts.emplace(
|
||||||
|
"a", AccountLedger::AccountState{.owner = "alice", .balance = 1});
|
||||||
|
dangling_operation.operations.emplace(
|
||||||
|
"op", AccountLedger::OperationState{
|
||||||
|
.sources = {debit("missing", 1)},
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.destination = {}});
|
||||||
|
Void::Testing::expect(!AccountLedger::restore(dangling_operation).has_value());
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
#include <Void/Containers/SparsePageTable.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <optional>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Table = Void::Containers::SparsePageTable<std::uint32_t, 2>;
|
||||||
|
using Address = Table::CellAddress;
|
||||||
|
using Changed = Table::ChangedPage;
|
||||||
|
using Edit = Table::Edit;
|
||||||
|
using EditStatus = Table::EditStatus;
|
||||||
|
using Page = Table::PageId;
|
||||||
|
using Revision = Table::Revision;
|
||||||
|
|
||||||
|
constexpr std::uint32_t kEmpty = 0;
|
||||||
|
|
||||||
|
[[nodiscard]] Address at(std::int64_t x, std::int64_t y = 0,
|
||||||
|
std::int64_t z = 0)
|
||||||
|
{
|
||||||
|
return Address{.x = x, .y = y, .z = z};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Page page(std::int64_t x, std::int64_t y = 0,
|
||||||
|
std::int64_t z = 0)
|
||||||
|
{
|
||||||
|
return Page{.x = x, .y = y, .z = z};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Edit edit(Address address, std::uint32_t value,
|
||||||
|
std::optional<Revision> expected = std::nullopt)
|
||||||
|
{
|
||||||
|
return Edit{.address = address,
|
||||||
|
.value = value,
|
||||||
|
.expected_revision = expected};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool same_changes(const std::vector<Changed>& lhs,
|
||||||
|
const std::vector<Changed>& rhs)
|
||||||
|
{
|
||||||
|
return lhs == rhs;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_edit_spans_adjacent_pages()
|
||||||
|
{
|
||||||
|
Table table{Table::Limits{.max_pages = 4}};
|
||||||
|
const Edit edits[] = {edit(at(1), 7), edit(at(2), 8)};
|
||||||
|
auto result = table.apply(edits);
|
||||||
|
Void::Testing::require(result.committed());
|
||||||
|
Void::Testing::require(result.changed.size() == 2);
|
||||||
|
// Changed pages are reported in page order.
|
||||||
|
Void::Testing::expect(result.changed[0] ==
|
||||||
|
Changed{.page = page(0), .revision = 1});
|
||||||
|
Void::Testing::expect(result.changed[1] ==
|
||||||
|
Changed{.page = page(1), .revision = 1});
|
||||||
|
Void::Testing::expect_eq(table.get(at(1)), 7u);
|
||||||
|
Void::Testing::expect_eq(table.get(at(2)), 8u);
|
||||||
|
Void::Testing::expect_eq(table.page_count(), std::size_t{2});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_batch_is_atomic_on_stale_revision()
|
||||||
|
{
|
||||||
|
Table table{Table::Limits{.max_pages = 4}};
|
||||||
|
const Edit first[] = {edit(at(1), 7)};
|
||||||
|
Void::Testing::require(table.apply(first).committed());
|
||||||
|
|
||||||
|
const Edit batch[] = {edit(at(0), 1, Revision{1}),
|
||||||
|
edit(at(2), 9, Revision{5})};
|
||||||
|
auto result = table.apply(batch);
|
||||||
|
Void::Testing::expect(result.status == EditStatus::stale_revision);
|
||||||
|
|
||||||
|
// Neither page changed.
|
||||||
|
Void::Testing::expect_eq(table.get(at(0)), kEmpty);
|
||||||
|
Void::Testing::expect_eq(table.get(at(1)), 7u);
|
||||||
|
Void::Testing::expect_eq(table.get(at(2)), kEmpty);
|
||||||
|
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
|
||||||
|
Void::Testing::expect(!table.page_revision(page(1)).has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_budget_exceeded()
|
||||||
|
{
|
||||||
|
Table table{Table::Limits{.max_pages = 1}};
|
||||||
|
const Edit edits[] = {edit(at(0), 1), edit(at(2), 2)};
|
||||||
|
auto result = table.apply(edits);
|
||||||
|
Void::Testing::expect(result.status == EditStatus::page_budget_exceeded);
|
||||||
|
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_revision_exhausted()
|
||||||
|
{
|
||||||
|
Table table{Table::Limits{.max_pages = 4}};
|
||||||
|
const Edit first[] = {edit(at(0), 1)};
|
||||||
|
Void::Testing::require(table.apply(first).committed());
|
||||||
|
|
||||||
|
auto state = table.save();
|
||||||
|
Void::Testing::require(state.pages.size() == 1);
|
||||||
|
state.pages[0].revision = std::numeric_limits<Revision>::max();
|
||||||
|
auto restored = Table::restore(state, Table::Limits{.max_pages = 4});
|
||||||
|
Void::Testing::require(restored.has_value());
|
||||||
|
|
||||||
|
const Edit second[] = {edit(at(0), 2)};
|
||||||
|
auto result = restored->apply(second);
|
||||||
|
Void::Testing::expect(result.status == EditStatus::revision_exhausted);
|
||||||
|
Void::Testing::expect_eq(restored->get(at(0)), 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_duplicate_edit_rejected()
|
||||||
|
{
|
||||||
|
Table table{Table::Limits{.max_pages = 4}};
|
||||||
|
const Edit edits[] = {edit(at(0), 1), edit(at(0), 2)};
|
||||||
|
auto result = table.apply(edits);
|
||||||
|
Void::Testing::expect(result.status == EditStatus::duplicate_edit);
|
||||||
|
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_unchanged_value_does_not_bump()
|
||||||
|
{
|
||||||
|
Table table{Table::Limits{.max_pages = 4}};
|
||||||
|
const Edit noop[] = {edit(at(0), kEmpty)};
|
||||||
|
auto first = table.apply(noop);
|
||||||
|
Void::Testing::require(first.committed());
|
||||||
|
Void::Testing::expect(first.changed.empty());
|
||||||
|
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
|
||||||
|
|
||||||
|
const Edit write[] = {edit(at(0), 5)};
|
||||||
|
Void::Testing::require(table.apply(write).committed());
|
||||||
|
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
|
||||||
|
|
||||||
|
const Edit repeat[] = {edit(at(0), 5)};
|
||||||
|
auto again = table.apply(repeat);
|
||||||
|
Void::Testing::require(again.committed());
|
||||||
|
Void::Testing::expect(again.changed.empty());
|
||||||
|
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_permuted_batch_matches()
|
||||||
|
{
|
||||||
|
Table first{Table::Limits{.max_pages = 4}};
|
||||||
|
Table second{Table::Limits{.max_pages = 4}};
|
||||||
|
|
||||||
|
const std::vector<Edit> ordered{edit(at(0), 1), edit(at(1), 2),
|
||||||
|
edit(at(2), 3), edit(at(5), 4)};
|
||||||
|
std::vector<Edit> permuted{ordered[2], ordered[0], ordered[3], ordered[1]};
|
||||||
|
|
||||||
|
auto a = first.apply(ordered);
|
||||||
|
auto b = second.apply(permuted);
|
||||||
|
Void::Testing::require(a.committed() && b.committed());
|
||||||
|
Void::Testing::expect(same_changes(a.changed, b.changed));
|
||||||
|
for (const auto& edit : ordered) {
|
||||||
|
Void::Testing::expect_eq(first.get(edit.address),
|
||||||
|
second.get(edit.address));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_negative_coordinates()
|
||||||
|
{
|
||||||
|
Table table{Table::Limits{.max_pages = 4}};
|
||||||
|
const Edit edits[] = {edit(at(-1), 3), edit(at(-2), 4), edit(at(-3), 5)};
|
||||||
|
auto result = table.apply(edits);
|
||||||
|
Void::Testing::require(result.committed());
|
||||||
|
// PageSize 2: -1 and -2 live in page -1 (offsets 1 and 0); -3 in page -2.
|
||||||
|
Void::Testing::expect_eq(*table.page_revision(page(-1)), Revision{1});
|
||||||
|
Void::Testing::expect_eq(*table.page_revision(page(-2)), Revision{1});
|
||||||
|
Void::Testing::expect_eq(table.get(at(-1)), 3u);
|
||||||
|
Void::Testing::expect_eq(table.get(at(-2)), 4u);
|
||||||
|
Void::Testing::expect_eq(table.get(at(-3)), 5u);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test sparse_page_restore_rejects_invalid_state()
|
||||||
|
{
|
||||||
|
Table::State duplicate;
|
||||||
|
duplicate.pages.push_back(
|
||||||
|
Table::PageState{.page = page(0), .revision = 1});
|
||||||
|
duplicate.pages.push_back(
|
||||||
|
Table::PageState{.page = page(0), .revision = 2});
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Table::restore(duplicate, Table::Limits{.max_pages = 4}).has_value());
|
||||||
|
|
||||||
|
Table::State too_many;
|
||||||
|
too_many.pages.push_back(
|
||||||
|
Table::PageState{.page = page(0), .revision = 1});
|
||||||
|
too_many.pages.push_back(
|
||||||
|
Table::PageState{.page = page(1), .revision = 1});
|
||||||
|
Void::Testing::expect(
|
||||||
|
!Table::restore(too_many, Table::Limits{.max_pages = 1}).has_value());
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
#include <Void/Core/Publication.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Payload {
|
||||||
|
std::uint64_t revision{0};
|
||||||
|
std::string text;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Tracked {
|
||||||
|
Tracked() { ++live; }
|
||||||
|
~Tracked() { --live; }
|
||||||
|
Tracked(const Tracked&) = delete;
|
||||||
|
Tracked& operator=(const Tracked&) = delete;
|
||||||
|
|
||||||
|
static inline std::atomic<int> live{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] std::shared_ptr<const Payload>
|
||||||
|
payload(std::uint64_t revision, std::string text = {})
|
||||||
|
{
|
||||||
|
return std::make_shared<const Payload>(
|
||||||
|
Payload{.revision = revision, .text = std::move(text)});
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test publication_retains_previous_snapshot()
|
||||||
|
{
|
||||||
|
Void::Core::Publication<Payload> publication{
|
||||||
|
payload(1, "world"), {.epoch = 1, .revision = 1}};
|
||||||
|
|
||||||
|
auto held = publication.acquire();
|
||||||
|
Void::Testing::require(held.get() != nullptr);
|
||||||
|
|
||||||
|
auto result = publication.publish(
|
||||||
|
payload(2, "new world"), {.epoch = 1, .revision = 2});
|
||||||
|
Void::Testing::expect(result.published());
|
||||||
|
|
||||||
|
// The retained handle still sees the old, complete snapshot.
|
||||||
|
Void::Testing::expect_eq(held->revision, std::uint64_t{1});
|
||||||
|
Void::Testing::expect_eq(held->text, std::string{"world"});
|
||||||
|
Void::Testing::expect_eq(held.version().revision, std::uint64_t{1});
|
||||||
|
|
||||||
|
auto current = publication.acquire();
|
||||||
|
Void::Testing::expect_eq(current->revision, std::uint64_t{2});
|
||||||
|
Void::Testing::expect_eq(current->text, std::string{"new world"});
|
||||||
|
Void::Testing::expect_eq(current.version().revision, std::uint64_t{2});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test publication_compare_and_publish_rejects_obsolete_epoch()
|
||||||
|
{
|
||||||
|
Void::Core::Publication<Payload> publication{
|
||||||
|
payload(1, "epoch one"), {.epoch = 1, .revision = 5}};
|
||||||
|
|
||||||
|
Void::Testing::require(
|
||||||
|
publication
|
||||||
|
.publish(payload(2, "epoch two"), {.epoch = 2, .revision = 0})
|
||||||
|
.published());
|
||||||
|
|
||||||
|
// A producer that validated against the old epoch must be rejected.
|
||||||
|
auto stale = publication.publish(payload(3, "late"),
|
||||||
|
{.epoch = 2, .revision = 1},
|
||||||
|
/*expected_epoch=*/1);
|
||||||
|
Void::Testing::expect(stale.status ==
|
||||||
|
Void::Core::Publication<Payload>::PublishStatus::
|
||||||
|
stale_epoch);
|
||||||
|
Void::Testing::expect_eq(publication.version().epoch, std::uint64_t{2});
|
||||||
|
Void::Testing::expect_eq(publication.acquire()->revision,
|
||||||
|
std::uint64_t{2});
|
||||||
|
|
||||||
|
// A lower epoch is rejected too.
|
||||||
|
auto older = publication.publish(payload(4, "older"),
|
||||||
|
{.epoch = 1, .revision = 99});
|
||||||
|
Void::Testing::expect(older.status ==
|
||||||
|
Void::Core::Publication<Payload>::PublishStatus::
|
||||||
|
stale_epoch);
|
||||||
|
Void::Testing::expect_eq(publication.acquire()->revision,
|
||||||
|
std::uint64_t{2});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test publication_rejects_non_advancing_revision()
|
||||||
|
{
|
||||||
|
Void::Core::Publication<Payload> publication{
|
||||||
|
payload(1), {.epoch = 1, .revision = 3}};
|
||||||
|
|
||||||
|
auto same = publication.publish(payload(2), {.epoch = 1, .revision = 3});
|
||||||
|
Void::Testing::expect(same.status ==
|
||||||
|
Void::Core::Publication<Payload>::PublishStatus::
|
||||||
|
stale_revision);
|
||||||
|
auto lower = publication.publish(payload(3), {.epoch = 1, .revision = 2});
|
||||||
|
Void::Testing::expect(lower.status ==
|
||||||
|
Void::Core::Publication<Payload>::PublishStatus::
|
||||||
|
stale_revision);
|
||||||
|
Void::Testing::expect_eq(publication.acquire()->revision,
|
||||||
|
std::uint64_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test publication_new_epoch_resets_revision()
|
||||||
|
{
|
||||||
|
Void::Core::Publication<Payload> publication{
|
||||||
|
payload(1), {.epoch = 1, .revision = 100}};
|
||||||
|
auto result = publication.publish_epoch(payload(2), 2);
|
||||||
|
Void::Testing::expect(result.published());
|
||||||
|
Void::Testing::expect_eq(publication.version().epoch, std::uint64_t{2});
|
||||||
|
Void::Testing::expect_eq(publication.version().revision,
|
||||||
|
std::uint64_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test publication_releases_value_after_last_reader()
|
||||||
|
{
|
||||||
|
std::weak_ptr<const Tracked> old;
|
||||||
|
{
|
||||||
|
auto initial = std::make_shared<const Tracked>();
|
||||||
|
old = initial;
|
||||||
|
Void::Core::Publication<Tracked> publication{
|
||||||
|
std::move(initial), {.epoch = 1, .revision = 1}};
|
||||||
|
auto held = publication.acquire();
|
||||||
|
Void::Testing::expect(!old.expired());
|
||||||
|
|
||||||
|
Void::Testing::require(
|
||||||
|
publication
|
||||||
|
.publish(std::make_shared<const Tracked>(),
|
||||||
|
{.epoch = 1, .revision = 2})
|
||||||
|
.published());
|
||||||
|
|
||||||
|
// The old value is still referenced by the retained reader.
|
||||||
|
Void::Testing::expect(!old.expired());
|
||||||
|
held = publication.acquire();
|
||||||
|
// Replacing the handle drops the last reference to the old value.
|
||||||
|
Void::Testing::expect(old.expired());
|
||||||
|
}
|
||||||
|
Void::Testing::expect(old.expired());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test publication_failed_preparation_preserves_last_good()
|
||||||
|
{
|
||||||
|
Void::Core::Publication<Payload> publication{
|
||||||
|
payload(7, "good"), {.epoch = 1, .revision = 7}};
|
||||||
|
|
||||||
|
try {
|
||||||
|
// A preparation that throws never reaches publish.
|
||||||
|
throw std::runtime_error{"preparation failed"};
|
||||||
|
} catch (const std::runtime_error&) {
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::expect_eq(publication.version().revision,
|
||||||
|
std::uint64_t{7});
|
||||||
|
Void::Testing::expect_eq(publication.acquire()->text, std::string{"good"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test publication_concurrent_readers_see_coherent_snapshots()
|
||||||
|
{
|
||||||
|
Void::Core::Publication<Payload> publication{
|
||||||
|
payload(0, "0"), {.epoch = 1, .revision = 0}};
|
||||||
|
|
||||||
|
constexpr std::uint64_t kPublishes = 200;
|
||||||
|
std::atomic<bool> done{false};
|
||||||
|
std::atomic<int> inconsistent{0};
|
||||||
|
std::atomic<std::uint64_t> observed_max{0};
|
||||||
|
|
||||||
|
std::vector<std::thread> readers;
|
||||||
|
for (int reader = 0; reader < 3; ++reader) {
|
||||||
|
readers.emplace_back([&] {
|
||||||
|
while (!done.load(std::memory_order_acquire)) {
|
||||||
|
auto snapshot = publication.acquire();
|
||||||
|
if (snapshot->revision != snapshot.version().revision) {
|
||||||
|
++inconsistent;
|
||||||
|
}
|
||||||
|
if (snapshot->text !=
|
||||||
|
std::to_string(snapshot->revision)) {
|
||||||
|
++inconsistent;
|
||||||
|
}
|
||||||
|
const auto revision = snapshot->revision;
|
||||||
|
auto previous = observed_max.load();
|
||||||
|
while (previous < revision &&
|
||||||
|
!observed_max.compare_exchange_weak(previous,
|
||||||
|
revision)) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (std::uint64_t revision = 1; revision <= kPublishes; ++revision) {
|
||||||
|
const auto result = publication.publish(
|
||||||
|
payload(revision, std::to_string(revision)),
|
||||||
|
{.epoch = 1, .revision = revision});
|
||||||
|
Void::Testing::expect(result.published());
|
||||||
|
}
|
||||||
|
done.store(true, std::memory_order_release);
|
||||||
|
for (auto& reader : readers) {
|
||||||
|
reader.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::expect_eq(inconsistent.load(), 0);
|
||||||
|
Void::Testing::expect_eq(publication.version().revision, kPublishes);
|
||||||
|
Void::Testing::expect_eq(publication.acquire()->text,
|
||||||
|
std::to_string(kPublishes));
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
#include <Void/Core/Sequence.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
struct WorldTag {};
|
||||||
|
struct OtherWorldTag {};
|
||||||
|
|
||||||
|
using WorldSequence = Void::Core::IdSequence<WorldTag>;
|
||||||
|
using SmallSequence = Void::Core::IdSequence<WorldTag, std::uint8_t>;
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_allocates_monotonically()
|
||||||
|
{
|
||||||
|
WorldSequence sequence;
|
||||||
|
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{1});
|
||||||
|
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{2});
|
||||||
|
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{3});
|
||||||
|
Void::Testing::expect_eq(sequence.high_water(), std::uint64_t{3});
|
||||||
|
Void::Testing::expect_eq(sequence.peek(), std::uint64_t{4});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_instances_are_independent()
|
||||||
|
{
|
||||||
|
WorldSequence first;
|
||||||
|
WorldSequence second;
|
||||||
|
Void::Testing::expect_eq(*first.next(), std::uint64_t{1});
|
||||||
|
Void::Testing::expect_eq(*second.next(), std::uint64_t{1});
|
||||||
|
Void::Testing::expect_eq(*first.next(), std::uint64_t{2});
|
||||||
|
Void::Testing::expect_eq(*second.next(), std::uint64_t{2});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_restore_retires_erased_high_water()
|
||||||
|
{
|
||||||
|
WorldSequence sequence;
|
||||||
|
(void)sequence.next();
|
||||||
|
(void)sequence.next();
|
||||||
|
const auto erased = *sequence.next(); // record 3 is erased by the caller
|
||||||
|
Void::Testing::expect_eq(erased, std::uint64_t{3});
|
||||||
|
|
||||||
|
const auto saved = sequence.state();
|
||||||
|
auto restored = WorldSequence::restore(saved);
|
||||||
|
Void::Testing::require(restored.has_value());
|
||||||
|
// The erased id is retired, not reused.
|
||||||
|
Void::Testing::expect_eq(*restored->next(), std::uint64_t{4});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_copy_replays_from_snapshot()
|
||||||
|
{
|
||||||
|
WorldSequence original;
|
||||||
|
(void)original.next();
|
||||||
|
(void)original.next();
|
||||||
|
|
||||||
|
auto snapshot = original; // copy at a completed boundary
|
||||||
|
Void::Testing::expect_eq(*snapshot.next(), std::uint64_t{3});
|
||||||
|
Void::Testing::expect_eq(*original.next(), std::uint64_t{3});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_batch_is_atomic()
|
||||||
|
{
|
||||||
|
WorldSequence sequence;
|
||||||
|
auto batch = sequence.next_batch(3);
|
||||||
|
Void::Testing::require(batch.has_value());
|
||||||
|
Void::Testing::expect_eq(batch->first, std::uint64_t{1});
|
||||||
|
Void::Testing::expect_eq(batch->count, std::uint64_t{3});
|
||||||
|
Void::Testing::expect_eq(*sequence.next(), std::uint64_t{4});
|
||||||
|
|
||||||
|
// A batch that does not fit changes nothing.
|
||||||
|
SmallSequence small{250};
|
||||||
|
const auto before = small.state();
|
||||||
|
auto too_large = small.next_batch(10);
|
||||||
|
Void::Testing::expect(!too_large.has_value());
|
||||||
|
Void::Testing::expect(small.state() == before);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_zero_batch_is_rejected()
|
||||||
|
{
|
||||||
|
WorldSequence sequence;
|
||||||
|
auto zero = sequence.next_batch(0);
|
||||||
|
Void::Testing::require(!zero.has_value());
|
||||||
|
Void::Testing::expect(zero.error().kind ==
|
||||||
|
Void::Core::SequenceErrorKind::zero_count);
|
||||||
|
Void::Testing::expect_eq(sequence.peek(), std::uint64_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_checked_exhaustion()
|
||||||
|
{
|
||||||
|
SmallSequence sequence{254};
|
||||||
|
Void::Testing::expect_eq(static_cast<int>(*sequence.next()), 254);
|
||||||
|
Void::Testing::expect_eq(static_cast<int>(*sequence.next()), 255);
|
||||||
|
Void::Testing::expect(sequence.exhausted());
|
||||||
|
Void::Testing::expect_eq(static_cast<int>(sequence.available()), 0);
|
||||||
|
|
||||||
|
const auto before = sequence.state();
|
||||||
|
auto overflow = sequence.next();
|
||||||
|
Void::Testing::require(!overflow.has_value());
|
||||||
|
Void::Testing::expect(overflow.error().kind ==
|
||||||
|
Void::Core::SequenceErrorKind::exhausted);
|
||||||
|
Void::Testing::expect(sequence.state() == before);
|
||||||
|
Void::Testing::expect_eq(static_cast<int>(sequence.high_water()), 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_batch_at_final_boundary()
|
||||||
|
{
|
||||||
|
SmallSequence sequence{255};
|
||||||
|
// Only max is available: a batch of two is rejected without change.
|
||||||
|
const auto before = sequence.state();
|
||||||
|
auto two = sequence.next_batch(2);
|
||||||
|
Void::Testing::require(!two.has_value());
|
||||||
|
Void::Testing::expect(two.error().kind ==
|
||||||
|
Void::Core::SequenceErrorKind::exhausted);
|
||||||
|
Void::Testing::expect(sequence.state() == before);
|
||||||
|
|
||||||
|
// A batch of exactly the remaining one succeeds and exhausts.
|
||||||
|
auto one = sequence.next_batch(1);
|
||||||
|
Void::Testing::require(one.has_value());
|
||||||
|
Void::Testing::expect_eq(static_cast<int>(one->first), 255);
|
||||||
|
Void::Testing::expect(sequence.exhausted());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_restore_rejects_invalid_state()
|
||||||
|
{
|
||||||
|
using State = SmallSequence::State;
|
||||||
|
auto zero = SmallSequence::restore(State{.next = 0, .exhausted = false});
|
||||||
|
Void::Testing::expect(!zero.has_value());
|
||||||
|
Void::Testing::expect(zero.error().kind ==
|
||||||
|
Void::Core::SequenceErrorKind::invalid_state);
|
||||||
|
auto inconsistent =
|
||||||
|
SmallSequence::restore(State{.next = 10, .exhausted = true});
|
||||||
|
Void::Testing::expect(!inconsistent.has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test id_sequence_state_is_fixed_width()
|
||||||
|
{
|
||||||
|
using Sequence = Void::Core::IdSequence<WorldTag, std::uint32_t>;
|
||||||
|
static_assert(
|
||||||
|
std::is_same_v<decltype(Sequence::State{}.next), std::uint32_t>);
|
||||||
|
Sequence sequence;
|
||||||
|
(void)sequence.next();
|
||||||
|
const auto state = sequence.state();
|
||||||
|
Void::Testing::expect_eq(state.next, std::uint32_t{2});
|
||||||
|
}
|
||||||
@@ -505,3 +505,119 @@ Void::Testing::Test portable_overflow_helpers_boundary_cases()
|
|||||||
Void::Testing::expect(portable_mul_overflow<std::uint64_t>(
|
Void::Testing::expect(portable_mul_overflow<std::uint64_t>(
|
||||||
std::numeric_limits<std::uint64_t>::max(), 2ULL, &u64));
|
std::numeric_limits<std::uint64_t>::max(), 2ULL, &u64));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── checked_euclidean_div ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
Void::Testing::Test checked_euclidean_div_examples_width_32()
|
||||||
|
{
|
||||||
|
using Void::Numeric::checked_euclidean_div;
|
||||||
|
const auto check = [](std::int32_t a, std::int32_t q, std::int32_t r) {
|
||||||
|
const auto result = checked_euclidean_div(a, std::int32_t{32});
|
||||||
|
Void::Testing::require(result.has_value());
|
||||||
|
Void::Testing::expect_eq(result->quotient, q);
|
||||||
|
Void::Testing::expect_eq(result->remainder, r);
|
||||||
|
};
|
||||||
|
|
||||||
|
check(-33, -2, 31);
|
||||||
|
check(-32, -1, 0);
|
||||||
|
check(-1, -1, 31);
|
||||||
|
check(0, 0, 0);
|
||||||
|
check(31, 0, 31);
|
||||||
|
check(32, 1, 0);
|
||||||
|
check(33, 1, 1);
|
||||||
|
|
||||||
|
// The existing truncating contract is intentionally unchanged.
|
||||||
|
Void::Testing::expect_eq(*Void::Numeric::checked_div(-1, 32), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test checked_euclidean_div_is_constexpr()
|
||||||
|
{
|
||||||
|
using Void::Numeric::checked_euclidean_div;
|
||||||
|
static_assert(checked_euclidean_div(-1, 32).value().quotient == -1);
|
||||||
|
static_assert(checked_euclidean_div(-1, 32).value().remainder == 31);
|
||||||
|
static_assert(checked_euclidean_div(-33, 32).value().quotient == -2);
|
||||||
|
static_assert(checked_euclidean_div(31, 32).value().quotient == 0);
|
||||||
|
static_assert(checked_euclidean_div(32, 32).value().remainder == 0);
|
||||||
|
Void::Testing::expect(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test checked_euclidean_div_exhaustive_int8()
|
||||||
|
{
|
||||||
|
bool ok = true;
|
||||||
|
for (int a = -128; a <= 127 && ok; ++a) {
|
||||||
|
for (int d = 1; d <= 127 && ok; ++d) {
|
||||||
|
const auto result = Void::Numeric::checked_euclidean_div(
|
||||||
|
static_cast<std::int8_t>(a), static_cast<std::int8_t>(d));
|
||||||
|
ok = result.has_value();
|
||||||
|
if (ok) {
|
||||||
|
const int q = result->quotient;
|
||||||
|
const int r = result->remainder;
|
||||||
|
ok = r >= 0 && r < d && q * d + r == a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Void::Testing::expect(ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test checked_euclidean_div_extremes()
|
||||||
|
{
|
||||||
|
using Void::Numeric::checked_euclidean_div;
|
||||||
|
const std::int32_t divisors[] = {1, 3, 32};
|
||||||
|
bool ok = true;
|
||||||
|
for (const auto d : divisors) {
|
||||||
|
const std::int32_t values[] = {
|
||||||
|
std::numeric_limits<std::int32_t>::min(),
|
||||||
|
std::numeric_limits<std::int32_t>::max()};
|
||||||
|
for (const auto a : values) {
|
||||||
|
const auto result = checked_euclidean_div(a, d);
|
||||||
|
ok = ok && result.has_value();
|
||||||
|
if (ok) {
|
||||||
|
const std::int64_t q = result->quotient;
|
||||||
|
const std::int64_t r = result->remainder;
|
||||||
|
ok = r >= 0 && r < d && q * d + r == a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Void::Testing::expect(ok);
|
||||||
|
|
||||||
|
const auto min32 = checked_euclidean_div(
|
||||||
|
std::numeric_limits<std::int64_t>::min(), std::int64_t{32});
|
||||||
|
Void::Testing::require(min32.has_value());
|
||||||
|
Void::Testing::expect_eq(min32->quotient,
|
||||||
|
std::int64_t{-288230376151711744});
|
||||||
|
Void::Testing::expect_eq(min32->remainder, std::int64_t{0});
|
||||||
|
|
||||||
|
const auto min3 = checked_euclidean_div(
|
||||||
|
std::numeric_limits<std::int64_t>::min(), std::int64_t{3});
|
||||||
|
Void::Testing::require(min3.has_value());
|
||||||
|
Void::Testing::expect_eq(min3->quotient,
|
||||||
|
std::int64_t{-3074457345618258603});
|
||||||
|
Void::Testing::expect_eq(min3->remainder, std::int64_t{1});
|
||||||
|
|
||||||
|
const auto max32 = checked_euclidean_div(
|
||||||
|
std::numeric_limits<std::int64_t>::max(), std::int64_t{32});
|
||||||
|
Void::Testing::require(max32.has_value());
|
||||||
|
Void::Testing::expect_eq(max32->quotient,
|
||||||
|
std::int64_t{288230376151711743});
|
||||||
|
Void::Testing::expect_eq(max32->remainder, std::int64_t{31});
|
||||||
|
|
||||||
|
const auto max3 = checked_euclidean_div(
|
||||||
|
std::numeric_limits<std::int64_t>::max(), std::int64_t{3});
|
||||||
|
Void::Testing::require(max3.has_value());
|
||||||
|
Void::Testing::expect_eq(max3->quotient,
|
||||||
|
std::int64_t{3074457345618258602});
|
||||||
|
Void::Testing::expect_eq(max3->remainder, std::int64_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test checked_euclidean_div_invalid_width()
|
||||||
|
{
|
||||||
|
using Void::Numeric::checked_euclidean_div;
|
||||||
|
using Void::Numeric::Error;
|
||||||
|
const auto zero = checked_euclidean_div(5, 0);
|
||||||
|
Void::Testing::require(!zero.has_value());
|
||||||
|
Void::Testing::expect(zero.error() == Error::DivisionByZero);
|
||||||
|
|
||||||
|
const auto negative = checked_euclidean_div(5, -1);
|
||||||
|
Void::Testing::require(!negative.has_value());
|
||||||
|
Void::Testing::expect(negative.error() == Error::InvalidInput);
|
||||||
|
}
|
||||||
@@ -146,3 +146,136 @@ Void::Testing::Test sample_indices_in_range()
|
|||||||
Void::Testing::expect(i < std::size_t{10});
|
Void::Testing::expect(i < std::size_t{10});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Xoshiro256 versioned state and bounded draws ─────────────────────────────
|
||||||
|
|
||||||
|
Void::Testing::Test xoshiro_frozen_outputs_are_portable()
|
||||||
|
{
|
||||||
|
// These values are part of the algorithm identity: any change means a
|
||||||
|
// new generator version, not a silent reinterpretation of saved worlds.
|
||||||
|
Void::Random::Xoshiro256 raw{42};
|
||||||
|
Void::Testing::expect_eq(raw(), std::uint64_t{1546998764402558742ULL});
|
||||||
|
Void::Testing::expect_eq(raw(), std::uint64_t{6990951692964543102ULL});
|
||||||
|
Void::Testing::expect_eq(raw(),
|
||||||
|
std::uint64_t{12544586762248559009ULL});
|
||||||
|
Void::Testing::expect_eq(raw(),
|
||||||
|
std::uint64_t{17057574109182124193ULL});
|
||||||
|
|
||||||
|
Void::Random::Xoshiro256 bounded{42};
|
||||||
|
Void::Testing::expect_eq(bounded.bounded(1000), std::uint64_t{742});
|
||||||
|
Void::Testing::expect_eq(bounded.bounded(1000), std::uint64_t{102});
|
||||||
|
Void::Testing::expect_eq(bounded.bounded(1000), std::uint64_t{9});
|
||||||
|
Void::Testing::expect_eq(bounded.bounded(1000), std::uint64_t{193});
|
||||||
|
|
||||||
|
Void::Random::Xoshiro256 stateful{42};
|
||||||
|
(void)stateful();
|
||||||
|
(void)stateful();
|
||||||
|
(void)stateful();
|
||||||
|
const auto state = stateful.state();
|
||||||
|
Void::Testing::expect_eq(state.version, std::uint32_t{1});
|
||||||
|
Void::Testing::expect_eq(state.words[0],
|
||||||
|
std::uint64_t{14724789073754520473ULL});
|
||||||
|
Void::Testing::expect_eq(state.words[1],
|
||||||
|
std::uint64_t{2590629650289322887ULL});
|
||||||
|
Void::Testing::expect_eq(state.words[2],
|
||||||
|
std::uint64_t{7959817307922065030ULL});
|
||||||
|
Void::Testing::expect_eq(state.words[3],
|
||||||
|
std::uint64_t{9375168587437865237ULL});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test xoshiro_state_round_trip_resumes_suffix()
|
||||||
|
{
|
||||||
|
Void::Random::Xoshiro256 original{42};
|
||||||
|
(void)original();
|
||||||
|
(void)original.bounded(1000);
|
||||||
|
(void)original();
|
||||||
|
(void)original.bounded(7);
|
||||||
|
|
||||||
|
const auto saved = original.state();
|
||||||
|
auto restored = Void::Random::Xoshiro256::from_state(saved);
|
||||||
|
Void::Testing::require(restored.has_value());
|
||||||
|
Void::Testing::expect(restored->state() == saved);
|
||||||
|
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
Void::Testing::expect_eq((*restored)(), original());
|
||||||
|
Void::Testing::expect_eq(restored->bounded(999),
|
||||||
|
original.bounded(999));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test xoshiro_state_rejects_invalid_without_changing_stream()
|
||||||
|
{
|
||||||
|
Void::Random::Xoshiro256 rng{5};
|
||||||
|
(void)rng();
|
||||||
|
const auto before = rng.state();
|
||||||
|
|
||||||
|
Void::Random::Xoshiro256::State zero{.version = 1, .words = {}};
|
||||||
|
auto zero_result = rng.restore(zero);
|
||||||
|
Void::Testing::require(!zero_result.has_value());
|
||||||
|
Void::Testing::expect(zero_result.error().kind ==
|
||||||
|
Void::Random::Xoshiro256::StateErrorKind::
|
||||||
|
invalid_state);
|
||||||
|
Void::Testing::expect(rng.state() == before);
|
||||||
|
|
||||||
|
Void::Random::Xoshiro256::State unknown{.version = 99,
|
||||||
|
.words = before.words};
|
||||||
|
auto unknown_result = rng.restore(unknown);
|
||||||
|
Void::Testing::require(!unknown_result.has_value());
|
||||||
|
Void::Testing::expect(unknown_result.error().kind ==
|
||||||
|
Void::Random::Xoshiro256::StateErrorKind::
|
||||||
|
unknown_version);
|
||||||
|
Void::Testing::expect(rng.state() == before);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test xoshiro_bounded_zero_and_one_do_not_consume()
|
||||||
|
{
|
||||||
|
Void::Random::Xoshiro256 rng{7};
|
||||||
|
const auto before = rng.state();
|
||||||
|
Void::Testing::expect_eq(rng.bounded(0), std::uint64_t{0});
|
||||||
|
Void::Testing::expect_eq(rng.bounded(1), std::uint64_t{0});
|
||||||
|
Void::Testing::expect(rng.state() == before);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test xoshiro_bounded_is_in_range()
|
||||||
|
{
|
||||||
|
const std::uint64_t bounds[] = {2, 3, 1000,
|
||||||
|
std::uint64_t{0x8000000000000001ULL},
|
||||||
|
std::numeric_limits<std::uint64_t>::max()};
|
||||||
|
Void::Random::Xoshiro256 rng{11};
|
||||||
|
for (const auto bound : bounds) {
|
||||||
|
for (int i = 0; i < 200; ++i) {
|
||||||
|
const auto value = rng.bounded(bound);
|
||||||
|
Void::Testing::expect(value < bound);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test xoshiro_interleaved_streams_are_independent()
|
||||||
|
{
|
||||||
|
Void::Random::Xoshiro256 interleaved_a{1};
|
||||||
|
Void::Random::Xoshiro256 interleaved_b{2};
|
||||||
|
Void::Random::Xoshiro256 sequential_a{1};
|
||||||
|
Void::Random::Xoshiro256 sequential_b{2};
|
||||||
|
|
||||||
|
for (int i = 0; i < 32; ++i) {
|
||||||
|
Void::Testing::expect_eq(interleaved_a(), sequential_a());
|
||||||
|
Void::Testing::expect_eq(interleaved_b(), sequential_b());
|
||||||
|
Void::Testing::expect_eq(interleaved_a.bounded(100),
|
||||||
|
sequential_a.bounded(100));
|
||||||
|
Void::Testing::expect_eq(interleaved_b.bounded(5),
|
||||||
|
sequential_b.bounded(5));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test xoshiro_discard_matches_draws()
|
||||||
|
{
|
||||||
|
Void::Random::Xoshiro256 discarded{9};
|
||||||
|
discarded.discard(5);
|
||||||
|
Void::Random::Xoshiro256 drawn{9};
|
||||||
|
for (int i = 0; i < 5; ++i) {
|
||||||
|
(void)drawn();
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 5; ++i) {
|
||||||
|
Void::Testing::expect_eq(discarded(), drawn());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
#include <Void/Messaging/RequestLedger.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <expected>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Ledger =
|
||||||
|
Void::Messaging::RequestLedger<std::string, std::expected<int, std::string>>;
|
||||||
|
using Key = Ledger::Key;
|
||||||
|
using Status = Ledger::Status;
|
||||||
|
|
||||||
|
[[nodiscard]] Key key(std::uint64_t epoch, std::uint64_t request_id,
|
||||||
|
std::string client = "client")
|
||||||
|
{
|
||||||
|
return Key{.epoch = epoch, .client = std::move(client),
|
||||||
|
.request_id = request_id};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_replays_exact_repeat()
|
||||||
|
{
|
||||||
|
Ledger ledger{8, 1};
|
||||||
|
const auto k = key(1, 42);
|
||||||
|
auto first = ledger.check(k, "op");
|
||||||
|
Void::Testing::expect(first.status == Status::admitted);
|
||||||
|
Void::Testing::require(ledger.record(k, 7));
|
||||||
|
|
||||||
|
auto repeat = ledger.check(k, "op");
|
||||||
|
Void::Testing::expect(repeat.status == Status::replay);
|
||||||
|
Void::Testing::require(repeat.result.has_value());
|
||||||
|
Void::Testing::expect_eq(*repeat.result, 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_replays_rejected_outcome()
|
||||||
|
{
|
||||||
|
Ledger ledger{8, 1};
|
||||||
|
const auto k = key(1, 1);
|
||||||
|
Void::Testing::expect(ledger.check(k, "op").status == Status::admitted);
|
||||||
|
Void::Testing::require(ledger.record(
|
||||||
|
k, std::unexpected<std::string>{"insufficient funds"}));
|
||||||
|
|
||||||
|
auto repeat = ledger.check(k, "op");
|
||||||
|
Void::Testing::expect(repeat.status == Status::replay);
|
||||||
|
Void::Testing::require(repeat.result.has_value());
|
||||||
|
Void::Testing::expect(!repeat.result->has_value());
|
||||||
|
Void::Testing::expect_eq(repeat.result->error(),
|
||||||
|
std::string{"insufficient funds"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_detects_payload_conflict()
|
||||||
|
{
|
||||||
|
Ledger ledger{8, 1};
|
||||||
|
const auto k = key(1, 5);
|
||||||
|
Void::Testing::expect(ledger.check(k, "payload-a").status ==
|
||||||
|
Status::admitted);
|
||||||
|
Void::Testing::require(ledger.record(k, 10));
|
||||||
|
|
||||||
|
auto conflict = ledger.check(k, "payload-b");
|
||||||
|
Void::Testing::expect(conflict.status == Status::payload_conflict);
|
||||||
|
Void::Testing::expect(!conflict.result.has_value());
|
||||||
|
|
||||||
|
// The conflicting retry changed nothing.
|
||||||
|
auto repeat = ledger.check(k, "payload-a");
|
||||||
|
Void::Testing::expect(repeat.status == Status::replay);
|
||||||
|
Void::Testing::expect_eq(*repeat.result, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_delayed_retry_after_newer_operations()
|
||||||
|
{
|
||||||
|
Ledger ledger{8, 1};
|
||||||
|
const auto first = key(1, 1);
|
||||||
|
const auto second = key(1, 2);
|
||||||
|
Void::Testing::expect(ledger.check(first, "one").status == Status::admitted);
|
||||||
|
Void::Testing::require(ledger.record(first, 100));
|
||||||
|
Void::Testing::expect(ledger.check(second, "two").status == Status::admitted);
|
||||||
|
Void::Testing::require(ledger.record(second, 200));
|
||||||
|
|
||||||
|
auto delayed = ledger.check(first, "one");
|
||||||
|
Void::Testing::expect(delayed.status == Status::replay);
|
||||||
|
Void::Testing::expect_eq(*delayed.result, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_epoch_rollover()
|
||||||
|
{
|
||||||
|
Ledger ledger{8, 1};
|
||||||
|
const auto old = key(1, 7);
|
||||||
|
Void::Testing::expect(ledger.check(old, "op").status == Status::admitted);
|
||||||
|
Void::Testing::require(ledger.record(old, 1));
|
||||||
|
|
||||||
|
Void::Testing::require(ledger.advance_epoch(2));
|
||||||
|
Void::Testing::expect_eq(ledger.epoch(), std::uint64_t{2});
|
||||||
|
Void::Testing::expect_eq(ledger.snapshot().size, std::size_t{0});
|
||||||
|
|
||||||
|
// The old request number can never execute again after cleanup.
|
||||||
|
Void::Testing::expect(ledger.check(old, "op").status == Status::stale_epoch);
|
||||||
|
|
||||||
|
const auto fresh = key(2, 7);
|
||||||
|
Void::Testing::expect(ledger.check(fresh, "op").status == Status::admitted);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_capacity_pressure()
|
||||||
|
{
|
||||||
|
Ledger ledger{2, 1};
|
||||||
|
Void::Testing::expect(ledger.check(key(1, 1), "a").status ==
|
||||||
|
Status::admitted);
|
||||||
|
Void::Testing::expect(ledger.check(key(1, 2), "b").status ==
|
||||||
|
Status::admitted);
|
||||||
|
Void::Testing::expect(ledger.check(key(1, 3), "c").status ==
|
||||||
|
Status::capacity_exceeded);
|
||||||
|
|
||||||
|
// Completed entries stay retained: capacity is only freed by rollover.
|
||||||
|
Void::Testing::require(ledger.record(key(1, 1), 1));
|
||||||
|
Void::Testing::require(ledger.record(key(1, 2), 2));
|
||||||
|
Void::Testing::expect(ledger.check(key(1, 3), "c").status ==
|
||||||
|
Status::capacity_exceeded);
|
||||||
|
|
||||||
|
Void::Testing::require(ledger.advance_epoch(2));
|
||||||
|
Void::Testing::expect(ledger.check(key(2, 3), "c").status ==
|
||||||
|
Status::admitted);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_in_progress_and_result_is_immutable()
|
||||||
|
{
|
||||||
|
Ledger ledger{8, 1};
|
||||||
|
const auto k = key(1, 9);
|
||||||
|
Void::Testing::expect(ledger.check(k, "op").status == Status::admitted);
|
||||||
|
Void::Testing::expect(ledger.check(k, "op").status == Status::in_progress);
|
||||||
|
|
||||||
|
Void::Testing::require(ledger.record(k, 5));
|
||||||
|
// A second record never overwrites the first answer.
|
||||||
|
Void::Testing::expect(!ledger.record(k, 6));
|
||||||
|
auto repeat = ledger.check(k, "op");
|
||||||
|
Void::Testing::expect(repeat.status == Status::replay);
|
||||||
|
Void::Testing::expect_eq(*repeat.result, 5);
|
||||||
|
|
||||||
|
const auto snap = ledger.snapshot();
|
||||||
|
Void::Testing::expect_eq(snap.size, std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(snap.completed, std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(snap.in_flight, std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test request_ledger_rejects_non_advancing_epoch()
|
||||||
|
{
|
||||||
|
Ledger ledger{8, 3};
|
||||||
|
Void::Testing::expect(!ledger.advance_epoch(3));
|
||||||
|
Void::Testing::expect(!ledger.advance_epoch(2));
|
||||||
|
Void::Testing::expect_eq(ledger.epoch(), std::uint64_t{3});
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
#include <Void/Script/Lua.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Script::ErrorKind;
|
||||||
|
using Void::Script::Host;
|
||||||
|
using Void::Script::HostInvocation;
|
||||||
|
using Void::Script::Input;
|
||||||
|
using Void::Script::Integer;
|
||||||
|
using Void::Script::Limits;
|
||||||
|
using Void::Script::LuaEvaluator;
|
||||||
|
|
||||||
|
[[nodiscard]] Host add_host()
|
||||||
|
{
|
||||||
|
return Host{
|
||||||
|
.name = "add",
|
||||||
|
.function = [](std::span<const Integer> arguments)
|
||||||
|
-> std::expected<Integer, std::string> {
|
||||||
|
if (arguments.size() != 2) {
|
||||||
|
return std::unexpected{std::string{"add expects two arguments"}};
|
||||||
|
}
|
||||||
|
return arguments[0] + arguments[1];
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Host fail_host()
|
||||||
|
{
|
||||||
|
return Host{
|
||||||
|
.name = "fail",
|
||||||
|
.function = [](std::span<const Integer> arguments)
|
||||||
|
-> std::expected<Integer, std::string> {
|
||||||
|
if (!arguments.empty() && arguments[0] < 0) {
|
||||||
|
return std::unexpected{std::string{"negative"}};
|
||||||
|
}
|
||||||
|
return arguments.empty() ? Integer{0} : arguments[0];
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test lua_evaluates_integer_results_and_inputs()
|
||||||
|
{
|
||||||
|
LuaEvaluator evaluator;
|
||||||
|
const Input inputs[] = {Input{.key = 1, .value = 2},
|
||||||
|
Input{.key = 2, .value = 3}};
|
||||||
|
auto result = evaluator.evaluate("return input[1] + input[2]", inputs);
|
||||||
|
Void::Testing::require(result.has_value());
|
||||||
|
Void::Testing::expect(result->integers == std::vector<Integer>{5});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_host_functions_are_recorded()
|
||||||
|
{
|
||||||
|
LuaEvaluator evaluator{Limits{}, {add_host()}};
|
||||||
|
auto result = evaluator.evaluate("return add(2, 3)");
|
||||||
|
Void::Testing::require(result.has_value());
|
||||||
|
Void::Testing::expect(result->integers == std::vector<Integer>{5});
|
||||||
|
Void::Testing::require(result->host_calls.size() == 1);
|
||||||
|
Void::Testing::expect(result->host_calls[0] ==
|
||||||
|
HostInvocation{.host = "add",
|
||||||
|
.arguments = {2, 3},
|
||||||
|
.result = 5});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_host_error_is_structured_and_recovers()
|
||||||
|
{
|
||||||
|
LuaEvaluator evaluator{Limits{}, {fail_host()}};
|
||||||
|
auto failed = evaluator.evaluate("return fail(-1)");
|
||||||
|
Void::Testing::require(!failed.has_value());
|
||||||
|
Void::Testing::expect(failed.error().kind == ErrorKind::host_error);
|
||||||
|
|
||||||
|
// A later valid evaluation starts from a clean state.
|
||||||
|
auto recovered = evaluator.evaluate("return fail(4)");
|
||||||
|
Void::Testing::require(recovered.has_value());
|
||||||
|
Void::Testing::expect(recovered->integers == std::vector<Integer>{4});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_instruction_limit()
|
||||||
|
{
|
||||||
|
Limits limits;
|
||||||
|
limits.max_instructions = 1'000;
|
||||||
|
LuaEvaluator evaluator{limits};
|
||||||
|
auto result = evaluator.evaluate("while true do end");
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind == ErrorKind::instruction_limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_allocator_limit()
|
||||||
|
{
|
||||||
|
Limits limits;
|
||||||
|
limits.max_allocator_bytes = 128 * 1024;
|
||||||
|
LuaEvaluator evaluator{limits};
|
||||||
|
auto result = evaluator.evaluate(
|
||||||
|
"local s = string.rep('x', 1000000) return #s");
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind == ErrorKind::allocator_limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_host_call_limit()
|
||||||
|
{
|
||||||
|
Limits limits;
|
||||||
|
limits.max_host_calls = 2;
|
||||||
|
LuaEvaluator evaluator{limits, {fail_host()}};
|
||||||
|
auto result = evaluator.evaluate("for i = 1, 10 do fail(i) end return 0");
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind == ErrorKind::host_call_limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_compile_error()
|
||||||
|
{
|
||||||
|
LuaEvaluator evaluator;
|
||||||
|
auto result = evaluator.evaluate("return (");
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind == ErrorKind::compile);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_result_limit()
|
||||||
|
{
|
||||||
|
Limits limits;
|
||||||
|
limits.max_result_integers = 2;
|
||||||
|
LuaEvaluator evaluator{limits};
|
||||||
|
auto result = evaluator.evaluate("return 1, 2, 3");
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind == ErrorKind::result_limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_rejects_non_integer_results()
|
||||||
|
{
|
||||||
|
LuaEvaluator evaluator;
|
||||||
|
auto result = evaluator.evaluate("return 'text'");
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind == ErrorKind::runtime);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test lua_input_limit()
|
||||||
|
{
|
||||||
|
Limits limits;
|
||||||
|
limits.max_inputs = 1;
|
||||||
|
LuaEvaluator evaluator{limits};
|
||||||
|
const Input inputs[] = {Input{.key = 1, .value = 1},
|
||||||
|
Input{.key = 2, .value = 2}};
|
||||||
|
auto result = evaluator.evaluate("return 0", inputs);
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind == ErrorKind::invalid_input);
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
#include <Void/System/Audio.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::System::AudioDevice;
|
||||||
|
using Void::System::AudioStatus;
|
||||||
|
using Void::System::PcmBuffer;
|
||||||
|
using Void::System::VoiceState;
|
||||||
|
|
||||||
|
[[nodiscard]] std::shared_ptr<const PcmBuffer>
|
||||||
|
buffer(std::uint32_t rate = 44100, std::uint16_t channels = 1,
|
||||||
|
std::size_t frames = 4)
|
||||||
|
{
|
||||||
|
PcmBuffer value;
|
||||||
|
value.format = {.sample_rate = rate, .channels = channels};
|
||||||
|
value.samples.assign(frames * channels, 100);
|
||||||
|
return std::make_shared<const PcmBuffer>(std::move(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test audio_play_owns_samples_and_stop_releases()
|
||||||
|
{
|
||||||
|
auto device = AudioDevice::open_silent();
|
||||||
|
Void::Testing::require(device.has_value());
|
||||||
|
|
||||||
|
auto samples = buffer();
|
||||||
|
std::weak_ptr<const PcmBuffer> weak = samples;
|
||||||
|
auto voice = device->play(samples, /*loop=*/true);
|
||||||
|
Void::Testing::require(voice.has_value());
|
||||||
|
samples.reset();
|
||||||
|
Void::Testing::expect(!weak.expired());
|
||||||
|
|
||||||
|
Void::Testing::expect(device->stop(*voice));
|
||||||
|
Void::Testing::expect(weak.expired());
|
||||||
|
Void::Testing::expect_eq(device->active_voices(), std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test audio_voice_cap()
|
||||||
|
{
|
||||||
|
auto device = AudioDevice::open_silent({.max_voices = 2});
|
||||||
|
Void::Testing::require(device.has_value());
|
||||||
|
|
||||||
|
auto first = device->play(buffer(), true);
|
||||||
|
auto second = device->play(buffer(), true);
|
||||||
|
Void::Testing::require(first.has_value() && second.has_value());
|
||||||
|
auto third = device->play(buffer(), true);
|
||||||
|
Void::Testing::require(!third.has_value());
|
||||||
|
Void::Testing::expect(third.error().status == AudioStatus::voice_limit);
|
||||||
|
|
||||||
|
Void::Testing::expect(device->stop(*first));
|
||||||
|
auto reused = device->play(buffer(), true);
|
||||||
|
Void::Testing::expect(reused.has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test audio_loop_stays_until_stopped()
|
||||||
|
{
|
||||||
|
auto device = AudioDevice::open_silent();
|
||||||
|
Void::Testing::require(device.has_value());
|
||||||
|
auto voice = device->play(buffer(), true);
|
||||||
|
Void::Testing::require(voice.has_value());
|
||||||
|
Void::Testing::expect(device->state(*voice) == VoiceState::playing);
|
||||||
|
Void::Testing::expect(device->stop(*voice));
|
||||||
|
Void::Testing::expect(device->state(*voice) == VoiceState::unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test audio_non_loop_finishes_and_releases()
|
||||||
|
{
|
||||||
|
auto device = AudioDevice::open_silent();
|
||||||
|
Void::Testing::require(device.has_value());
|
||||||
|
// A zero-length duration finishes on the next state query.
|
||||||
|
auto samples = buffer(1'000'000'000, 1, 1);
|
||||||
|
std::weak_ptr<const PcmBuffer> weak = samples;
|
||||||
|
auto voice = device->play(samples, /*loop=*/false);
|
||||||
|
Void::Testing::require(voice.has_value());
|
||||||
|
samples.reset();
|
||||||
|
Void::Testing::expect(device->state(*voice) == VoiceState::finished);
|
||||||
|
Void::Testing::expect(weak.expired());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test audio_close_stops_active_voices_and_reopens()
|
||||||
|
{
|
||||||
|
auto device = AudioDevice::open_silent();
|
||||||
|
Void::Testing::require(device.has_value());
|
||||||
|
auto samples = buffer();
|
||||||
|
std::weak_ptr<const PcmBuffer> weak = samples;
|
||||||
|
auto voice = device->play(samples, true);
|
||||||
|
Void::Testing::require(voice.has_value());
|
||||||
|
samples.reset();
|
||||||
|
|
||||||
|
device->close();
|
||||||
|
Void::Testing::expect(weak.expired());
|
||||||
|
Void::Testing::expect_eq(device->active_voices(), std::size_t{0});
|
||||||
|
auto rejected = device->play(buffer(), true);
|
||||||
|
Void::Testing::require(!rejected.has_value());
|
||||||
|
Void::Testing::expect(rejected.error().status == AudioStatus::closed);
|
||||||
|
|
||||||
|
auto reopened = AudioDevice::open_silent();
|
||||||
|
Void::Testing::require(reopened.has_value());
|
||||||
|
Void::Testing::expect(reopened->play(buffer(), true).has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test audio_rejects_invalid_buffers()
|
||||||
|
{
|
||||||
|
auto device = AudioDevice::open_silent();
|
||||||
|
Void::Testing::require(device.has_value());
|
||||||
|
auto null_buffer = device->play(nullptr);
|
||||||
|
Void::Testing::require(!null_buffer.has_value());
|
||||||
|
Void::Testing::expect(null_buffer.error().status ==
|
||||||
|
AudioStatus::invalid_buffer);
|
||||||
|
|
||||||
|
PcmBuffer empty;
|
||||||
|
empty.format = {.sample_rate = 44100, .channels = 1};
|
||||||
|
auto empty_buffer = device->play(
|
||||||
|
std::make_shared<const PcmBuffer>(std::move(empty)));
|
||||||
|
Void::Testing::require(!empty_buffer.has_value());
|
||||||
|
Void::Testing::expect(empty_buffer.error().status ==
|
||||||
|
AudioStatus::invalid_buffer);
|
||||||
|
}
|
||||||
@@ -3,8 +3,17 @@
|
|||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
#include <Void/Testing/Test.hpp>
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <cerrno>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <format>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <iterator>
|
||||||
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
Void::Testing::Test read_file_returns_contents()
|
Void::Testing::Test read_file_returns_contents()
|
||||||
{
|
{
|
||||||
@@ -212,3 +221,272 @@ Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps()
|
|||||||
kLinkMtime);
|
kLinkMtime);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Portable scoped temp directory (TempDir is POSIX-only today, but the
|
||||||
|
/// replace_file contract must also run on Windows x64).
|
||||||
|
struct ScopedTestDir
|
||||||
|
{
|
||||||
|
std::filesystem::path path;
|
||||||
|
|
||||||
|
explicit ScopedTestDir(std::string_view label)
|
||||||
|
{
|
||||||
|
path = std::filesystem::temp_directory_path() /
|
||||||
|
std::format("void_path_{}_{:016x}",
|
||||||
|
label,
|
||||||
|
Void::FileSystem::detail::next_temp_entropy());
|
||||||
|
std::filesystem::create_directories(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
~ScopedTestDir()
|
||||||
|
{
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::remove_all(path, ec);
|
||||||
|
}
|
||||||
|
|
||||||
|
ScopedTestDir(const ScopedTestDir&) = delete;
|
||||||
|
ScopedTestDir& operator=(const ScopedTestDir&) = delete;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] std::string slurp(const std::filesystem::path& path)
|
||||||
|
{
|
||||||
|
std::ifstream in{path, std::ios::binary};
|
||||||
|
return std::string{std::istreambuf_iterator<char>{in},
|
||||||
|
std::istreambuf_iterator<char>{}};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t entry_count(const std::filesystem::path& dir)
|
||||||
|
{
|
||||||
|
std::size_t count = 0;
|
||||||
|
for (const auto& entry : std::filesystem::directory_iterator{dir}) {
|
||||||
|
(void)entry;
|
||||||
|
++count;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
void seed(const std::filesystem::path& path, std::string_view content)
|
||||||
|
{
|
||||||
|
std::ofstream out{path, std::ios::binary | std::ios::trunc};
|
||||||
|
out.write(content.data(), static_cast<std::streamsize>(content.size()));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// Contract for replace_file/atomic_write that must hold on every supported
|
||||||
|
// platform: pre-publication failures preserve the old file, post-publication
|
||||||
|
// failures report visibility + unknown durability, and staging files never
|
||||||
|
// outlive a call or endanger the live destination.
|
||||||
|
Void::Testing::Test replace_file_contract_durability_and_faults()
|
||||||
|
{
|
||||||
|
ScopedTestDir dir{"contract"};
|
||||||
|
const auto target = dir.path / "slot.bin";
|
||||||
|
|
||||||
|
// First creation: there is no previous destination.
|
||||||
|
{
|
||||||
|
auto r = Void::FileSystem::replace_file(target, std::string_view{"first"});
|
||||||
|
Void::Testing::expect(r.has_value());
|
||||||
|
Void::Testing::expect_eq(slurp(target), std::string{"first"});
|
||||||
|
Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replacement of an existing destination.
|
||||||
|
{
|
||||||
|
auto r = Void::FileSystem::replace_file(target, std::string_view{"second"});
|
||||||
|
Void::Testing::expect(r.has_value());
|
||||||
|
Void::Testing::expect_eq(slurp(target), std::string{"second"});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failure while staging (before publication): old contents stay readable
|
||||||
|
// and intact, and the staging file is cleaned up.
|
||||||
|
{
|
||||||
|
seed(target, "A");
|
||||||
|
Void::FileSystem::ReplaceOptions opts;
|
||||||
|
opts.fault_hook = [](Void::FileSystem::ReplacePhase phase)
|
||||||
|
-> std::optional<int> {
|
||||||
|
if (phase == Void::FileSystem::ReplacePhase::write_stage) {
|
||||||
|
return EIO;
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
auto r =
|
||||||
|
Void::FileSystem::replace_file(target, std::string_view{"B"}, opts);
|
||||||
|
Void::Testing::expect(!r.has_value());
|
||||||
|
Void::Testing::expect(r.error().phase ==
|
||||||
|
Void::FileSystem::ReplacePhase::write_stage);
|
||||||
|
Void::Testing::expect(!r.error().visible_on_disk);
|
||||||
|
Void::Testing::expect(!r.error().durability_unknown);
|
||||||
|
Void::Testing::expect_eq(slurp(target), std::string{"A"});
|
||||||
|
Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failure injected immediately before the publish operation: the old file
|
||||||
|
// must remain completely intact.
|
||||||
|
{
|
||||||
|
seed(target, "A");
|
||||||
|
Void::FileSystem::ReplaceOptions opts;
|
||||||
|
opts.fault_hook = [](Void::FileSystem::ReplacePhase phase)
|
||||||
|
-> std::optional<int> {
|
||||||
|
if (phase == Void::FileSystem::ReplacePhase::rename) {
|
||||||
|
return EIO;
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
auto r =
|
||||||
|
Void::FileSystem::replace_file(target, std::string_view{"B"}, opts);
|
||||||
|
Void::Testing::expect(!r.has_value());
|
||||||
|
Void::Testing::expect(r.error().phase ==
|
||||||
|
Void::FileSystem::ReplacePhase::rename);
|
||||||
|
Void::Testing::expect(!r.error().visible_on_disk);
|
||||||
|
Void::Testing::expect(!r.error().durability_unknown);
|
||||||
|
Void::Testing::expect_eq(slurp(target), std::string{"A"});
|
||||||
|
Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failure after visibility changed: the new file is visible, durability is
|
||||||
|
// explicitly unknown, and the live destination is never deleted.
|
||||||
|
{
|
||||||
|
seed(target, "A");
|
||||||
|
Void::FileSystem::ReplaceOptions opts;
|
||||||
|
opts.fault_hook = [](Void::FileSystem::ReplacePhase phase)
|
||||||
|
-> std::optional<int> {
|
||||||
|
if (phase == Void::FileSystem::ReplacePhase::sync_parent) {
|
||||||
|
return EIO;
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
auto r =
|
||||||
|
Void::FileSystem::replace_file(target, std::string_view{"B"}, opts);
|
||||||
|
Void::Testing::expect(!r.has_value());
|
||||||
|
Void::Testing::expect(r.error().phase ==
|
||||||
|
Void::FileSystem::ReplacePhase::sync_parent);
|
||||||
|
Void::Testing::expect(r.error().visible_on_disk);
|
||||||
|
Void::Testing::expect(r.error().durability_unknown);
|
||||||
|
Void::Testing::expect_eq(slurp(target), std::string{"B"});
|
||||||
|
Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// atomic_write is the convenience wrapper over the same publication path.
|
||||||
|
{
|
||||||
|
auto r = Void::FileSystem::atomic_write(target, "via atomic_write");
|
||||||
|
Void::Testing::expect(r.has_value());
|
||||||
|
Void::Testing::expect_eq(slurp(target), std::string{"via atomic_write"});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unicode destination name (UTF-8 on POSIX, UTF-16 on Windows).
|
||||||
|
{
|
||||||
|
const auto unicode = dir.path / std::filesystem::path{u8"слот-δ.txt"};
|
||||||
|
auto r =
|
||||||
|
Void::FileSystem::replace_file(unicode, std::string_view{"unicode"});
|
||||||
|
Void::Testing::expect(r.has_value());
|
||||||
|
Void::Testing::expect_eq(slurp(unicode), std::string{"unicode"});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Concurrent writers must never expose partial contents and must not leave
|
||||||
|
// staging files behind (exclusive temporary names + atomic publication).
|
||||||
|
Void::Testing::Test replace_file_concurrent_writers_are_atomic()
|
||||||
|
{
|
||||||
|
ScopedTestDir dir{"concurrent"};
|
||||||
|
const auto target = dir.path / "slot.bin";
|
||||||
|
seed(target, "initial");
|
||||||
|
|
||||||
|
std::vector<std::thread> writers;
|
||||||
|
for (int t = 0; t < 4; ++t) {
|
||||||
|
writers.emplace_back([&target, t] {
|
||||||
|
const std::string payload(4096,
|
||||||
|
static_cast<char>('a' + t));
|
||||||
|
for (int i = 0; i < 20; ++i) {
|
||||||
|
(void)Void::FileSystem::replace_file(
|
||||||
|
target, std::string_view{payload});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (auto& writer : writers) {
|
||||||
|
writer.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string content = slurp(target);
|
||||||
|
Void::Testing::expect_eq(content.size(), std::size_t{4096});
|
||||||
|
Void::Testing::expect(content.find_first_not_of(content.front()) ==
|
||||||
|
std::string::npos);
|
||||||
|
Void::Testing::expect_eq(entry_count(dir.path), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Issue #9: read_file_bounded uses one handle, checks the cap before
|
||||||
|
// allocation and again on every chunk, and handles empty/binary/Unicode paths.
|
||||||
|
Void::Testing::Test read_file_bounded_handles_empty_binary_and_limits()
|
||||||
|
{
|
||||||
|
ScopedTestDir dir{"bounded"};
|
||||||
|
|
||||||
|
const auto empty = dir.path / "empty.bin";
|
||||||
|
seed(empty, "");
|
||||||
|
auto empty_result = Void::FileSystem::read_file_bounded(empty);
|
||||||
|
Void::Testing::require(empty_result.has_value());
|
||||||
|
Void::Testing::expect(empty_result->empty());
|
||||||
|
|
||||||
|
const std::string binary{"\x00\x01\x02\xff\x00", 5};
|
||||||
|
const auto binary_path = dir.path / "binary.bin";
|
||||||
|
seed(binary_path, binary);
|
||||||
|
auto binary_result = Void::FileSystem::read_file_bounded(binary_path);
|
||||||
|
Void::Testing::require(binary_result.has_value());
|
||||||
|
Void::Testing::expect_eq(*binary_result, binary);
|
||||||
|
|
||||||
|
const auto unicode = dir.path / std::filesystem::path{u8"данные-δ.bin"};
|
||||||
|
seed(unicode, "unicode payload");
|
||||||
|
auto unicode_result = Void::FileSystem::read_file_bounded(unicode);
|
||||||
|
Void::Testing::require(unicode_result.has_value());
|
||||||
|
Void::Testing::expect_eq(*unicode_result, std::string{"unicode payload"});
|
||||||
|
|
||||||
|
const auto data = dir.path / "data.bin";
|
||||||
|
seed(data, std::string(16, 'x'));
|
||||||
|
|
||||||
|
// Exactly at the limit is accepted.
|
||||||
|
auto exact = Void::FileSystem::read_file_bounded(data, {.max_bytes = 16});
|
||||||
|
Void::Testing::require(exact.has_value());
|
||||||
|
Void::Testing::expect_eq(exact->size(), std::size_t{16});
|
||||||
|
|
||||||
|
// One byte over is rejected by the pre-allocation size check.
|
||||||
|
auto over = Void::FileSystem::read_file_bounded(data, {.max_bytes = 15});
|
||||||
|
Void::Testing::require(!over.has_value());
|
||||||
|
Void::Testing::expect(over.error().message().find("limit") !=
|
||||||
|
std::string::npos);
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
// A stream that keeps producing data after open must be cut off by the
|
||||||
|
// per-chunk check even though it has no initial size to validate.
|
||||||
|
Void::Testing::Test read_file_bounded_rejects_growth_past_limit()
|
||||||
|
{
|
||||||
|
ScopedTestDir dir{"bounded_growth"};
|
||||||
|
const auto fifo = dir.path / "stream";
|
||||||
|
Void::Testing::require(::mkfifo(fifo.c_str(), 0600) == 0);
|
||||||
|
|
||||||
|
std::thread writer{[&fifo] {
|
||||||
|
const int fd = ::open(fifo.c_str(), O_WRONLY);
|
||||||
|
if (fd < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const std::string payload(64, 'z');
|
||||||
|
std::size_t offset = 0;
|
||||||
|
while (offset < payload.size()) {
|
||||||
|
const ssize_t written =
|
||||||
|
::write(fd, payload.data() + offset, payload.size() - offset);
|
||||||
|
if (written <= 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
offset += static_cast<std::size_t>(written);
|
||||||
|
}
|
||||||
|
(void)::close(fd);
|
||||||
|
}};
|
||||||
|
|
||||||
|
auto result = Void::FileSystem::read_file_bounded(fifo, {.max_bytes = 8});
|
||||||
|
writer.join();
|
||||||
|
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().message().find("limit") !=
|
||||||
|
std::string::npos);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
#include <Void/Testing/CompletionObserver.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <future>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using namespace std::chrono_literals;
|
||||||
|
|
||||||
|
[[nodiscard]] std::vector<char> completion_order(char first, char second)
|
||||||
|
{
|
||||||
|
Void::Testing::CompletionGate gate;
|
||||||
|
std::mutex mutex;
|
||||||
|
std::vector<char> order;
|
||||||
|
|
||||||
|
const auto task = [&](char id) {
|
||||||
|
return Void::Testing::observe_completion(
|
||||||
|
[id] { return id; },
|
||||||
|
[&, id] {
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex};
|
||||||
|
order.push_back(id);
|
||||||
|
}
|
||||||
|
gate.arrive();
|
||||||
|
(void)gate.wait_release(5s);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
auto a = task(first);
|
||||||
|
auto b = task(second);
|
||||||
|
auto first_future = std::async(std::launch::async, std::move(a));
|
||||||
|
if (!gate.wait_for(1, 5s)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
auto second_future = std::async(std::launch::async, std::move(b));
|
||||||
|
const bool both = gate.wait_for(2, 5s);
|
||||||
|
gate.release();
|
||||||
|
Void::Testing::expect_eq(first_future.get(), first);
|
||||||
|
Void::Testing::expect_eq(second_future.get(), second);
|
||||||
|
if (!both) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::lock_guard lock{mutex};
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test completion_observer_runs_before_future_ready()
|
||||||
|
{
|
||||||
|
Void::Testing::CompletionGate gate;
|
||||||
|
std::promise<void> observed;
|
||||||
|
auto wrapped = Void::Testing::observe_completion(
|
||||||
|
[] { return 42; },
|
||||||
|
[&] {
|
||||||
|
observed.set_value();
|
||||||
|
(void)gate.wait_release(5s);
|
||||||
|
});
|
||||||
|
|
||||||
|
auto future = std::async(std::launch::async, std::move(wrapped));
|
||||||
|
observed.get_future().wait();
|
||||||
|
// The observer already ran, but the callable has not returned yet.
|
||||||
|
Void::Testing::expect(future.wait_for(0ms) ==
|
||||||
|
std::future_status::timeout);
|
||||||
|
gate.release();
|
||||||
|
Void::Testing::expect_eq(future.get(), 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test completion_observer_preserves_result_categories()
|
||||||
|
{
|
||||||
|
int observed = 0;
|
||||||
|
|
||||||
|
auto void_callable =
|
||||||
|
Void::Testing::observe_completion([] {}, [&] { ++observed; });
|
||||||
|
void_callable();
|
||||||
|
Void::Testing::expect_eq(observed, 1);
|
||||||
|
|
||||||
|
auto move_only = Void::Testing::observe_completion(
|
||||||
|
[] { return std::make_unique<int>(7); },
|
||||||
|
[&] { ++observed; });
|
||||||
|
auto value = move_only();
|
||||||
|
Void::Testing::require(value != nullptr);
|
||||||
|
Void::Testing::expect_eq(*value, 7);
|
||||||
|
Void::Testing::expect_eq(observed, 2);
|
||||||
|
|
||||||
|
int storage = 5;
|
||||||
|
auto reference = Void::Testing::observe_completion(
|
||||||
|
[&]() -> int& { return storage; }, [] {});
|
||||||
|
int& ref = reference();
|
||||||
|
ref = 9;
|
||||||
|
Void::Testing::expect_eq(storage, 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test completion_observer_forwards_exceptions()
|
||||||
|
{
|
||||||
|
int observed = 0;
|
||||||
|
auto throwing = Void::Testing::observe_completion(
|
||||||
|
[]() -> int { throw std::runtime_error{"boom"}; },
|
||||||
|
[&] { ++observed; });
|
||||||
|
|
||||||
|
bool caught = false;
|
||||||
|
try {
|
||||||
|
(void)throwing();
|
||||||
|
} catch (const std::runtime_error&) {
|
||||||
|
caught = true;
|
||||||
|
}
|
||||||
|
Void::Testing::expect(caught);
|
||||||
|
Void::Testing::expect_eq(observed, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test completion_gate_release_and_timeout()
|
||||||
|
{
|
||||||
|
Void::Testing::CompletionGate gate;
|
||||||
|
Void::Testing::expect(!gate.wait_release(5ms));
|
||||||
|
gate.arrive();
|
||||||
|
Void::Testing::expect(gate.wait_for(1, 5ms));
|
||||||
|
Void::Testing::expect(!gate.wait_for(2, 5ms));
|
||||||
|
gate.release();
|
||||||
|
Void::Testing::expect(gate.wait_release(5ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test completion_order_is_deterministic()
|
||||||
|
{
|
||||||
|
Void::Testing::expect(completion_order('A', 'B') ==
|
||||||
|
std::vector<char>{'A', 'B'});
|
||||||
|
Void::Testing::expect(completion_order('B', 'A') ==
|
||||||
|
std::vector<char>{'B', 'A'});
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
#include <Void/Update/Resolver.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <tuple>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Update::PackageDependency;
|
||||||
|
using Void::Update::PackageDescription;
|
||||||
|
using Void::Update::Resolution;
|
||||||
|
using Void::Update::ResolutionDiagnostic;
|
||||||
|
using Void::Update::ResolutionRequest;
|
||||||
|
using Void::Semver::Version;
|
||||||
|
|
||||||
|
[[nodiscard]] Version version(std::string_view text)
|
||||||
|
{
|
||||||
|
return *Void::Semver::parse_strict(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] PackageDependency dependency(std::string_view id,
|
||||||
|
std::string_view range)
|
||||||
|
{
|
||||||
|
auto parsed = Void::Update::make_package_dependency(std::string{id}, range);
|
||||||
|
return *parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] PackageDescription package(
|
||||||
|
std::string id,
|
||||||
|
std::string_view version_text,
|
||||||
|
std::string digest,
|
||||||
|
std::vector<std::string> capabilities = {},
|
||||||
|
std::vector<PackageDependency> dependencies = {})
|
||||||
|
{
|
||||||
|
return PackageDescription{.id = std::move(id),
|
||||||
|
.version = version(version_text),
|
||||||
|
.content_digest = std::move(digest),
|
||||||
|
.capabilities = std::move(capabilities),
|
||||||
|
.dependencies = std::move(dependencies)};
|
||||||
|
}
|
||||||
|
|
||||||
|
using Summary = std::tuple<std::string, std::string, std::string>;
|
||||||
|
|
||||||
|
[[nodiscard]] std::vector<Summary> summarize(const Resolution& resolution)
|
||||||
|
{
|
||||||
|
std::vector<Summary> out;
|
||||||
|
for (const auto& entry : resolution.packages) {
|
||||||
|
out.emplace_back(entry.identity.id,
|
||||||
|
entry.identity.version.to_string(),
|
||||||
|
entry.identity.content_digest);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::vector<std::string> selected(std::initializer_list<const char*> ids)
|
||||||
|
{
|
||||||
|
std::vector<std::string> out;
|
||||||
|
for (const char* id : ids) {
|
||||||
|
out.push_back(id);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_transitive_closure()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("app", "1.0.0", "d-app", {}, {dependency("lib", "^1.0")}),
|
||||||
|
package("lib", "1.0.0", "d-lib-1"),
|
||||||
|
package("lib", "1.1.0", "d-lib-2"),
|
||||||
|
package("lib", "2.0.0", "d-lib-3"),
|
||||||
|
};
|
||||||
|
auto roots = selected({"app"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(result.has_value());
|
||||||
|
const auto summary = summarize(*result);
|
||||||
|
Void::Testing::require(summary.size() == 2);
|
||||||
|
Void::Testing::expect_eq(std::get<0>(summary[0]), std::string{"app"});
|
||||||
|
Void::Testing::expect_eq(std::get<0>(summary[1]), std::string{"lib"});
|
||||||
|
Void::Testing::expect_eq(std::get<1>(summary[1]), std::string{"1.1.0"});
|
||||||
|
Void::Testing::expect_eq(std::get<2>(summary[1]), std::string{"d-lib-2"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_is_order_invariant()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("app", "1.0.0", "d-app", {}, {dependency("lib", "^1.0")}),
|
||||||
|
package("lib", "1.0.0", "d-lib-1"),
|
||||||
|
package("lib", "1.1.0", "d-lib-2"),
|
||||||
|
};
|
||||||
|
auto roots = selected({"app"});
|
||||||
|
const auto first = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
std::reverse(installed.begin(), installed.end());
|
||||||
|
const auto second = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(first.has_value() && second.has_value());
|
||||||
|
Void::Testing::expect(summarize(*first) == summarize(*second));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_missing_dependency()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("app", "1.0.0", "d-app", {}, {dependency("gone", "^1.0")})};
|
||||||
|
auto roots = selected({"app"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::missing_dependency);
|
||||||
|
Void::Testing::expect_eq(result.error().package, std::string{"app"});
|
||||||
|
Void::Testing::expect_eq(result.error().field,
|
||||||
|
std::string{"dependencies[0].range"});
|
||||||
|
Void::Testing::expect_eq(result.error().related, std::string{"gone"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_incompatible_version()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("app", "1.0.0", "d-app", {}, {dependency("lib", "^2.0")}),
|
||||||
|
package("lib", "1.0.0", "d-lib")};
|
||||||
|
auto roots = selected({"app"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::incompatible_version);
|
||||||
|
Void::Testing::expect_eq(result.error().related, std::string{"lib"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_backtracks_for_constraints()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("app", "1.0.0", "d-app", {}, {dependency("lib", "=1.0.0")}),
|
||||||
|
package("lib", "1.0.0", "d-lib-1"),
|
||||||
|
package("lib", "1.1.0", "d-lib-2")};
|
||||||
|
auto roots = selected({"app", "lib"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(result.has_value());
|
||||||
|
const auto summary = summarize(*result);
|
||||||
|
Void::Testing::require(summary.size() == 2);
|
||||||
|
Void::Testing::expect_eq(std::get<1>(summary[1]), std::string{"1.0.0"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_detects_cycle()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("a", "1.0.0", "d-a", {}, {dependency("b", "*")}),
|
||||||
|
package("b", "1.0.0", "d-b", {}, {dependency("a", "*")})};
|
||||||
|
auto roots = selected({"a"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::cyclic_dependency);
|
||||||
|
Void::Testing::expect_eq(result.error().related, std::string{"a -> b -> a"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_rejects_ambiguous_identity()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("lib", "1.0.0+one", "d-one"),
|
||||||
|
package("lib", "1.0.0+two", "d-two")};
|
||||||
|
auto roots = selected({"lib"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::ambiguous_package);
|
||||||
|
Void::Testing::expect_eq(result.error().package, std::string{"lib"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_rejects_competing_exclusive_capabilities()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("gpu-a", "1.0.0", "d-a", {"gpu"}),
|
||||||
|
package("gpu-b", "1.0.0", "d-b", {"gpu"})};
|
||||||
|
auto roots = selected({"gpu-a", "gpu-b"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(
|
||||||
|
result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::exclusive_capability_conflict);
|
||||||
|
Void::Testing::expect_eq(result.error().package, std::string{"gpu-a"});
|
||||||
|
Void::Testing::expect_eq(result.error().related, std::string{"gpu-b"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_frozen_identity_includes_build_and_digest()
|
||||||
|
{
|
||||||
|
const Void::Update::PackageIdentity base{.id = "lib",
|
||||||
|
.version = version("1.0.0+build.1"),
|
||||||
|
.content_digest = "sha256:a"};
|
||||||
|
auto changed_build = base;
|
||||||
|
changed_build.version = version("1.0.0+build.2");
|
||||||
|
auto changed_digest = base;
|
||||||
|
changed_digest.content_digest = "sha256:b";
|
||||||
|
|
||||||
|
Void::Testing::expect(!(base == changed_build));
|
||||||
|
Void::Testing::expect(!(base == changed_digest));
|
||||||
|
Void::Testing::expect(base == base);
|
||||||
|
// SemVer precedence alone treats both as equal; the frozen identity must not.
|
||||||
|
Void::Testing::expect((base.version <=> changed_build.version) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_same_precedence_distinct_digest_is_ambiguous()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("lib", "1.0.0+build.1", "sha256:a"),
|
||||||
|
package("lib", "1.0.0+build.1", "sha256:b")};
|
||||||
|
auto roots = selected({"lib"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::ambiguous_package);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_rejects_empty_fields()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("lib", "1.0.0", "")};
|
||||||
|
auto roots = selected({"lib"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::invalid_request);
|
||||||
|
Void::Testing::expect_eq(result.error().field,
|
||||||
|
std::string{"content_digest"});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_enforces_package_limit()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("app", "1.0.0", "d-app", {}, {dependency("lib", "*")}),
|
||||||
|
package("lib", "1.0.0", "d-lib")};
|
||||||
|
auto roots = selected({"app"});
|
||||||
|
Void::Update::ResolutionLimits limits;
|
||||||
|
limits.max_packages = 1;
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed,
|
||||||
|
.selected = roots,
|
||||||
|
.limits = limits});
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect(result.error().kind ==
|
||||||
|
Void::Update::ResolutionErrorKind::limit_exceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test resolve_packages_deduplicates_identical_descriptions()
|
||||||
|
{
|
||||||
|
std::vector<PackageDescription> installed{
|
||||||
|
package("lib", "1.0.0", "d-lib"),
|
||||||
|
package("lib", "1.0.0", "d-lib")};
|
||||||
|
auto roots = selected({"lib"});
|
||||||
|
auto result = Void::Update::resolve_packages(
|
||||||
|
ResolutionRequest{.installed = installed, .selected = roots});
|
||||||
|
Void::Testing::require(result.has_value());
|
||||||
|
Void::Testing::expect_eq(result->packages.size(), std::size_t{1});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user