Serve legacy LAN clients through the authoritative runtime

This commit is contained in:
faumaray committed 2026-12-02 22:13:39 +03:00
1 parent 8c4c1fe235
commit 09545bfe85
5 files changed
+576 -31

No files matched your search

+18
View File
@@ -7,6 +7,8 @@
#include <optional>
#include <string>
namespace settlement { class SimulationRuntime; }
namespace settlement::viewer {
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
@@ -20,6 +22,15 @@ struct LanRejection {
GridPosition destination;
};
struct LanCommandResult {
CommandStatus status;
CommandKind kind;
GridPosition cell;
std::uint8_t value;
GridPosition destination;
AgentId resident;
};
class LanSession {
public:
LanSession();
@@ -39,7 +50,14 @@ public:
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
GridPosition destination = {}, AgentId resident = 0);
[[nodiscard]] std::optional<LanRejection> take_rejection() noexcept;
// poll_guest pauses further sends until this one retained result is drained.
[[nodiscard]] std::optional<LanCommandResult> take_result() noexcept;
[[nodiscard]] std::unique_ptr<World> poll(World& world);
// Protocol 11 accepts the compiled default rules and a 32x32 active colony.
// Calls never wait for the owner. An admitted guest operation survives peer
// turnover, so poll_host must continue with the same owner until it settles.
void poll_host(SimulationRuntime& runtime);
[[nodiscard]] std::unique_ptr<World> poll_guest();
private:
struct Impl;
+180 -31
View File
@@ -6,6 +6,7 @@
#include "lan_session.hpp"
#include "lan_wire.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <algorithm>
#include <array>
@@ -153,6 +154,12 @@ struct Action {
} // namespace
struct LanSession::Impl {
struct PendingCommand {
std::future<RuntimeResult> completion;
Void::Uuid::Uuid session;
std::uint64_t peer_generation;
};
bool winsock = false;
Socket listener;
Channel peer;
@@ -167,12 +174,18 @@ struct LanSession::Impl {
std::string notice;
std::deque<Action> actions;
std::optional<LanRejection> rejected_command;
std::optional<LanCommandResult> command_result;
bool result_backpressure = false;
std::uint64_t guest_sequence = 0;
Clock::time_point last_ping{};
Clock::time_point last_snapshot{};
std::uint64_t sent_tick = 0;
std::uint64_t sent_host_sequence = 0;
std::uint64_t sent_guest_sequence = 0;
std::uint64_t peer_generation = 0;
std::optional<Void::Uuid::Uuid> runtime_session;
std::optional<RulesManifest> compatibility_rules;
std::optional<PendingCommand> pending_command;
Impl() {
WSADATA data{};
@@ -185,14 +198,18 @@ struct LanSession::Impl {
}
void drop_peer() noexcept {
++peer_generation;
peer = Channel{};
connecting = authenticated = reject_pending = false;
awaiting_receipt.reset();
guest_sequence = 0;
actions.clear();
rejected_command.reset();
command_result.reset();
last_snapshot = {};
last_ping = {};
// pending_command belongs to the authenticated guest slot, even after
// its socket disappears. A later peer waits for this result to settle.
}
void accept_guest() {
@@ -223,17 +240,21 @@ struct LanSession::Impl {
connecting = false;
}
void authenticate(Message message, std::string_view payload) {
if (reject_pending) return;
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
peer.queue(Message::Reject);
reject_pending = true;
return;
}
authenticated = true;
notice.clear();
}
void handle_host(World& world, Message message, std::string_view payload) {
if (!authenticated) {
if (reject_pending) return;
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
peer.queue(Message::Reject);
reject_pending = true;
return;
}
authenticated = true;
notice.clear();
authenticate(message, payload);
return;
}
if (message == Message::Ping && payload.empty()) return;
@@ -244,6 +265,83 @@ struct LanSession::Impl {
peer.queue(Message::Receipt, std::string_view(reply));
}
void reply(CommandStatus status, const World& world) {
const auto bytes = lan_wire::encode_receipt({status, world.next_command_sequence(guest_player)});
peer.queue(Message::Receipt, std::string_view(bytes));
}
void handle_runtime_host(SimulationRuntime& runtime, const PublishedSnapshot& snapshot,
Message message, std::string_view payload) {
if (!authenticated) {
authenticate(message, payload);
return;
}
if (message == Message::Ping && payload.empty()) return;
const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt;
if (!command) throw std::runtime_error("Invalid guest command.");
if (pending_command) throw std::runtime_error("A guest command is already pending.");
if (command->sequence != snapshot.world->next_command_sequence(guest_player)) {
reply(CommandStatus::WrongSequence, *snapshot.world);
return;
}
const auto& identity = snapshot.identity;
const CommandEnvelope envelope{
command_envelope_version, identity.world, identity.session, identity.city,
snapshot.next_requests[guest_player - 1],
CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident}
};
auto submitted = runtime.try_submit({guest_player}, envelope);
if (submitted.admission == RuntimeAdmission::Accepted) {
pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation);
} else if (submitted.admission == RuntimeAdmission::Busy) {
reply(CommandStatus::Busy, *snapshot.world);
} else {
throw std::runtime_error("The authoritative owner cannot accept guest commands.");
}
}
void complete_runtime_command() {
if (!pending_command || pending_command->completion.wait_for(0s) != std::future_status::ready) return;
auto pending = std::move(*pending_command);
pending_command.reset();
const auto result = pending.completion.get();
if (pending.peer_generation != peer_generation || !authenticated ||
!runtime_session || pending.session != *runtime_session) return;
if (result.outcome != RuntimeOutcome::Completed || !result.receipt || !result.snapshot ||
result.snapshot->identity.session != pending.session) {
throw std::runtime_error("The authoritative guest command did not commit.");
}
const auto& receipt = *result.receipt;
if (receipt.status == DispatchStatus::Completed) {
reply(receipt.command_status, *result.snapshot->world);
} else if (receipt.status == DispatchStatus::Busy) {
reply(CommandStatus::Busy, *result.snapshot->world);
} else {
throw std::runtime_error("The guest command belongs to an obsolete or conflicting request.");
}
}
void bind_runtime(const RuntimeView& view) {
if (!compatibility_rules) {
auto rules = default_rules_manifest();
if (!rules) throw std::runtime_error("Could not resolve the legacy LAN rules.");
compatibility_rules = std::move(*rules);
}
if (view.state != RuntimeState::Running || !view.snapshot) {
throw std::runtime_error("The authoritative owner is unavailable.");
}
const auto& snapshot = *view.snapshot;
if (!snapshot.rules || *snapshot.rules != *compatibility_rules) {
throw std::runtime_error("Protocol 11 requires the compiled default rules.");
}
if (!snapshot.world->scenario_active() || snapshot.world->width() != first_colony_map_size ||
snapshot.world->height() != first_colony_map_size) {
throw std::runtime_error("Protocol 11 requires a supported 32x32 colony.");
}
if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer();
runtime_session = snapshot.identity.session;
}
void handle_guest(std::unique_ptr<World>& latest, Message message, std::string_view payload) {
if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version.");
if (message == Message::Snapshot) {
@@ -264,6 +362,8 @@ struct LanSession::Impl {
}
const auto status = receipt->status;
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
command_result = LanCommandResult{status, awaiting_receipt->kind, awaiting_receipt->cell,
awaiting_receipt->value, awaiting_receipt->destination, awaiting_receipt->resident};
if (status != CommandStatus::Accepted) {
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell,
awaiting_receipt->value, awaiting_receipt->destination};
@@ -291,6 +391,7 @@ struct LanSession::Impl {
void send_action() {
if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return;
if (result_backpressure && command_result) return;
const Action action = actions.front();
const auto payload = lan_wire::encode_command(
{guest_player, guest_sequence, action.kind, action.cell, action.value, action.destination, action.resident});
@@ -298,6 +399,31 @@ struct LanSession::Impl {
actions.pop_front();
awaiting_receipt = action;
}
template<class Receive, class SendHost>
void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) {
if (listener && accept_allowed) accept_guest();
if (!peer.socket) return;
const auto now = Clock::now();
if ((!authenticated && now - peer.opened > 8s) ||
(authenticated && now - peer.last_received > 15s)) {
throw std::runtime_error("The peer did not respond.");
}
if (connecting) finish_connection();
if (connecting) return;
peer.receive(receive);
if (authenticated && guest) {
send_action();
if (!peer.pending() && now - last_ping >= 2s) {
peer.queue(Message::Ping);
last_ping = now;
}
} else if (authenticated) {
send_host(now);
}
peer.flush();
if (reject_pending && !peer.pending()) drop_peer();
}
};
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
@@ -397,34 +523,57 @@ std::optional<LanRejection> LanSession::take_rejection() noexcept {
return std::exchange(impl_->rejected_command, std::nullopt);
}
std::optional<LanCommandResult> LanSession::take_result() noexcept {
return std::exchange(impl_->command_result, std::nullopt);
}
std::unique_ptr<World> LanSession::poll(World& world) {
auto& connection = *impl_;
connection.result_backpressure = false;
std::unique_ptr<World> latest;
try {
if (connection.listener) connection.accept_guest();
if (!connection.peer.socket) return nullptr;
const auto now = Clock::now();
if ((!connection.authenticated && now - connection.peer.opened > 8s) ||
(connection.authenticated && now - connection.peer.last_received > 15s)) {
throw std::runtime_error("The peer did not respond.");
}
if (connection.connecting) connection.finish_connection();
if (connection.connecting) return nullptr;
connection.peer.receive([&](Message message, std::string_view payload) {
if (connection.pending_command) throw std::runtime_error("Continue polling the authoritative owner.");
connection.poll_network([&](Message message, std::string_view payload) {
if (connection.guest) connection.handle_guest(latest, message, payload);
else connection.handle_host(world, message, payload);
});
if (connection.authenticated && connection.guest) {
connection.send_action();
if (!connection.peer.pending() && now - connection.last_ping >= 2s) {
connection.peer.queue(Message::Ping);
connection.last_ping = now;
}
} else if (connection.authenticated) {
connection.send_snapshot(world, now);
}
connection.peer.flush();
if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer();
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); });
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
latest.reset();
}
return latest;
}
void LanSession::poll_host(SimulationRuntime& runtime) {
auto& connection = *impl_;
if (!connection.listener || connection.guest) return;
try {
connection.complete_runtime_command();
// Completion may have published a newer next-request number. Re-read it
// before admitting a reconnect or decoding any further guest intent.
const auto view = runtime.view();
connection.bind_runtime(view);
connection.poll_network([&](Message message, std::string_view payload) {
connection.handle_runtime_host(runtime, *view.snapshot, message, payload);
}, [&](Clock::time_point now) {
if (!connection.pending_command) connection.send_snapshot(*view.snapshot->world, now);
}, !connection.pending_command);
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
}
}
std::unique_ptr<World> LanSession::poll_guest() {
auto& connection = *impl_;
connection.result_backpressure = true;
std::unique_ptr<World> latest;
if (!connection.guest) return nullptr;
try {
connection.poll_network([&](Message message, std::string_view payload) {
connection.handle_guest(latest, message, payload);
}, [](Clock::time_point) {});
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
+50
View File
@@ -0,0 +1,50 @@
# Serve compatible LAN clients from the immutable authoritative runtime
Task ID: S16-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16, system/s16-authority fast-forwarded to 8c4c1fe. Existing LanSession::poll(World&) protocol11 is tested (4 cases/baseline binary interop). Runtime and command dispatcher new headers exist. M01-F4 identified manifest and outstanding-command reconnect gates, included below.
## 2. Objective and deliverables
Add production host polling that consumes immutable runtime views and submits authenticated guest actions to the owner asynchronously. Add guest-only polling usable by a view-only client, preserve current hardcoded two slots and old packet format.
## 3. Scope and non-goals
Legacy LAN11 compatibility adapter and actual loopback tests. No public new protocol/version or remote rollout, no new internet exposure. Preserve existing poll(World&) entry/fixtures for old API clients. Viewer source is owned separately.
## 4. Files to inspect
Inspect app/lan_session.hpp, app/lan_session_win32.cpp, app/lan_wire.hpp/.cpp, tests/lan_tests.cpp, simulation_runtime.hpp, command_dispatcher.hpp, world.hpp, rules_manifest.hpp, docs/plan/systems/S16.md. Read /tmp/stoneheart-verify.KoZwE4o8/interop.cpp/.py for existing binary interop.
## 5. Write ownership and coordination
Write scope: app/lan_session.hpp; app/lan_session_win32.cpp; tests/lan_tests.cpp; docs/plan/systems/S16.md
If an identified shared codec change is necessary, contact root first; no data layout redesign. Other workers own Win32 viewer/core. You are not alone, do not change Git/Serena/other worktrees.
## 6. Implementation or investigation approach
NEW poll_host(SimulationRuntime&) and poll_guest() (or equally explicit) for real viewer. Wire11 Hello carries no manifest/epoch, so allow ONLY default compatibility manifest (verified frozen identity); close incompatible connection before exposing a snapshot/command. Bind host session incarnation; detecting replacement drops peer & requires new hello before serving new world. Existing TCP framing/auth and slot validation retained. Read current immutable published World and prepare v13 snapshots with current bounds. No direct mutation in new host path. Screen sends one action at a time; bound hostile/pipelined volume, keep pings/timeouts/disconnect progress, never wait on a long owner while polling socket. Serialize one outstanding valid command per authenticated guest slot.
## 7. Interfaces and data contracts
Wire request IDs are legacy World::next_command_sequence(guest), only accepted gameplay increments them. Modern envelope number from committed PublishedSnapshot::next_requests[guest] also advances on domain rejection. Precheck wire sequence without mutating state; old wrong-sequence -> expected number. Submit trusted guest=2, verified UUIDs/world/city/version, exact payload; report the correct legacy result and next wire sequence only from corresponding committed runtime result. Reject unsupported actions using existing authority. Track one outstanding admitted operation across TCP disconnect/rebind; suppress old-connection replies by connection generation, hold/reconcile its completion before next guest's sequence or authentication/publication is used, prevent reusing in-flight modern request number. On epoch change fence old future before new peer bind. No borrowed runtime pointer persisted. Expose status to viewer on incompatible rules/fault. Send early public signatures.
## 8. Dependencies and integration
Root owns actual Win32 viewer integration. Runtime consumers now available at baseline; old standalone overload remains tested. Add only in-process loopback tests using random port/loopback flag. Reuse existing socket implementation and avoid duplicate dispatch/snapshot logic. Legacy reader file/body remains format13 and lower limits; world with unsupported future schema must be rejected explicitly in later change.
## 9. Edge cases security and performance
On Busy/Closed/Faulted/superseded/out-of-order preserve protocol-correct old next id and prevent lost reported effects. Guest can correct a rejected action using same old number. Do not retain retired peer's optimistic blueprint metadata. Check long owner tick does not block server pings/poll; settled work from old peer cannot reply to a new one. Enforce bounded admission and no logs of join codes. Test a publication at same tick.
## 10. Acceptance criteria
1. Old-style genuine guest joins runtime-owned host and receives actual committed world; user action, domain rejection and corrected next command preserve legacy sequences. 2. Deliberately blocked/delayed command, disconnect/reconnect, no old receipt to new peer, sequential guest slot safely resumes. 3. New epoch and non-default manifest refuse or reauthenticate before any legacy snapshot. 4. Both existing LAN11 fixtures and old API work; deterministic cross-version loopback including old guest executable. 5. Real x64 tests and warning status.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_lan_tests.exe --tag lan (or registered runtime LAN tag plus full target), verbose CTest, git diff --check. Logs lan-owner-*. Root can stage external original-binary harness if needed.
## 12. Constraints and stop conditions
No changes to socket reachability, authentication standards, new transport, UI or unrelated game state. Two failed fixes for the same defect -> send evidence and changed hypothesis to root. No children/Git/remote mutations.
## 13. Authorization and decisions
User approved milestone/system work, commits/PRs/accumulation. M01-F3/F4 require authenticated owner entry and preserved old-wire rules. Root handles final integration.
## 14. Return format
Return S16-02 status, early exact caller entry points, peer/session tracking contracts, actual test evidence/counts/interop and any native limitations.
The client also needs positive acknowledgements to remove committed draft parts. The approved preferred guest interface exposes `take_result()` with the full accepted or rejected intent, including resident ID. Retain one completion until the preferred caller drains it, clear stale results across connection generations and preserve legacy `take_rejection()` behavior. The loopback cases cover accepted and rejected results.
+6
View File
@@ -47,6 +47,12 @@
## Приёмка
Клиент Windows может обслуживать хост через `LanSession::poll_host(SimulationRuntime&)`, а гостя — через `poll_guest()`. Хост читает опубликованный снимок и отправляет команду доверенного слота 2 владельцу мира. Сетевой опрос продолжает работу, пока симуляция завершает приказ. `take_result()` возвращает гостю результат вместе с исходными параметрами намерения. До чтения результата следующая команда гостя остаётся в ограниченной очереди. [Сетевой интерфейс](../../../app/lan_session.hpp)
Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается.
Пять проверок `--tag lan-owner` под Wine покрывают квитанции, заполнение очереди, совмещённые пакеты, переподключение при задержанной публикации, откат с незавершённой командой и отказ при несовместимых правилах. Отдельный двоичный клиент прототипа подтвердил обмен в обоих направлениях с новым хостом и гостем. Проверка физической Windows и двух машин остаётся частью сетевой приёмки. [Сценарии](../../../tests/lan_tests.cpp)
Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6)
Селектор `--tag session` под Wine выполнил десять проверок, включая двух клиентов, конфликт данных повтора, откат с новой инкарнацией и отказ до/после изменения. Сценарий из 700 тактов сверяет эталон и 2/6/12 потоков. Подключение окна и сетевого транспорта к владельцу мира входит в следующий срез M01. [Сценарии](../../../tests/session_tests.cpp)
+322
View File
@@ -1,14 +1,26 @@
#define NOMINMAX
#include <winsock2.h>
#include <ws2tcpip.h>
#include "lan_session.hpp"
#include "lan_wire.hpp"
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <chrono>
#include <condition_variable>
#include <future>
#include <mutex>
#include <spanstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace {
@@ -29,11 +41,128 @@ constexpr auto command_bytes = "\x23\x00\x00\x00\x03"
constexpr auto receipt_bytes = "\x0a\x00\x00\x00\x04\x04\x10\x32\x54\x76\x98\xba\xdc\xfe"sv;
constexpr auto ping_bytes = "\x01\x00\x00\x00\x06"sv;
WorldCheckpoint colony_checkpoint() {
auto identity = Void::Uuid::try_v4();
auto rules = default_rules_manifest();
require(identity.has_value() && rules.has_value());
return {make_first_colony(2), *identity, 1, std::move(*rules)};
}
template<class Pump, class Condition>
void pump_until(Pump pump, Condition condition, const char* message) {
const auto deadline = std::chrono::steady_clock::now() + 3s;
do {
pump();
if (condition()) return;
std::this_thread::sleep_for(1ms);
} while (std::chrono::steady_clock::now() < deadline);
throw std::runtime_error(message);
}
struct CaptureGate {
std::mutex mutex;
std::condition_variable changed;
bool armed = false;
bool entered = false;
bool released = false;
void capture(RuntimePhase phase) {
if (phase != RuntimePhase::BeforeCapture) return;
std::unique_lock lock(mutex);
if (!armed) return;
entered = true;
changed.notify_all();
if (!changed.wait_for(lock, 5s, [&] { return released; })) {
throw std::runtime_error("LAN test capture gate timed out.");
}
}
void arm() { std::lock_guard lock(mutex); armed = true; }
bool waiting() { std::lock_guard lock(mutex); return entered; }
void release() {
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
};
struct RawGuest {
SOCKET socket = INVALID_SOCKET;
std::string input;
std::string output;
bool closed = false;
std::vector<lan_wire::Receipt> receipts;
std::unique_ptr<World> snapshot;
RawGuest(std::uint16_t port, std::uint64_t key) {
socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socket == INVALID_SOCKET) throw std::runtime_error("Raw guest socket failed.");
auto close_on_error = Void::Scope::on_exit([&] { closesocket(socket); });
sockaddr_in remote{};
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
remote.sin_port = htons(port);
if (connect(socket, reinterpret_cast<const sockaddr*>(&remote), sizeof(remote)) != 0) {
throw std::runtime_error("Raw guest connect failed.");
}
u_long enabled = 1;
require(ioctlsocket(socket, static_cast<long>(FIONBIO), &enabled) == 0);
const auto hello = lan_wire::encode_hello({lan_wire::protocol_version, key});
lan_wire::append_frame(output, lan_wire::Message::Hello, std::string_view(hello));
close_on_error.release();
}
~RawGuest() { closesocket(socket); }
RawGuest(const RawGuest&) = delete;
RawGuest& operator=(const RawGuest&) = delete;
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value});
lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes));
}
void poll() {
if (closed) return;
if (!output.empty()) {
const auto sent = send(socket, output.data(), static_cast<int>(output.size()), 0);
if (sent > 0) output.erase(0, static_cast<std::size_t>(sent));
else if (sent == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
}
std::array<char, 8192> bytes{};
for (int attempt = 0; attempt < 16 && !closed; ++attempt) {
const auto count = recv(socket, bytes.data(), static_cast<int>(bytes.size()), 0);
if (count == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
break;
}
if (count == 0) { closed = true; break; }
input.append(bytes.data(), static_cast<std::size_t>(count));
std::size_t consumed = 0;
while (const auto frame = lan_wire::next_frame(std::string_view(input).substr(consumed))) {
if (frame->message == lan_wire::Message::Receipt) {
auto receipt = lan_wire::decode_receipt(frame->payload);
require(receipt.has_value());
receipts.push_back(*receipt);
} else if (frame->message == lan_wire::Message::Snapshot) {
std::ispanstream stream(frame->payload);
snapshot = World::read_save(stream);
}
consumed += frame->size;
}
input.erase(0, consumed);
}
}
};
struct LanTests : Void::Testing::Suite<LanTests> {
[[= Void::Testing::tag("wire")]] Test test_protocol_11_fixed_messages();
[[= Void::Testing::tag("wire")]] Test test_fragmented_and_coalesced_frames();
[[= Void::Testing::tag("wire")]] Test test_frame_size_limits();
[[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_receipts_and_corrected_legacy_sequence();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_wrong_sequence_busy_and_pipelining();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_retains_slot_work_across_reconnect();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_reauthenticates_after_pending_rollback();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults();
};
Test LanTests::test_protocol_11_fixed_messages() {
@@ -295,4 +424,197 @@ Test LanTests::test_shared_colony_over_loopback() {
require(authoritative->production_orders().size() == previous_size + 10);
}
Test LanTests::test_runtime_host_receipts_and_corrected_legacy_sequence() {
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
LanSession host, guest;
host.host(0, true);
guest.join("127.0.0.1", host.join_code(), host.port());
std::unique_ptr<World> view;
const auto pump = [&] {
host.poll_host(runtime);
if (auto latest = guest.poll_guest()) view = std::move(latest);
};
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Runtime guest did not join.");
require(view && view->tick() == 0);
const auto resident = view->agents().back().id;
require(guest.submit(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), {}, resident));
std::optional<LanCommandResult> result;
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Profession receipt missing.");
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::AssignProfession &&
result->resident == resident && result->value == static_cast<std::uint8_t>(Profession::Miner));
require(runtime.latest()->world->agents().back().profession == Profession::Miner);
require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast<std::uint8_t>(BedBase::Stone)));
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Bed receipt missing.");
require(result->status == CommandStatus::Accepted && result->cell == GridPosition{16, 18});
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0));
require(guest.submit(CommandKind::SetForaging, {14, 12}, 1));
pump_until(pump, [&] { return guest.take_rejection().has_value(); }, "Bed rejection missing.");
// The failed result remains undrained. The queued correction cannot execute.
for (int attempt = 0; attempt < 20; ++attempt) pump();
require(runtime.latest()->next_requests[1] == 4);
result = guest.take_result();
require(result && result->status == CommandStatus::InvalidTarget && result->kind == CommandKind::PlaceBed &&
result->cell == GridPosition{16, 18} && result->destination == GridPosition{} && result->value == 0);
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Corrected command receipt missing.");
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
require(runtime.latest()->next_requests[1] == 5 && runtime.latest()->world->next_command_sequence(2) == 4);
require(runtime.latest()->world->production_orders().size() == 1);
pump_until(pump, [&] { return view->next_command_sequence(2) == 4; }, "Same-tick snapshot missing.");
require(view->tick() == 0);
guest.leave();
require(!guest.take_result());
}
Test LanTests::test_runtime_host_wrong_sequence_busy_and_pipelining() {
CaptureGate gate;
RuntimeOptions options{.capacity = 1, .ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
SimulationRuntime runtime(colony_checkpoint(), options);
auto release = Void::Scope::on_exit([&] { gate.release(); });
LanSession host;
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Raw runtime guest did not join.");
guest.command(99, CommandKind::SetForaging, {14, 12}, 1);
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Wrong-sequence receipt missing.");
require(guest.receipts[0].status == CommandStatus::WrongSequence && guest.receipts[0].next_sequence == 1);
const auto snapshot = runtime.latest();
gate.arm();
const auto& id = snapshot->identity;
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, 1,
CommandPayload{CommandKind::SetForaging, {13, 14}, 1}});
require(local.admission == RuntimeAdmission::Accepted);
pump_until(pump, [&] { return gate.waiting(); }, "Owner did not reach blocked capture.");
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Busy receipt missing.");
require(guest.receipts[1].status == CommandStatus::Busy && guest.receipts[1].next_sequence == 1);
require(runtime.latest()->next_requests[1] == 1);
gate.release();
require(local.completion.wait_for(3s) == std::future_status::ready);
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
// Two coalesced commands cannot turn one guest slot into multiple in-flight operations.
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
guest.command(2, CommandKind::SetForaging, {18, 12}, 1);
pump_until(pump, [&] { return guest.closed; }, "Pipelined guest was not bounded.");
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
pump_until(pump, [&] {
fence = runtime.synchronize();
return fence.admission == RuntimeAdmission::Accepted;
}, "Owner did not release its admission slot.");
require(fence.completion.wait_for(3s) == std::future_status::ready);
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->next_command_sequence(2) == 2);
}
Test LanTests::test_runtime_host_retains_slot_work_across_reconnect() {
CaptureGate gate;
RuntimeOptions options{.ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
SimulationRuntime runtime(colony_checkpoint(), options);
auto release = Void::Scope::on_exit([&] { gate.release(); });
LanSession host, first, next;
host.host(0, true);
const auto code = host.join_code();
const auto pump = [&] {
host.poll_host(runtime);
static_cast<void>(first.poll_guest());
static_cast<void>(next.poll_guest());
};
first.join("127.0.0.1", code, host.port());
pump_until(pump, [&] { return first.state() == LanState::GuestConnected; }, "First guest did not join.");
gate.arm();
require(first.submit(CommandKind::PlaceBed, {16, 18}, 1));
pump_until(pump, [&] { return gate.waiting(); }, "Guest command did not reach blocked owner.");
require(runtime.latest()->world->production_orders().empty());
first.leave();
pump_until(pump, [&] { return host.state() == LanState::Hosting; }, "Old socket did not close.");
next.join("127.0.0.1", code, host.port());
for (int attempt = 0; attempt < 20; ++attempt) pump();
require(next.state() == LanState::Connecting && !next.take_result());
gate.release();
pump_until(pump, [&] { return next.state() == LanState::GuestConnected; }, "Reconnected guest did not join.");
require(!next.take_result());
require(runtime.latest()->world->production_orders().size() == 1);
require(runtime.latest()->next_requests[1] == 2);
require(next.submit(CommandKind::SetForaging, {14, 12}, 1));
std::optional<LanCommandResult> result;
pump_until(pump, [&] { result = next.take_result(); return result.has_value(); }, "New guest receipt missing.");
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
require(runtime.latest()->next_requests[1] == 3 && runtime.latest()->world->next_command_sequence(2) == 3);
}
Test LanTests::test_runtime_host_reauthenticates_after_pending_rollback() {
CaptureGate gate;
RuntimeOptions options{.ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
auto initial = colony_checkpoint();
const auto world_id = initial.world_id;
SimulationRuntime runtime(std::move(initial), options);
auto release = Void::Scope::on_exit([&] { gate.release(); });
LanSession host, guest;
host.host(0, true);
guest.join("127.0.0.1", host.join_code(), host.port());
const auto pump = [&] { host.poll_host(runtime); static_cast<void>(guest.poll_guest()); };
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Rollback guest did not join.");
const auto old_session = runtime.latest()->identity.session;
gate.arm();
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
pump_until(pump, [&] { return gate.waiting(); }, "Rollback guest command did not block.");
auto ticket = runtime.begin_load();
require(ticket.has_value());
auto rollback = colony_checkpoint();
rollback.world_id = world_id;
auto installed = runtime.try_install(*ticket, rollback);
require(installed.admission == RuntimeAdmission::Accepted);
gate.release();
require(installed.completion.wait_for(3s) == std::future_status::ready);
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Old epoch peer stayed connected.");
require(runtime.latest()->identity.session != old_session && runtime.latest()->identity.world == world_id);
require(runtime.latest()->world->production_orders().empty() && !guest.take_result());
guest.reconnect();
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Guest could not reauthenticate.");
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
std::optional<LanCommandResult> result;
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "New epoch receipt missing.");
require(result->status == CommandStatus::Accepted && runtime.latest()->next_requests[1] == 2);
}
Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() {
auto initial = colony_checkpoint();
auto packages = builtin_rule_packages();
require(packages.has_value());
const std::array selected{std::string{"settlement.core"}};
auto rules = resolve_rules(*packages, selected);
require(rules.has_value());
initial.rules = std::move(*rules);
SimulationRuntime incompatible(std::move(initial), {.ticking = false});
LanSession host, guest;
host.host(0, true);
guest.join("127.0.0.1", host.join_code(), host.port());
host.poll_host(incompatible);
require(host.state() == LanState::Hosting && host.detail().find("default rules") != std::string::npos);
for (int attempt = 0; attempt < 20; ++attempt) {
host.poll_host(incompatible);
require(!guest.poll_guest());
}
require(guest.state() != LanState::GuestConnected);
guest.leave();
RuntimeOptions options{.ticking = false};
options.observer = [](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected capture failure.");
};
SimulationRuntime faulting(colony_checkpoint(), options);
guest.join("127.0.0.1", host.join_code(), host.port());
const auto pump = [&] { host.poll_host(faulting); static_cast<void>(guest.poll_guest()); };
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Fault guest did not join.");
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Faulted peer stayed connected.");
require(faulting.view().state == RuntimeState::Faulted && faulting.latest()->world->production_orders().empty());
require(!guest.take_result());
}
} // namespace