Compare commits
11
Commits
build-vbs
...
3cade95a32
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cade95a32 | ||
|
|
dceca1f207 | ||
|
|
a4851c2c20 | ||
|
|
7232fa4ba5 | ||
|
|
f2b002eb26 | ||
|
|
ed3fbc677a | ||
|
|
afd4d99a2d | ||
|
|
f8eca20ef5 | ||
|
|
37c3cd4383 | ||
|
|
9d899cc949 | ||
|
|
d30384d981 |
No files matched your search
@@ -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,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
|
||||
@@ -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,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,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,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});
|
||||
}
|
||||
@@ -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,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