#include "evo/network/session_client.hpp" #include "evo/network/session_server.hpp" #include "evo/network/tcp.hpp" #include "network_pki.hpp" #include "network_test.hpp" #include #include #include #include #include #include namespace evo::network_test { namespace { using namespace evo::network; using Clock = std::chrono::steady_clock; constexpr world::WorldIdentity identity{11, 12}; constexpr std::uint64_t region = 21; constexpr std::uint64_t now_seconds = 1'000'000; DevGrantKey grant_key(std::uint8_t fill = 0x33) { std::array secret{}; secret.fill(fill); auto k = DevGrantKey::import(DeploymentEnvironment::dev, secret); CHECK(k); return std::move(*k); } std::vector grants(std::uint64_t subject, std::size_t count, std::uint64_t first_id, std::uint8_t fill = 0x33, std::uint64_t grant_region = region) { const auto k = grant_key(fill); std::vector out; for (std::size_t i = 0; i < count; ++i) { const auto g = k.issue( {first_id + i, subject, identity, grant_region, now_seconds - 60, now_seconds + 1800}); CHECK(g); out.push_back(*g); } return out; } client::EnvironmentPresentation environment(std::uint64_t tick) { client::EnvironmentCell c; c.voxel = {0, 0, -16000}; c.chunk_revision = 1; c.habitat = {{0}, {0}, {0}, {10}, {20}, {3}}; c.volume = {600}; c.terrain_material = {1}; c.presence[0] = client::FieldPresence::present; c.quantity[0] = tick; // Visible change per tick. c.moisture_status = world::MoistureStatus::zero_capacity; auto v = client::EnvironmentPresentation::create({identity, tick, tick}, 1, -16000, {&c, 1}); CHECK(v); return std::move(*v); } client::OrganismPresentation no_organisms(std::uint64_t tick) { auto v = client::OrganismPresentation::create({identity, tick, 0}, -16000, {}); CHECK(v); return std::move(*v); } struct Harness { explicit Harness(std::size_t max_sessions = 4, std::chrono::milliseconds hello = std::chrono::milliseconds{3000}) { server = make_server(0, max_sessions, hello); port = server->port(); } std::unique_ptr make_server(std::uint16_t at, std::size_t max_sessions, std::chrono::milliseconds hello) { SessionServerConfig c; c.listen = "127.0.0.1:" + std::to_string(at); c.credentials = pki.server; c.admission.world = identity; c.admission.region = region; c.admission.max_sessions = max_sessions; c.admission.intent_window = 8; c.admission.window_ticks = 8; c.admission.max_intents_per_window = 8; c.hello_deadline = hello; auto s = SessionServer::create(std::move(c), grant_key()); CHECK(s); return std::move(*s); } std::unique_ptr client(std::vector g) { SessionClientConfig c; c.host = "127.0.0.1"; c.port = port; c.trust = {pki.authority, server_name}; c.grants = std::move(g); c.first_retry = std::chrono::milliseconds{50}; c.max_retry = std::chrono::milliseconds{200}; c.attempt_deadline = std::chrono::milliseconds{3000}; auto s = SessionClient::create(std::move(c)); CHECK(s); clients.push_back(s->get()); return std::move(*s); } void tick() { ++facts.simulated_tick; if (server) server->publish(environment(facts.simulated_tick), no_organisms(facts.simulated_tick), facts); } // Pumps everything until `done` or the wall-clock limit. bool until(const std::function& done, std::chrono::milliseconds limit = std::chrono::milliseconds{5000}) { const auto end = Clock::now() + limit; while (Clock::now() < end) { const auto now = Clock::now(); if (server) server->poll(facts, now_seconds, now); for (auto* c : clients) c->poll(now); if (done()) return true; std::this_thread::sleep_for(std::chrono::milliseconds{1}); } return false; } void collect(SessionClient& c, std::vector& into) { auto e = c.take_events(); into.insert(into.end(), e.begin(), e.end()); } Pki pki; RegionFacts facts{true, 1, 100, 90, 5}; std::unique_ptr server; std::uint16_t port{}; std::vector clients; }; bool has(const std::vector& events, ClientEvent::Kind kind) { return std::ranges::any_of(events, [&](const ClientEvent& e) { return e.kind == kind; }); } const ClientEvent* last(const std::vector& events, ClientEvent::Kind kind) { const auto it = std::ranges::find_if(events.rbegin(), events.rend(), [&](const ClientEvent& e) { return e.kind == kind; }); return it == events.rend() ? nullptr : &*it; } void connect_view_intents_and_outcomes() { Harness h; h.tick(); auto c = h.client(grants(7, 4, 100)); std::vector events; CHECK(h.until([&] { h.collect(*c, events); return c->latest_view().has_value(); })); const auto w = c->welcome(); CHECK(w && w->session == 1 && w->epoch == 1 && w->world == 11 && w->frame == 12 && w->region == region && w->commit_watermark == 90 && w->server_tick == 101); CHECK(c->grants_left() == 3 && h.server->sessions() == 1); CHECK(c->environment().freshness() == client::Freshness::current); CHECK(c->environment().current()->cells()[0].quantity[0] == 101); CHECK(must(c->latest_view()).commit_watermark == 90 && must(c->latest_view()).server_tick == 101); CHECK(h.until([&] { return c->organisms().current() != nullptr; })); CHECK(c->organisms().current()->cells().empty()); // Explicitly no organisms. // Views follow the region: a new tick replaces the presentation. h.tick(); CHECK(h.until([&] { return must(c->latest_view()).server_tick == 102; })); CHECK(c->environment().current()->cells()[0].quantity[0] == 102); // Admitted intention: carried by a host input, then durably committed. CHECK(c->send({1, 0, 1000, 0})); CHECK(h.until([&] { h.collect(*c, events); return last(events, ClientEvent::Kind::result) != nullptr; })); CHECK(last(events, ClientEvent::Kind::result)->result.status == IntentStatus::admitted); CHECK(!h.server->carry(105)); // Intended tick 102 + 4 = 106. const auto request = h.server->carry(106); CHECK(must(request)[0] == 'I' && must(request)[3] == '1'); CHECK(!h.server->carry(200)); // Carried once. h.server->committed(must(request), 106, 6); CHECK(h.until([&] { h.collect(*c, events); return last(events, ClientEvent::Kind::outcome) != nullptr; })); const auto* outcome = last(events, ClientEvent::Kind::outcome); CHECK(outcome->outcome.sequence == 1 && outcome->outcome.finality == IntentFinality::committed_no_effect && outcome->outcome.tick == 106 && outcome->outcome.commit_sequence == 6); // Rejected: replay and an out-of-bound vector never reach the host. events.clear(); CHECK(c->send({1, 0, 0, 1000}) && c->send({2, 0, 1000, 1000})); CHECK(h.until([&] { h.collect(*c, events); return std::ranges::count_if(events, [](const ClientEvent& e) { return e.kind == ClientEvent::Kind::result; }) == 2; })); CHECK(events[0].result.status == IntentStatus::replayed && events[1].result.status == IntentStatus::invalid_vector); CHECK(!h.server->carry(1000)); // A dropped host input is reported as not committed. events.clear(); CHECK(c->send({3, 0, -707, 707})); CHECK(h.until([&] { h.collect(*c, events); return has(events, ClientEvent::Kind::result); })); CHECK(last(events, ClientEvent::Kind::result)->result.status == IntentStatus::admitted); const auto dropped = h.server->carry(1000); CHECK(dropped); h.server->not_committed(must(dropped)); CHECK(h.until([&] { h.collect(*c, events); return last(events, ClientEvent::Kind::outcome) != nullptr; })); CHECK(last(events, ClientEvent::Kind::outcome)->outcome.finality == IntentFinality::not_committed); } void duplicate_capacity_and_authentication() { Harness h{2}; h.tick(); auto first = h.client(grants(7, 2, 100)); CHECK(h.until([&] { return first->phase() == SessionPhase::established; })); // Same subject, fresh grant: refused; control is never duplicated. auto twin = h.client(grants(7, 1, 200)); std::vector twin_events; CHECK(h.until([&] { h.collect(*twin, twin_events); return has(twin_events, ClientEvent::Kind::closed); })); CHECK(last(twin_events, ClientEvent::Kind::closed)->reason == CloseReason::duplicate_session); CHECK(first->phase() == SessionPhase::established && h.server->sessions() == 1); // One grant only: after the refusal, reconnection stops explicitly. CHECK(h.until([&] { h.collect(*twin, twin_events); return twin->phase() == SessionPhase::exhausted; })); CHECK(has(twin_events, ClientEvent::Kind::exhausted)); // A reused grant is refused even for a different connection. auto reuse = h.client(grants(7, 1, 100)); // Grant id 100 was used by `first`. std::vector reuse_events; CHECK(h.until([&] { h.collect(*reuse, reuse_events); return has(reuse_events, ClientEvent::Kind::closed); })); CHECK(last(reuse_events, ClientEvent::Kind::closed)->reason == CloseReason::unauthenticated); // Foreign key and foreign region are unauthenticated. std::vector> others; // Kept alive: the harness polls them. for (auto g : {grants(8, 1, 300, 0x44), grants(9, 1, 301, 0x33, region + 1)}) { others.push_back(h.client(std::move(g))); auto* other = others.back().get(); std::vector e; CHECK(h.until([&] { h.collect(*other, e); return has(e, ClientEvent::Kind::closed); })); CHECK(last(e, ClientEvent::Kind::closed)->reason == CloseReason::unauthenticated); } // Capacity: a second subject fits, a third is refused with `capacity`. auto second = h.client(grants(10, 1, 400)); CHECK(h.until([&] { return second->phase() == SessionPhase::established; })); auto third = h.client(grants(11, 1, 500)); std::vector third_events; CHECK(h.until([&] { h.collect(*third, third_events); return has(third_events, ClientEvent::Kind::closed); })); CHECK(last(third_events, ClientEvent::Kind::closed)->reason == CloseReason::capacity); } void stale_epoch_restart_and_reconnect() { Harness h; h.tick(); auto c = h.client(grants(7, 6, 100)); std::vector events; CHECK(h.until([&] { return c->latest_view().has_value(); })); CHECK(c->send({1, 0, 1000, 0})); CHECK(h.until([&] { h.collect(*c, events); return has(events, ClientEvent::Kind::result); })); // New ownership epoch: the session is closed as stale, its pending intention's // outcome is unknown, and the presentation is kept but marked stale. h.facts.epoch = 2; CHECK(h.until([&] { h.collect(*c, events); return has(events, ClientEvent::Kind::closed); })); CHECK(last(events, ClientEvent::Kind::closed)->reason == CloseReason::stale_epoch); CHECK(has(events, ClientEvent::Kind::unknown)); CHECK(c->environment().freshness() == client::Freshness::stale); CHECK(!h.server->carry(1000)); // Old-epoch intentions never ride new inputs. // Reconnect with a fresh grant: new session, new epoch, fresh baseline. h.tick(); CHECK(h.until([&] { h.collect(*c, events); return c->phase() == SessionPhase::established && c->latest_view().has_value(); })); CHECK(must(c->welcome()).epoch == 2 && must(c->welcome()).session == 2 && c->grants_left() == 4); CHECK(c->environment().freshness() == client::Freshness::current); CHECK(must(c->latest_view()).epoch == 2); // Server process restart: the listener disappears, then a new one takes the port // with a new epoch. The client reconnects without the old session's state. events.clear(); h.server.reset(); CHECK(h.until([&] { h.collect(*c, events); return has(events, ClientEvent::Kind::lost); })); CHECK(c->phase() != SessionPhase::established && c->environment().freshness() == client::Freshness::stale); h.facts = {true, 3, 40, 40, 2}; // Recovered at the committed checkpoint: tick went back. h.server = h.make_server(h.port, 4, std::chrono::milliseconds{3000}); h.tick(); CHECK(h.until([&] { h.collect(*c, events); return c->phase() == SessionPhase::established && c->latest_view().has_value(); })); CHECK(must(c->welcome()).epoch == 3 && must(c->welcome()).session == 1); // The layer was reset for the new session, so the earlier tick does not regress it. CHECK(must(c->latest_view()).server_tick == 41 && c->environment().current()->revision().tick == 41); } void abuse() { // Not ready yet: Hello is refused with server_shutdown and retried later. Harness h; h.facts.ready = false; h.facts.epoch = 0; auto c = h.client(grants(7, 3, 100)); std::vector events; CHECK(h.until([&] { h.collect(*c, events); return has(events, ClientEvent::Kind::closed); })); CHECK(last(events, ClientEvent::Kind::closed)->reason == CloseReason::server_shutdown); // Refused before admission: the grant was never recorded, so it is not spent. CHECK(c->grants_left() == 3); h.facts = {true, 1, 100, 90, 5}; h.tick(); CHECK(h.until([&] { return c->phase() == SessionPhase::established; })); CHECK(c->grants_left() == 2); // Flooding: the byte-rate limit closes the connection. The flooding client may see // a transport reset before it reads the Close frame, so check the server's decision. CHECK(h.until([&] { return c->latest_view().has_value(); })); (void)h.server->take_events(); for (std::uint64_t s = 10; s < 2000; ++s) CHECK(c->send({s, 0, 0, 0})); std::vector server_events; CHECK(h.until([&] { auto e = h.server->take_events(); server_events.insert(server_events.end(), e.begin(), e.end()); return std::ranges::any_of(server_events, [](const SessionEvent& x) { return x.kind == SessionEvent::Kind::closed && x.reason == CloseReason::rate_limited; }); })); CHECK(h.until([&] { h.collect(*c, events); return c->phase() != SessionPhase::established; })); // Plaintext and silent connections are dropped without a session: the server // closes the socket (plaintext at the TLS handshake, silence at the deadline). Harness quiet{4, std::chrono::milliseconds{200}}; const auto dropped_by_server = [&](TcpStream& s, std::span bytes) { std::size_t sent = 0; return quiet.until([&] { if (sent < bytes.size()) if (const auto n = s.write(bytes.subspan(sent))) sent += *n; std::array sink{}; const auto r = s.read(sink); return !r.has_value(); }); }; auto plain = TcpStream::connect("127.0.0.1", quiet.port); CHECK(plain); const auto bytes = encode(IntentMessage{1, 1, 1, 1, 0, 0}); CHECK(dropped_by_server(**plain, bytes)); auto silent = TcpStream::connect("127.0.0.1", quiet.port); CHECK(silent); const auto start = Clock::now(); CHECK(dropped_by_server(**silent, {})); CHECK(Clock::now() - start >= std::chrono::milliseconds{150}); // Held until the deadline. CHECK(quiet.until([&] { return quiet.server->connections() == 0; })); CHECK(quiet.server->sessions() == 0); } } // namespace void session_tests() { connect_view_intents_and_outcomes(); duplicate_capacity_and_authentication(); stale_epoch_restart_and_reconnect(); abuse(); } } // namespace evo::network_test