#include "evo/client/region_session.hpp" #include #include #include namespace evo::client { namespace { using network::SessionCloseReason; using Clock = std::chrono::steady_clock; } // namespace struct RegionSessionClient::Impl { std::unique_ptr endpoint; network::WireGrant grant{}; std::uint16_t protocol_version{network::session_protocol_version}; Clock::time_point deadline; RegionSessionState state{RegionSessionState::connecting}; network::quic::ConnectionId connection{}; std::optional welcome; std::optional reason; std::optional transport_cause; std::optional refresh_result; std::uint64_t next_sequence{1}, server_tick{}; std::optional simulated; std::vector intention_receipts; std::vector action_receipts; std::vector action_outcomes; std::vector primitive_life_receipts; std::vector primitive_life_outcomes; std::optional snapshots; std::optional cellular_perception; std::optional mutation_offer; std::uint64_t snapshot_chunks{}, snapshot_bytes{}; std::optional handoff; // v4: continue at another region. std::optional redirect; // v4: the probe is owned elsewhere. static constexpr std::size_t max_kept = 1024; // Per kind, until taken; oldest dropped. template static void keep(std::vector& list, const T& item) { if (list.size() >= max_kept) list.erase(list.begin()); list.push_back(item); } void seen_tick(std::uint64_t tick) { server_tick = std::max(server_tick, tick); } // A protocol close names its cause on stderr: which channel, the codec or assembly // error, or the message alternative and version that was not expected here. void protocol_close(const char* where, int detail, std::size_t bytes) { std::fprintf(stderr, "session protocol close: %s detail=%d bytes=%zu state=%d\n", where, detail, bytes, static_cast(state)); end(SessionCloseReason::protocol, true); } // Datagrams: receipts and watermarks only, after Welcome. void datagram(std::span bytes) { if (state != RegionSessionState::established) return; const auto decoded = network::decode_session(bytes); if (!decoded) return protocol_close("datagram decode", static_cast(decoded.error()), bytes.size()); if (const auto* m = std::get_if(&*decoded)) { seen_tick(m->server_tick); return keep(intention_receipts, *m); } if (const auto* m = std::get_if(&*decoded)) { ++snapshot_chunks; snapshot_bytes += bytes.size(); seen_tick(m->tick); if (!snapshots) return; // Before Welcome (channels are not ordered): the next tick resends. const auto accepted = snapshots->accept(*m); if (!accepted) // Malformed snapshot. return protocol_close("snapshot", static_cast(accepted.error()), bytes.size()); if (const auto ack = accepted.value_or(std::nullopt); ack && connection != 0) // A lost ack only means the next delta is against an older baseline. (void)endpoint ->send_datagram(connection, network::encode_session(*ack, protocol_version)) .has_value(); return; } if (const auto* m = std::get_if(&*decoded)) { if (!welcome || m->epoch != welcome->epoch) return; // Another epoch's watermark says nothing about this session. seen_tick(m->tick); if (!simulated || m->sequence >= simulated->sequence) simulated = *m; return; } protocol_close("datagram unexpected", static_cast(decoded->index()), bytes.size()); } // An encoding refused for this session's version (empty) is never sent as success. bool send(const network::SessionMessage& m) { const auto bytes = network::encode_session(m, protocol_version); return connection != 0 && !bytes.empty() && endpoint->send_message(connection, bytes).has_value(); } // Ends the session locally; `tell` sends a Close first (best effort). void end(SessionCloseReason why, bool tell) { if (state == RegionSessionState::closed) return; if (tell) (void)send(network::SessionClose{why}); state = RegionSessionState::closed; reason = why; grant.fill(0); if (connection != 0) endpoint->close(connection); } void message(std::span bytes) { std::uint16_t wire_version{}; const auto decoded = network::decode_session(bytes, &wire_version); if (!decoded) return protocol_close("message decode", static_cast(decoded.error()), bytes.size()); if (wire_version != protocol_version) return end(SessionCloseReason::unsupported_version, true); if (const auto* m = std::get_if(&*decoded)) return end(m->reason, false); if (state == RegionSessionState::awaiting_welcome) { if (const auto* m = std::get_if(&*decoded)) { redirect = m->owner; // A Close (moved) follows. return; } if (const auto* m = std::get_if(&*decoded)) { welcome = *m; snapshots.emplace(world::WorldIdentity{m->world, m->frame}, m->epoch); seen_tick(m->server_tick); state = RegionSessionState::established; return; } } else if (state == RegionSessionState::established) { if (const auto* m = std::get_if(&*decoded)) { if (m->status == 0) welcome->expires_at = m->expires_at; refresh_result = *m; return; } if (const auto* m = std::get_if(&*decoded)) { seen_tick(m->server_tick); return keep(action_receipts, *m); } if (const auto* m = std::get_if(&*decoded)) return keep(action_outcomes, *m); if (const auto* m = std::get_if(&*decoded)) { seen_tick(m->tick); cellular_perception = *m; return; } if (const auto* m = std::get_if(&*decoded)) { seen_tick(m->tick); if (m->candidates.empty()) mutation_offer.reset(); else mutation_offer = *m; return; } if (const auto* m = std::get_if(&*decoded)) { seen_tick(m->server_tick); return keep(primitive_life_receipts, *m); } if (const auto* m = std::get_if(&*decoded)) return keep(primitive_life_outcomes, *m); if (const auto* m = std::get_if(&*decoded)) { handoff = *m; // A Close (handed_off) follows. return; } } protocol_close("message unexpected", static_cast(decoded->index()) * 100 + wire_version, bytes.size()); } }; RegionSessionClient::RegionSessionClient(std::unique_ptr impl) : impl_{std::move(impl)} {} RegionSessionClient::~RegionSessionClient() = default; std::expected, network::quic::EndpointError> RegionSessionClient::connect(RegionSessionClientConfig config, Clock::time_point now) { if (config.protocol_version != network::session_protocol_version && config.protocol_version != network::session_protocol_v5 && config.protocol_version != network::session_protocol_v6 && config.protocol_version != network::session_protocol_v7 && config.protocol_version != network::session_protocol_v8 && config.protocol_version != network::session_protocol_v9 && config.protocol_version != network::session_protocol_v10) return std::unexpected(network::quic::EndpointError::configuration); auto endpoint = network::quic::Endpoint::connect(config.transport); if (!endpoint) return std::unexpected(endpoint.error()); auto impl = std::make_unique(); impl->endpoint = std::move(*endpoint); impl->protocol_version = config.protocol_version; impl->grant = config.grant; config.grant.fill(0); impl->deadline = now + config.welcome_deadline; return std::unique_ptr{new RegionSessionClient{std::move(impl)}}; } void RegionSessionClient::poll(Clock::time_point now) { auto& m = *impl_; for (auto& e : m.endpoint->poll()) { using network::quic::EventKind; if (m.state == RegionSessionState::closed) continue; if (e.kind == EventKind::connected && m.state == RegionSessionState::connecting) { m.connection = e.connection; m.state = RegionSessionState::awaiting_welcome; network::SessionHello hello; hello.grant = m.grant; m.grant.fill(0); // The grant is a credential: keep it no longer than needed. if (!m.send(hello)) m.end(SessionCloseReason::connection_lost, false); } else if (e.kind == EventKind::message) { m.message(e.bytes); } else if (e.kind == EventKind::datagram) { m.datagram(e.bytes); } else if (e.kind == EventKind::closed) { m.transport_cause = e.cause; m.connection = 0; // Already gone; nothing to close or send. m.end(SessionCloseReason::connection_lost, false); } } if ((m.state == RegionSessionState::connecting || m.state == RegionSessionState::awaiting_welcome) && now >= m.deadline) m.end(SessionCloseReason::timeout, false); } bool RegionSessionClient::refresh(const network::WireGrant& grant) { return impl_->state == RegionSessionState::established && impl_->send(network::SessionRefresh{grant}); } std::optional RegionSessionClient::take_refresh_result() { return std::exchange(impl_->refresh_result, std::nullopt); } void RegionSessionClient::close() { impl_->end(SessionCloseReason::client_closed, true); } std::optional RegionSessionClient::send_intention(std::uint64_t tick, std::int16_t move_x, std::int16_t move_y) { auto& m = *impl_; if (m.protocol_version != network::session_protocol_version || m.state != RegionSessionState::established || m.connection == 0 || !m.welcome) return std::nullopt; const network::SessionIntention intention{ m.welcome->session, m.welcome->epoch, m.next_sequence, tick, move_x, move_y}; if (!m.endpoint->send_datagram(m.connection, network::encode_session(intention))) return std::nullopt; return m.next_sequence++; } std::optional RegionSessionClient::send_cellular_intention( std::uint64_t tick, std::int16_t move_x, std::int16_t move_y, std::optional> intake_target) { auto& m = *impl_; if (m.protocol_version != network::session_protocol_v6 || m.state != RegionSessionState::established || m.connection == 0 || !m.welcome) return std::nullopt; const network::CellularIntention intention{m.welcome->session, m.welcome->epoch, m.next_sequence, tick, move_x, move_y, intake_target.has_value(), intake_target ? intake_target->first : 0, intake_target ? intake_target->second : 0}; if (!m.endpoint->send_datagram(m.connection, network::encode_session(intention, m.protocol_version))) return std::nullopt; return m.next_sequence++; } bool RegionSessionClient::send_action(std::uint64_t action_id, network::ActionKind kind, std::uint64_t tick) { auto& m = *impl_; return m.protocol_version == network::session_protocol_version && m.state == RegionSessionState::established && m.welcome && m.send(network::SessionAction{m.welcome->session, m.welcome->epoch, action_id, static_cast(kind), tick}); } bool RegionSessionClient::send_cellular_action( std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x, std::int16_t move_y, std::optional> intake_target, bool engulf, bool bud) { auto& m = *impl_; return (m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || m.protocol_version == network::session_protocol_v10) && m.state == RegionSessionState::established && m.welcome && action_id != 0 && tick != 0 && m.send(network::CellularAction{m.welcome->session, m.welcome->epoch, action_id, tick, move_x, move_y, intake_target.has_value(), intake_target ? intake_target->first : 0, intake_target ? intake_target->second : 0, engulf, bud}); } bool RegionSessionClient::send_cellular_mutation(std::uint64_t action_id, std::uint64_t tick, std::uint64_t life_identity, std::uint64_t event_index, std::uint64_t offer_tick, std::uint16_t operator_id) { auto& m = *impl_; return m.protocol_version == network::session_protocol_v10 && m.state == RegionSessionState::established && m.welcome && action_id != 0 && offer_tick != 0 && tick > offer_tick && m.send(network::CellularMutationAction{m.welcome->session, m.welcome->epoch, action_id, tick, life_identity, event_index, offer_tick, operator_id}); } bool RegionSessionClient::query_action(std::uint64_t action_id) { auto& m = *impl_; return (m.protocol_version == network::session_protocol_version || m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || m.protocol_version == network::session_protocol_v10) && m.state == RegionSessionState::established && m.send(network::ActionQuery{action_id}); } bool RegionSessionClient::request_primitive_life(std::uint64_t request_id) { auto& m = *impl_; return (m.protocol_version == network::session_protocol_v5 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || m.protocol_version == network::session_protocol_v10) && m.state == RegionSessionState::established && m.welcome && request_id != 0 && m.send(network::PrimitiveLifeRequest{m.welcome->session, m.welcome->epoch, request_id}); } bool RegionSessionClient::query_primitive_life(std::uint64_t request_id) { auto& m = *impl_; return (m.protocol_version == network::session_protocol_v5 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || m.protocol_version == network::session_protocol_v10) && m.state == RegionSessionState::established && request_id != 0 && m.send(network::PrimitiveLifeQuery{request_id}); } std::vector RegionSessionClient::take_primitive_life_receipts() { return std::exchange(impl_->primitive_life_receipts, {}); } std::vector RegionSessionClient::take_primitive_life_outcomes() { return std::exchange(impl_->primitive_life_outcomes, {}); } std::vector RegionSessionClient::take_intention_receipts() { return std::exchange(impl_->intention_receipts, {}); } std::vector RegionSessionClient::take_action_receipts() { return std::exchange(impl_->action_receipts, {}); } std::vector RegionSessionClient::take_action_outcomes() { return std::exchange(impl_->action_outcomes, {}); } std::optional RegionSessionClient::simulated() const noexcept { return impl_->simulated; } std::uint64_t RegionSessionClient::server_tick() const noexcept { return impl_->server_tick; } bool RegionSessionClient::set_interest(const network::SessionInterest& interest) { auto& m = *impl_; return (m.protocol_version == network::session_protocol_version || m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || m.protocol_version == network::session_protocol_v10) && m.state == RegionSessionState::established && m.send(interest); } const network::ReplicatedView* RegionSessionClient::view() const noexcept { const auto& snapshots = impl_->snapshots; return snapshots ? snapshots->latest() : nullptr; } const std::optional& RegionSessionClient::cellular_perception() const noexcept { return impl_->cellular_perception; } const std::optional& RegionSessionClient::mutation_offer() const noexcept { return impl_->mutation_offer; } std::expected RegionSessionClient::environment() const { const auto& snapshots = impl_->snapshots; if (!snapshots) return std::unexpected(client::ViewError::empty_slice); return snapshots->environment(); } std::expected RegionSessionClient::organisms() const { const auto& snapshots = impl_->snapshots; if (!snapshots) return std::unexpected(client::ViewError::empty_slice); return snapshots->organisms(); } std::uint64_t RegionSessionClient::snapshot_chunks() const noexcept { return impl_->snapshot_chunks; } std::uint64_t RegionSessionClient::snapshot_bytes() const noexcept { return impl_->snapshot_bytes; } std::optional RegionSessionClient::take_handoff() { return std::exchange(impl_->handoff, std::nullopt); } const std::optional& RegionSessionClient::redirect() const noexcept { return impl_->redirect; } RegionSessionState RegionSessionClient::state() const noexcept { return impl_->state; } const std::optional& RegionSessionClient::welcome() const noexcept { return impl_->welcome; } std::optional RegionSessionClient::transport_cause() const noexcept { return impl_->transport_cause; } std::optional RegionSessionClient::close_reason() const noexcept { return impl_->reason; } } // namespace evo::client