Integrate session-scoped command dispatch into M01
This commit is contained in:
commit
645abefac5
6 files changed
+709
-2
No files matched your search
@@ -0,0 +1,133 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t command_envelope_version = 1;
|
||||
|
||||
struct SessionIdentity {
|
||||
Void::Uuid::Uuid world;
|
||||
Void::Uuid::Uuid session;
|
||||
std::uint64_t city = 1;
|
||||
bool operator==(const SessionIdentity&) const = default;
|
||||
};
|
||||
|
||||
// Created by the trusted transport/local adapter, never decoded from payload data.
|
||||
// Reconnected clients keep their assigned slot within the same session.
|
||||
struct TrustedClient {
|
||||
std::uint8_t player;
|
||||
};
|
||||
|
||||
struct CommandPayload {
|
||||
CommandKind kind = CommandKind::PlaceBed;
|
||||
GridPosition cell{};
|
||||
std::uint8_t value = 0;
|
||||
GridPosition destination{};
|
||||
AgentId resident = 0;
|
||||
bool operator==(const CommandPayload&) const = default;
|
||||
};
|
||||
|
||||
struct LegacyCabinPayload {
|
||||
GridPosition cell;
|
||||
GridPosition sawmill;
|
||||
GridPosition stonecutter;
|
||||
bool operator==(const LegacyCabinPayload&) const = default;
|
||||
};
|
||||
|
||||
using SessionPayload = std::variant<CommandPayload, LegacyCabinPayload>;
|
||||
|
||||
struct CommandEnvelope {
|
||||
std::uint32_t version = command_envelope_version;
|
||||
Void::Uuid::Uuid world;
|
||||
Void::Uuid::Uuid session;
|
||||
std::uint64_t city = 1;
|
||||
std::uint64_t request = 0;
|
||||
SessionPayload payload;
|
||||
};
|
||||
|
||||
enum class DispatchStatus : std::uint8_t {
|
||||
Completed,
|
||||
UnsupportedVersion,
|
||||
WrongWorld,
|
||||
StaleSession,
|
||||
UnauthorizedClient,
|
||||
InvalidRequest,
|
||||
OutOfOrder,
|
||||
Conflict,
|
||||
Busy,
|
||||
Faulted
|
||||
};
|
||||
|
||||
struct DispatchReceipt {
|
||||
DispatchStatus status;
|
||||
// Meaningful for Completed. Revision counts successful dispatcher mutations
|
||||
// in this session, including legacy cabin placement, independently of ticks.
|
||||
CommandStatus command_status = CommandStatus::Unavailable;
|
||||
std::uint64_t tick = 0;
|
||||
std::uint64_t revision = 0;
|
||||
bool operator==(const DispatchReceipt&) const = default;
|
||||
};
|
||||
|
||||
enum class CommandMutationPhase : std::uint8_t { BeforeMutation, AfterMutation };
|
||||
|
||||
struct CommandDispatcherOptions {
|
||||
std::size_t max_receipts_per_client = 65'536;
|
||||
// Optional failure observer around authoritative application. An exception
|
||||
// fences the staged dispatcher, so the owner must discard its candidate.
|
||||
void (*mutation_observer)(CommandMutationPhase) = nullptr;
|
||||
};
|
||||
|
||||
// Single-owner component. The caller must pass the session's authoritative World.
|
||||
// Exact repeats retain their original result for the entire session. At capacity,
|
||||
// new requests receive Busy and stored receipts remain available. No eviction.
|
||||
// Domain rejections consume a request number; transient dispatch errors do not.
|
||||
// Copies may be staged with a candidate World and committed only after publication.
|
||||
// Any mutation exception poisons this instance. Old completed receipts remain
|
||||
// readable, while further effects require a newly constructed session/dispatcher.
|
||||
// Upstream replacement contract and tests: Void/Library#6
|
||||
// https://git.faumaray.com/Void/Library/issues/6
|
||||
class CommandDispatcher {
|
||||
public:
|
||||
explicit CommandDispatcher(SessionIdentity identity, CommandDispatcherOptions options = {});
|
||||
|
||||
[[nodiscard]] const SessionIdentity& identity() const noexcept { return identity_; }
|
||||
[[nodiscard]] std::uint64_t revision() const noexcept { return revision_; }
|
||||
[[nodiscard]] bool faulted() const noexcept { return faulted_; }
|
||||
[[nodiscard]] std::size_t receipt_count(TrustedClient client) const noexcept;
|
||||
[[nodiscard]] std::uint64_t next_request(TrustedClient client) const noexcept;
|
||||
|
||||
[[nodiscard]] DispatchReceipt dispatch(World& world, TrustedClient client, const CommandEnvelope& command);
|
||||
// Invalid context/conflicting reuse returns its dispatch error. An otherwise
|
||||
// valid request without a retained receipt returns nullopt without side effects.
|
||||
[[nodiscard]] std::optional<DispatchReceipt> lookup(TrustedClient client, const CommandEnvelope& command) const;
|
||||
|
||||
private:
|
||||
struct Record {
|
||||
std::uint64_t city;
|
||||
SessionPayload payload;
|
||||
DispatchReceipt receipt{DispatchStatus::Faulted};
|
||||
bool completed = false;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::optional<DispatchStatus> validate_context(
|
||||
TrustedClient client, const CommandEnvelope& command) const noexcept;
|
||||
[[nodiscard]] CommandStatus apply(World& world, TrustedClient client, const CommandEnvelope& command);
|
||||
|
||||
SessionIdentity identity_;
|
||||
CommandDispatcherOptions options_;
|
||||
std::array<std::vector<Record>, colony_player_slots> records_;
|
||||
std::uint64_t revision_ = 0;
|
||||
bool faulted_ = false;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,113 @@
|
||||
#include "settlement/core/command_dispatcher.hpp"
|
||||
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
|
||||
bool valid_client(TrustedClient client) noexcept {
|
||||
return client.player >= colony_host && client.player <= colony_player_slots;
|
||||
}
|
||||
|
||||
std::size_t client_index(TrustedClient client) noexcept {
|
||||
return static_cast<std::size_t>(client.player - colony_host);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
CommandDispatcher::CommandDispatcher(SessionIdentity identity, CommandDispatcherOptions options)
|
||||
: identity_(identity), options_(options) {
|
||||
if (identity.world.is_nil() || identity.session.is_nil() || identity.city == 0) {
|
||||
throw std::invalid_argument("command dispatcher requires nonnil world/session and a city");
|
||||
}
|
||||
if (options.max_receipts_per_client == 0 ||
|
||||
options.max_receipts_per_client >= std::numeric_limits<std::uint64_t>::max()) {
|
||||
throw std::invalid_argument("receipt capacity must be positive and leave a next request number");
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t CommandDispatcher::receipt_count(TrustedClient client) const noexcept {
|
||||
return valid_client(client) ? records_[client_index(client)].size() : 0;
|
||||
}
|
||||
|
||||
std::uint64_t CommandDispatcher::next_request(TrustedClient client) const noexcept {
|
||||
if (!valid_client(client)) return 0;
|
||||
return static_cast<std::uint64_t>(records_[client_index(client)].size()) + 1;
|
||||
}
|
||||
|
||||
std::optional<DispatchStatus> CommandDispatcher::validate_context(
|
||||
TrustedClient client, const CommandEnvelope& command) const noexcept {
|
||||
if (!valid_client(client)) return DispatchStatus::UnauthorizedClient;
|
||||
if (command.version != command_envelope_version) return DispatchStatus::UnsupportedVersion;
|
||||
if (command.world.is_nil() || command.world != identity_.world) return DispatchStatus::WrongWorld;
|
||||
if (command.session.is_nil() || command.session != identity_.session) return DispatchStatus::StaleSession;
|
||||
if (command.request == 0) return DispatchStatus::InvalidRequest;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<DispatchReceipt> CommandDispatcher::lookup(
|
||||
TrustedClient client, const CommandEnvelope& command) const {
|
||||
if (const auto invalid = validate_context(client, command)) return DispatchReceipt{*invalid};
|
||||
const auto& records = records_[client_index(client)];
|
||||
if (command.request > records.size()) return std::nullopt;
|
||||
const auto& record = records[static_cast<std::size_t>(command.request - 1)];
|
||||
if (command.city != record.city || command.payload != record.payload) {
|
||||
return DispatchReceipt{DispatchStatus::Conflict};
|
||||
}
|
||||
return record.completed ? record.receipt : DispatchReceipt{DispatchStatus::Faulted};
|
||||
}
|
||||
|
||||
CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const CommandEnvelope& command) {
|
||||
if (command.city != identity_.city) return CommandStatus::Unauthorized;
|
||||
if (const auto* payload = std::get_if<CommandPayload>(&command.payload)) {
|
||||
if (payload->kind > CommandKind::CraftFurniture) return CommandStatus::InvalidTarget;
|
||||
if (payload->kind == CommandKind::PlaceRoom) {
|
||||
const auto inside = [&world](GridPosition cell) {
|
||||
return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height();
|
||||
};
|
||||
// Legacy room-size arithmetic assumes coordinates belong to this map.
|
||||
if (!inside(payload->cell) || !inside(payload->destination)) return CommandStatus::InvalidTarget;
|
||||
}
|
||||
return world.apply_command({client.player, world.next_command_sequence(client.player), payload->kind,
|
||||
payload->cell, payload->value, payload->destination, payload->resident}).status;
|
||||
}
|
||||
|
||||
if (client.player != colony_host) return CommandStatus::Unauthorized;
|
||||
if (world.scenario_active()) return CommandStatus::Unavailable;
|
||||
const auto& payload = std::get<LegacyCabinPayload>(command.payload);
|
||||
try {
|
||||
world.queue_cabin(payload.cell, payload.sawmill, payload.stonecutter);
|
||||
} catch (const std::invalid_argument&) {
|
||||
return CommandStatus::InvalidTarget;
|
||||
}
|
||||
return CommandStatus::Accepted;
|
||||
}
|
||||
|
||||
DispatchReceipt CommandDispatcher::dispatch(World& world, TrustedClient client, const CommandEnvelope& command) {
|
||||
if (const auto recorded = lookup(client, command)) return *recorded;
|
||||
if (faulted_) return {DispatchStatus::Faulted};
|
||||
auto& records = records_[client_index(client)];
|
||||
if (command.request != next_request(client)) return {DispatchStatus::OutOfOrder};
|
||||
if (records.size() == options_.max_receipts_per_client ||
|
||||
revision_ == std::numeric_limits<std::uint64_t>::max()) return {DispatchStatus::Busy};
|
||||
|
||||
// All record allocation/copy work happens before the authoritative mutation.
|
||||
// An exceptional effect leaves this entry incomplete and fences further work.
|
||||
records.push_back(Record{command.city, command.payload});
|
||||
auto& record = records.back();
|
||||
try {
|
||||
if (options_.mutation_observer) options_.mutation_observer(CommandMutationPhase::BeforeMutation);
|
||||
const auto status = apply(world, client, command);
|
||||
if (options_.mutation_observer) options_.mutation_observer(CommandMutationPhase::AfterMutation);
|
||||
if (status == CommandStatus::Accepted) ++revision_;
|
||||
record.receipt = {DispatchStatus::Completed, status, world.tick(), revision_};
|
||||
record.completed = true;
|
||||
} catch (...) {
|
||||
faulted_ = true;
|
||||
throw;
|
||||
}
|
||||
return record.receipt;
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
Reference in new issue
Block a user