Add M10.5a session protocol v2 and snapshot replication core
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (ecs) (push) Successful in 1m58s
Foundation / checks (client) (push) Failing after 9m57s
Foundation / checks (network) (push) Successful in 11m17s
Foundation / checks (tsan) (push) Successful in 7m49s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (checks) (push) Canceled after 25m43s
Foundation / checks (postgres) (push) Canceled after 15m44s
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (ecs) (push) Successful in 1m58s
Foundation / checks (client) (push) Failing after 9m57s
Foundation / checks (network) (push) Successful in 11m17s
Foundation / checks (tsan) (push) Successful in 7m49s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (checks) (push) Canceled after 25m43s
Foundation / checks (postgres) (push) Canceled after 15m44s
Session protocol v2 adds Interest, SnapshotChunk and SnapshotAck (v1 is refused). ReplicationServer filters by a server-capped client focus and a perception predicate, sends per-tick entity deltas against the acknowledged baseline (kept up to 40 ticks), nearest first within 16 KiB with a slower distant tier, as self-contained datagram chunks. SnapshotAssembler applies complete snapshots to one of two baselines and validates them as presentations. ADR-0093. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,491 @@
|
||||
#include "evo/network/replication.hpp"
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
|
||||
namespace evo::network {
|
||||
namespace {
|
||||
constexpr std::uint8_t max_chunks = 16;
|
||||
constexpr std::size_t max_partial = 4;
|
||||
constexpr std::size_t max_applied = 2;
|
||||
constexpr auto last_presence = static_cast<std::uint8_t>(client::FieldPresence::present);
|
||||
constexpr auto last_moisture = static_cast<std::uint8_t>(world::MoistureStatus::available);
|
||||
constexpr auto last_state = static_cast<std::uint8_t>(client::OrganismState::dead);
|
||||
|
||||
void put(std::vector<std::uint8_t>& out, std::uint64_t v, std::size_t count) {
|
||||
for (std::size_t i = 0; i < count; ++i)
|
||||
out.push_back(static_cast<std::uint8_t>(v >> (8 * i)));
|
||||
}
|
||||
void put_signed(std::vector<std::uint8_t>& out, std::int64_t v) {
|
||||
put(out, static_cast<std::uint64_t>(v), 8);
|
||||
}
|
||||
|
||||
// Bounds-checked little-endian reader; any overrun latches failure.
|
||||
class Reader {
|
||||
public:
|
||||
explicit Reader(std::span<const std::uint8_t> bytes) : bytes_{bytes} {}
|
||||
std::uint64_t u(std::size_t count) {
|
||||
if (!ok_ || bytes_.size() - at_ < count) {
|
||||
ok_ = false;
|
||||
return 0;
|
||||
}
|
||||
std::uint64_t v = 0;
|
||||
for (std::size_t i = 0; i < count; ++i)
|
||||
v |= static_cast<std::uint64_t>(bytes_[at_ + i]) << (8 * i);
|
||||
at_ += count;
|
||||
return v;
|
||||
}
|
||||
std::int64_t i64() {
|
||||
return static_cast<std::int64_t>(u(8));
|
||||
}
|
||||
// An out-of-range value fails the read and yields 0, never an invalid enumerator.
|
||||
std::uint8_t enumerator(std::uint8_t last) {
|
||||
const auto v = static_cast<std::uint8_t>(u(1));
|
||||
if (v > last) {
|
||||
ok_ = false;
|
||||
return 0;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
[[nodiscard]] bool ok() const noexcept {
|
||||
return ok_;
|
||||
}
|
||||
[[nodiscard]] bool done() const noexcept {
|
||||
return at_ == bytes_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
std::span<const std::uint8_t> bytes_;
|
||||
std::size_t at_{};
|
||||
bool ok_{true};
|
||||
};
|
||||
|
||||
std::vector<std::uint8_t> remove_environment(const world::VoxelAddress& v) {
|
||||
std::vector<std::uint8_t> out{static_cast<std::uint8_t>(RecordKind::environment_remove)};
|
||||
for (const auto c : {v.x, v.y, v.z})
|
||||
put_signed(out, c);
|
||||
return out;
|
||||
}
|
||||
std::vector<std::uint8_t> remove_organism(std::uint64_t id) {
|
||||
std::vector<std::uint8_t> out{static_cast<std::uint8_t>(RecordKind::organism_remove)};
|
||||
put(out, id, 8);
|
||||
return out;
|
||||
}
|
||||
std::uint64_t distance(std::int64_t x, std::int64_t y, const SessionInterest& i) {
|
||||
const auto dx =
|
||||
x > i.x ? static_cast<std::uint64_t>(x - i.x) : static_cast<std::uint64_t>(i.x - x);
|
||||
const auto dy =
|
||||
y > i.y ? static_cast<std::uint64_t>(y - i.y) : static_cast<std::uint64_t>(i.y - y);
|
||||
return std::max(dx, dy); // Chebyshev: the interest is a square.
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::vector<std::uint8_t> encode_record(const client::EnvironmentCell& c) {
|
||||
std::vector<std::uint8_t> out{static_cast<std::uint8_t>(RecordKind::environment_upsert)};
|
||||
for (const auto v : {c.voxel.x, c.voxel.y, c.voxel.z})
|
||||
put_signed(out, v);
|
||||
put(out, c.chunk_revision, 8);
|
||||
for (const auto v : {c.habitat.x, c.habitat.y, c.habitat.z, c.habitat.width, c.habitat.height,
|
||||
c.habitat.depth})
|
||||
put(out, static_cast<std::uint32_t>(v.value), 4); // Validated <= 1e6 um.
|
||||
put(out, c.volume.value, 8);
|
||||
put(out, c.substrate.value, 2);
|
||||
put(out, c.terrain_material.value, 2);
|
||||
put(out, c.terrain_fill, 2);
|
||||
for (std::size_t k = 0; k < world::field_count; ++k) {
|
||||
out.push_back(static_cast<std::uint8_t>(c.presence.at(k)));
|
||||
if (c.presence.at(k) == client::FieldPresence::present)
|
||||
put(out, c.quantity.at(k), 8);
|
||||
}
|
||||
out.push_back(static_cast<std::uint8_t>(c.moisture_status));
|
||||
if (c.moisture_status == world::MoistureStatus::available) {
|
||||
put(out, c.moisture.numerator, 8);
|
||||
put(out, c.moisture.denominator, 8);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> encode_record(const client::OrganismCell& c) {
|
||||
std::vector<std::uint8_t> out{static_cast<std::uint8_t>(RecordKind::organism_upsert)};
|
||||
const auto& p = c.phenotype;
|
||||
put(out, c.id, 8);
|
||||
for (const auto v : {c.voxel.x, c.voxel.y, c.voxel.z})
|
||||
put_signed(out, v);
|
||||
put(out, static_cast<std::uint32_t>(c.x.value), 4); // Validated < 1e6 um.
|
||||
put(out, static_cast<std::uint32_t>(c.y.value), 4);
|
||||
put(out, p.structural_mass, 8);
|
||||
put(out, p.membrane_mass, 8);
|
||||
put(out, p.total_mass, 8);
|
||||
put(out, p.extent, 4);
|
||||
put(out, p.surface, 8);
|
||||
put(out, p.maintenance, 8);
|
||||
put(out, p.movement_speed, 4);
|
||||
put(out, p.ingestion_rate, 8);
|
||||
put(out, p.conversion_per_thousand, 4);
|
||||
put(out, p.thermal_shortfall, 4);
|
||||
put(out, c.growth.realized_per_thousand, 4);
|
||||
put(out, c.growth.damage_per_thousand, 4);
|
||||
out.push_back(static_cast<std::uint8_t>(c.state));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::expected<ReplicationServer, ReplicationError> ReplicationServer::create(ReplicationLimits l) {
|
||||
if (l.max_radius == 0 || l.max_radius > 7 || l.near_radius > l.max_radius ||
|
||||
l.far_interval == 0 || l.max_baselines == 0 || l.max_baselines > 16 ||
|
||||
l.max_baseline_age == 0 || l.tick_budget_bytes < session_datagram_bytes ||
|
||||
l.tick_budget_bytes > std::size_t{max_chunks} * session_datagram_bytes ||
|
||||
l.max_sessions == 0 || l.max_sessions > 1024)
|
||||
return std::unexpected(ReplicationError::invalid_config);
|
||||
return ReplicationServer{l};
|
||||
}
|
||||
|
||||
std::expected<void, ReplicationError> ReplicationServer::open(std::uint64_t session,
|
||||
std::uint64_t epoch) {
|
||||
if (session == 0 || epoch == 0 ||
|
||||
std::ranges::any_of(sessions_, [&](const Session& s) { return s.id == session; }))
|
||||
return std::unexpected(ReplicationError::invalid_config);
|
||||
if (sessions_.size() >= limits_.max_sessions)
|
||||
return std::unexpected(ReplicationError::full);
|
||||
Session s;
|
||||
s.id = session;
|
||||
s.epoch = epoch;
|
||||
sessions_.push_back(std::move(s));
|
||||
return {};
|
||||
}
|
||||
|
||||
void ReplicationServer::close(std::uint64_t session) {
|
||||
std::erase_if(sessions_, [&](const Session& s) { return s.id == session; });
|
||||
}
|
||||
|
||||
std::expected<SessionInterest, ReplicationError>
|
||||
ReplicationServer::set_interest(std::uint64_t session, SessionInterest interest) {
|
||||
const auto it =
|
||||
std::ranges::find_if(sessions_, [&](const Session& s) { return s.id == session; });
|
||||
if (it == sessions_.end())
|
||||
return std::unexpected(ReplicationError::unknown_session);
|
||||
interest.radius = std::min(interest.radius, limits_.max_radius);
|
||||
if (it->interest != interest) {
|
||||
it->interest = interest;
|
||||
it->baselines.clear(); // Another area: start from a fresh baseline.
|
||||
it->acked = 0;
|
||||
}
|
||||
return interest;
|
||||
}
|
||||
|
||||
std::optional<SessionInterest> ReplicationServer::interest(std::uint64_t session) const {
|
||||
const auto it =
|
||||
std::ranges::find_if(sessions_, [&](const Session& s) { return s.id == session; });
|
||||
return it == sessions_.end() ? std::nullopt : it->interest;
|
||||
}
|
||||
|
||||
void ReplicationServer::acknowledge(std::uint64_t session, const SnapshotAck& ack) {
|
||||
const auto it =
|
||||
std::ranges::find_if(sessions_, [&](const Session& s) { return s.id == session; });
|
||||
if (it == sessions_.end() || ack.epoch != it->epoch || ack.tick <= it->acked)
|
||||
return;
|
||||
if (std::ranges::any_of(it->baselines, [&](const Snapshot& b) { return b.tick == ack.tick; }))
|
||||
it->acked = ack.tick;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::uint64_t, std::vector<SnapshotChunk>>>
|
||||
ReplicationServer::tick(std::uint64_t tick,
|
||||
const std::function<ReplicationSource(const SessionInterest&)>& source,
|
||||
const Perceives& perceives, std::size_t payload) {
|
||||
std::vector<std::pair<std::uint64_t, std::vector<SnapshotChunk>>> out;
|
||||
payload = std::min(payload, session_datagram_bytes);
|
||||
const auto overhead = session_header_bytes + snapshot_chunk_header_bytes;
|
||||
if (tick == 0 || payload <= overhead)
|
||||
return out;
|
||||
const auto capacity = payload - overhead; // Record bytes per chunk.
|
||||
std::vector<std::pair<SessionInterest, ReplicationSource>> sources;
|
||||
for (auto& s : sessions_) {
|
||||
if (!s.interest || (!s.baselines.empty() && s.baselines.back().tick >= tick))
|
||||
continue;
|
||||
const auto& in = *s.interest;
|
||||
auto cached = std::ranges::find_if(sources, [&](const auto& e) { return e.first == in; });
|
||||
if (cached == sources.end()) {
|
||||
sources.emplace_back(in, source(in));
|
||||
cached = std::prev(sources.end());
|
||||
}
|
||||
const auto& src = cached->second;
|
||||
// Spatial filter, then perception: nothing outside either is ever encoded.
|
||||
std::map<Key, std::pair<std::vector<std::uint8_t>, std::uint64_t>> truth;
|
||||
for (const auto& c : src.environment)
|
||||
if (c.voxel.z == in.z && distance(c.voxel.x, c.voxel.y, in) <= in.radius)
|
||||
truth[Key{std::uint8_t{1}, c.voxel.x, c.voxel.y, c.voxel.z}] = {
|
||||
encode_record(c), distance(c.voxel.x, c.voxel.y, in)};
|
||||
for (const auto& o : src.organisms)
|
||||
if (o.voxel.z == in.z && distance(o.voxel.x, o.voxel.y, in) <= in.radius &&
|
||||
(!perceives || perceives(s.id, o)))
|
||||
truth[Key{std::uint8_t{3}, static_cast<std::int64_t>(o.id), 0, 0}] = {
|
||||
encode_record(o), distance(o.voxel.x, o.voxel.y, in)};
|
||||
// Baselines older than the limit are forgotten; an expired ack means a fresh one.
|
||||
while (!s.baselines.empty() && tick - s.baselines.front().tick > limits_.max_baseline_age)
|
||||
s.baselines.pop_front();
|
||||
const auto base = std::ranges::find_if(
|
||||
s.baselines, [&](const Snapshot& b) { return s.acked != 0 && b.tick == s.acked; });
|
||||
const bool fresh = base == s.baselines.end();
|
||||
static const std::map<Key, Entry> empty;
|
||||
const auto& base_state = fresh ? empty : base->state;
|
||||
struct Candidate {
|
||||
std::uint64_t distance{}, staleness{};
|
||||
Key key;
|
||||
const std::vector<std::uint8_t>* record{};
|
||||
};
|
||||
std::vector<std::vector<std::uint8_t>> removals;
|
||||
std::vector<Key> removed;
|
||||
for (const auto& [key, entry] : base_state)
|
||||
if (!truth.contains(key)) {
|
||||
removals.push_back(
|
||||
std::get<0>(key) == 1
|
||||
? remove_environment({std::get<1>(key), std::get<2>(key), std::get<3>(key)})
|
||||
: remove_organism(static_cast<std::uint64_t>(std::get<1>(key))));
|
||||
removed.push_back(key);
|
||||
}
|
||||
std::vector<Candidate> candidates;
|
||||
std::uint64_t deferred = 0;
|
||||
for (const auto& [key, value] : truth) {
|
||||
const auto known = base_state.find(key);
|
||||
if (known != base_state.end() && known->second.record == value.first)
|
||||
continue; // The client already holds this value.
|
||||
const bool due = known == base_state.end() || value.second <= limits_.near_radius ||
|
||||
tick - known->second.updated >= limits_.far_interval;
|
||||
if (!due) {
|
||||
++deferred;
|
||||
continue;
|
||||
}
|
||||
const auto staleness = known == base_state.end()
|
||||
? std::numeric_limits<std::uint64_t>::max()
|
||||
: tick - known->second.updated;
|
||||
candidates.push_back({value.second, staleness, key, &value.first});
|
||||
}
|
||||
std::ranges::sort(candidates, [](const Candidate& a, const Candidate& b) {
|
||||
return std::tie(a.distance, b.staleness, a.key) <
|
||||
std::tie(b.distance, a.staleness, b.key);
|
||||
});
|
||||
// Pack whole records: removals first, then the nearest changes, within the budget.
|
||||
std::vector<std::vector<std::uint8_t>> chunks(1);
|
||||
std::size_t bytes = overhead;
|
||||
const auto fits = [&](const std::vector<std::uint8_t>& record) {
|
||||
if (chunks.back().size() + record.size() <= capacity) {
|
||||
if (bytes + record.size() > limits_.tick_budget_bytes)
|
||||
return false;
|
||||
} else {
|
||||
if (chunks.size() >= max_chunks || record.size() > capacity ||
|
||||
bytes + overhead + record.size() > limits_.tick_budget_bytes)
|
||||
return false;
|
||||
chunks.emplace_back();
|
||||
bytes += overhead;
|
||||
}
|
||||
chunks.back().insert(chunks.back().end(), record.begin(), record.end());
|
||||
bytes += record.size();
|
||||
return true;
|
||||
};
|
||||
auto state = base_state;
|
||||
std::uint64_t sent = 0;
|
||||
for (std::size_t i = 0; i < removals.size(); ++i) {
|
||||
if (!fits(removals[i])) {
|
||||
deferred += removals.size() - i; // Removed next tick; the client keeps them.
|
||||
break;
|
||||
}
|
||||
state.erase(removed[i]);
|
||||
++sent;
|
||||
}
|
||||
for (std::size_t i = 0; i < candidates.size(); ++i) {
|
||||
if (!fits(*candidates[i].record)) {
|
||||
deferred += candidates.size() - i;
|
||||
break;
|
||||
}
|
||||
state[candidates[i].key] = Entry{*candidates[i].record, tick};
|
||||
++sent;
|
||||
}
|
||||
std::vector<SnapshotChunk> messages;
|
||||
for (std::size_t i = 0; i < chunks.size(); ++i) {
|
||||
SnapshotChunk m;
|
||||
m.epoch = s.epoch;
|
||||
m.tick = tick;
|
||||
m.baseline = fresh ? 0 : base->tick;
|
||||
m.field_revision = src.field_revision;
|
||||
m.organism_revision = src.organism_revision;
|
||||
m.mask = src.mask;
|
||||
m.slice_z = in.z;
|
||||
m.index = static_cast<std::uint8_t>(i);
|
||||
m.count = static_cast<std::uint8_t>(chunks.size());
|
||||
m.records = std::move(chunks[i]);
|
||||
messages.push_back(std::move(m));
|
||||
}
|
||||
stats_.snapshots += 1;
|
||||
stats_.chunks += messages.size();
|
||||
stats_.bytes += bytes;
|
||||
stats_.deferred += deferred;
|
||||
stats_.fresh_baselines += fresh ? 1 : 0;
|
||||
stats_.records += sent;
|
||||
s.baselines.push_back({tick, std::move(state)});
|
||||
// Keep the acknowledged baseline (acks lag by the round trip) and the newest others.
|
||||
while (s.baselines.size() > limits_.max_baselines)
|
||||
s.baselines.erase(std::ranges::find_if(
|
||||
s.baselines, [&](const Snapshot& b) { return b.tick != s.acked; }));
|
||||
out.emplace_back(s.id, std::move(messages));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
ReplicationStats ReplicationServer::stats() const {
|
||||
auto s = stats_;
|
||||
s.retained_entities = 0;
|
||||
for (const auto& session : sessions_)
|
||||
for (const auto& b : session.baselines)
|
||||
s.retained_entities += b.state.size();
|
||||
return s;
|
||||
}
|
||||
|
||||
std::expected<std::optional<SnapshotAck>, AssemblyError>
|
||||
SnapshotAssembler::accept(const SnapshotChunk& chunk) {
|
||||
const std::uint64_t newest = applied_.empty() ? 0 : applied_.back().tick;
|
||||
if (chunk.epoch != epoch_ || chunk.tick <= newest)
|
||||
return std::optional<SnapshotAck>{}; // Stale or another epoch: ignored.
|
||||
auto found = partial_.find(chunk.tick);
|
||||
if (found == partial_.end()) {
|
||||
if (partial_.size() >= max_partial)
|
||||
partial_.erase(partial_.begin()); // The oldest assembly gives way.
|
||||
Partial p;
|
||||
p.first = chunk;
|
||||
p.first.records.clear();
|
||||
p.chunks.resize(chunk.count);
|
||||
found = partial_.emplace(chunk.tick, std::move(p)).first;
|
||||
}
|
||||
auto& p = found->second;
|
||||
const auto h = p.first; // A copy: the assembly entry is erased below.
|
||||
if (h.baseline != chunk.baseline || h.count != chunk.count || h.mask != chunk.mask ||
|
||||
h.slice_z != chunk.slice_z || h.field_revision != chunk.field_revision ||
|
||||
h.organism_revision != chunk.organism_revision)
|
||||
return std::unexpected(AssemblyError::malformed);
|
||||
if (!p.chunks.at(chunk.index))
|
||||
p.chunks.at(chunk.index) = chunk.records;
|
||||
if (std::ranges::any_of(p.chunks, [](const auto& c) { return !c.has_value(); }))
|
||||
return std::optional<SnapshotAck>{};
|
||||
// Complete: apply to its baseline, which must be one this client still holds.
|
||||
const ReplicatedView* base = nullptr;
|
||||
if (h.baseline != 0) {
|
||||
const auto it = std::ranges::find_if(
|
||||
applied_, [&](const ReplicatedView& v) { return v.tick == h.baseline; });
|
||||
if (it == applied_.end()) {
|
||||
partial_.erase(found);
|
||||
return std::optional<SnapshotAck>{}; // The server falls back to a fresh baseline.
|
||||
}
|
||||
base = &*it;
|
||||
}
|
||||
std::map<std::pair<std::int64_t, std::int64_t>, client::EnvironmentCell> environment;
|
||||
std::map<std::uint64_t, client::OrganismCell> organisms;
|
||||
if (base) {
|
||||
for (const auto& c : base->environment)
|
||||
environment[{c.voxel.x, c.voxel.y}] = c;
|
||||
for (const auto& o : base->organisms)
|
||||
organisms[o.id] = o;
|
||||
}
|
||||
for (const auto& records : p.chunks) {
|
||||
if (!records)
|
||||
return std::unexpected(AssemblyError::malformed); // Unreachable: all present.
|
||||
Reader r{*records};
|
||||
while (r.ok() && !r.done()) {
|
||||
const auto kind = r.u(1);
|
||||
if (kind == static_cast<std::uint8_t>(RecordKind::environment_upsert)) {
|
||||
client::EnvironmentCell c;
|
||||
c.voxel = {r.i64(), r.i64(), r.i64()};
|
||||
c.chunk_revision = r.u(8);
|
||||
c.habitat = {{r.u(4)}, {r.u(4)}, {r.u(4)}, {r.u(4)}, {r.u(4)}, {r.u(4)}};
|
||||
c.volume = {r.u(8)};
|
||||
c.substrate = {static_cast<std::uint16_t>(r.u(2))};
|
||||
c.terrain_material = {static_cast<std::uint16_t>(r.u(2))};
|
||||
c.terrain_fill = static_cast<std::uint16_t>(r.u(2));
|
||||
for (std::size_t k = 0; k < world::field_count; ++k) {
|
||||
c.presence.at(k) =
|
||||
static_cast<client::FieldPresence>(r.enumerator(last_presence));
|
||||
if (c.presence.at(k) == client::FieldPresence::present)
|
||||
c.quantity.at(k) = r.u(8);
|
||||
}
|
||||
c.moisture_status = static_cast<world::MoistureStatus>(r.enumerator(last_moisture));
|
||||
if (c.moisture_status == world::MoistureStatus::available)
|
||||
c.moisture = {r.u(8), r.u(8)};
|
||||
if (c.voxel.z != h.slice_z)
|
||||
return std::unexpected(AssemblyError::malformed);
|
||||
environment[{c.voxel.x, c.voxel.y}] = c;
|
||||
} else if (kind == static_cast<std::uint8_t>(RecordKind::environment_remove)) {
|
||||
const auto x = r.i64(), y = r.i64(), z = r.i64();
|
||||
if (z != h.slice_z)
|
||||
return std::unexpected(AssemblyError::malformed);
|
||||
environment.erase({x, y});
|
||||
} else if (kind == static_cast<std::uint8_t>(RecordKind::organism_upsert)) {
|
||||
client::OrganismCell o;
|
||||
o.id = r.u(8);
|
||||
o.voxel = {r.i64(), r.i64(), r.i64()};
|
||||
o.x = {r.u(4)};
|
||||
o.y = {r.u(4)};
|
||||
auto& ph = o.phenotype;
|
||||
ph.structural_mass = r.u(8);
|
||||
ph.membrane_mass = r.u(8);
|
||||
ph.total_mass = r.u(8);
|
||||
ph.extent = static_cast<std::uint32_t>(r.u(4));
|
||||
ph.surface = r.u(8);
|
||||
ph.maintenance = r.u(8);
|
||||
ph.movement_speed = static_cast<std::uint32_t>(r.u(4));
|
||||
ph.ingestion_rate = r.u(8);
|
||||
ph.conversion_per_thousand = static_cast<std::uint32_t>(r.u(4));
|
||||
ph.thermal_shortfall = static_cast<std::uint32_t>(r.u(4));
|
||||
o.growth.realized_per_thousand = static_cast<std::uint32_t>(r.u(4));
|
||||
o.growth.damage_per_thousand = static_cast<std::uint32_t>(r.u(4));
|
||||
o.state = static_cast<client::OrganismState>(r.enumerator(last_state));
|
||||
if (o.voxel.z != h.slice_z)
|
||||
return std::unexpected(AssemblyError::malformed);
|
||||
organisms[o.id] = o;
|
||||
} else if (kind == static_cast<std::uint8_t>(RecordKind::organism_remove)) {
|
||||
organisms.erase(r.u(8));
|
||||
} else {
|
||||
return std::unexpected(AssemblyError::malformed);
|
||||
}
|
||||
}
|
||||
if (!r.ok())
|
||||
return std::unexpected(AssemblyError::malformed);
|
||||
}
|
||||
ReplicatedView view;
|
||||
view.tick = h.tick;
|
||||
view.field_revision = h.field_revision;
|
||||
view.organism_revision = h.organism_revision;
|
||||
view.mask = h.mask;
|
||||
view.slice_z = h.slice_z;
|
||||
for (auto& [voxel, cell] : environment)
|
||||
view.environment.push_back(cell);
|
||||
for (auto& [id, organism] : organisms)
|
||||
view.organisms.push_back(organism);
|
||||
// The same validation as any presentation: a snapshot that cannot be shown is refused.
|
||||
if (!client::EnvironmentPresentation::create({identity_, view.tick, view.field_revision},
|
||||
view.mask, view.slice_z, view.environment) &&
|
||||
!view.environment.empty())
|
||||
return std::unexpected(AssemblyError::invalid_view);
|
||||
if (!client::OrganismPresentation::create({identity_, view.tick, view.organism_revision},
|
||||
view.slice_z, view.organisms))
|
||||
return std::unexpected(AssemblyError::invalid_view);
|
||||
applied_.push_back(std::move(view));
|
||||
while (applied_.size() > max_applied)
|
||||
applied_.pop_front();
|
||||
std::erase_if(partial_, [&](const auto& e) { return e.first <= h.tick; });
|
||||
return std::optional<SnapshotAck>{SnapshotAck{epoch_, applied_.back().tick}};
|
||||
}
|
||||
|
||||
std::expected<client::EnvironmentPresentation, client::ViewError>
|
||||
SnapshotAssembler::environment() const {
|
||||
if (applied_.empty())
|
||||
return std::unexpected(client::ViewError::empty_slice);
|
||||
const auto& v = applied_.back();
|
||||
return client::EnvironmentPresentation::create({identity_, v.tick, v.field_revision}, v.mask,
|
||||
v.slice_z, v.environment);
|
||||
}
|
||||
|
||||
std::expected<client::OrganismPresentation, client::ViewError>
|
||||
SnapshotAssembler::organisms() const {
|
||||
if (applied_.empty())
|
||||
return std::unexpected(client::ViewError::empty_slice);
|
||||
const auto& v = applied_.back();
|
||||
return client::OrganismPresentation::create({identity_, v.tick, v.organism_revision}, v.slice_z,
|
||||
v.organisms);
|
||||
}
|
||||
} // namespace evo::network
|
||||
@@ -16,6 +16,9 @@ constexpr std::size_t action_receipt_bytes = 8 + 1 + 8 + 8;
|
||||
constexpr std::size_t action_outcome_bytes = 8 + 1 + 8 + 8;
|
||||
constexpr std::size_t action_query_bytes = 8;
|
||||
constexpr std::uint8_t max_admit_status = static_cast<std::uint8_t>(AdmitStatus::not_ready);
|
||||
constexpr std::size_t interest_bytes = (3 * std::size_t{8}) + 2;
|
||||
constexpr std::size_t snapshot_ack_bytes = 2 * std::size_t{8};
|
||||
constexpr std::uint8_t max_snapshot_chunks = 16;
|
||||
|
||||
void put(std::vector<std::uint8_t>& out, std::uint64_t v, std::size_t count) {
|
||||
for (std::size_t i = 0; i < count; ++i)
|
||||
@@ -128,6 +131,32 @@ std::vector<std::uint8_t> encode_session(const SessionMessage& message) {
|
||||
put(out, m.action_id, 8);
|
||||
return out;
|
||||
}
|
||||
std::vector<std::uint8_t> operator()(const SessionInterest& m) const {
|
||||
auto out = header(SessionMessageType::interest, interest_bytes);
|
||||
for (const auto v : {m.x, m.y, m.z})
|
||||
put(out, static_cast<std::uint64_t>(v), 8);
|
||||
put(out, m.radius, 2);
|
||||
return out;
|
||||
}
|
||||
std::vector<std::uint8_t> operator()(const SnapshotChunk& m) const {
|
||||
auto out = header(SessionMessageType::snapshot_chunk,
|
||||
snapshot_chunk_header_bytes + m.records.size());
|
||||
for (const auto v :
|
||||
{m.epoch, m.tick, m.baseline, m.field_revision, m.organism_revision})
|
||||
put(out, v, 8);
|
||||
put(out, m.mask, 4);
|
||||
put(out, static_cast<std::uint64_t>(m.slice_z), 8);
|
||||
out.push_back(m.index);
|
||||
out.push_back(m.count);
|
||||
out.insert(out.end(), m.records.begin(), m.records.end());
|
||||
return out;
|
||||
}
|
||||
std::vector<std::uint8_t> operator()(const SnapshotAck& m) const {
|
||||
auto out = header(SessionMessageType::snapshot_ack, snapshot_ack_bytes);
|
||||
put(out, m.epoch, 8);
|
||||
put(out, m.tick, 8);
|
||||
return out;
|
||||
}
|
||||
};
|
||||
return std::visit(Encoder{}, message);
|
||||
}
|
||||
@@ -243,6 +272,40 @@ decode_session(std::span<const std::uint8_t> bytes) {
|
||||
return std::unexpected(SessionCodecError::wrong_length);
|
||||
return ActionQuery{get(payload, 0, 8)};
|
||||
}
|
||||
case static_cast<std::uint8_t>(SessionMessageType::interest): {
|
||||
if (!expect(interest_bytes))
|
||||
return std::unexpected(SessionCodecError::wrong_length);
|
||||
return SessionInterest{static_cast<std::int64_t>(get(payload, 0, 8)),
|
||||
static_cast<std::int64_t>(get(payload, 8, 8)),
|
||||
static_cast<std::int64_t>(get(payload, 16, 8)),
|
||||
static_cast<std::uint16_t>(get(payload, 24, 2))};
|
||||
}
|
||||
case static_cast<std::uint8_t>(SessionMessageType::snapshot_chunk): {
|
||||
// Variable length: a fixed header and up to one datagram of records.
|
||||
if (payload.size() < snapshot_chunk_header_bytes ||
|
||||
payload.size() > snapshot_chunk_header_bytes + max_snapshot_records_bytes)
|
||||
return std::unexpected(SessionCodecError::wrong_length);
|
||||
SnapshotChunk m;
|
||||
m.epoch = get(payload, 0, 8);
|
||||
m.tick = get(payload, 8, 8);
|
||||
m.baseline = get(payload, 16, 8);
|
||||
m.field_revision = get(payload, 24, 8);
|
||||
m.organism_revision = get(payload, 32, 8);
|
||||
m.mask = static_cast<std::uint32_t>(get(payload, 40, 4));
|
||||
m.slice_z = static_cast<std::int64_t>(get(payload, 44, 8));
|
||||
m.index = payload[52];
|
||||
m.count = payload[53];
|
||||
if (m.epoch == 0 || m.tick == 0 || m.baseline >= m.tick || m.count == 0 ||
|
||||
m.count > max_snapshot_chunks || m.index >= m.count)
|
||||
return std::unexpected(SessionCodecError::invalid_value);
|
||||
m.records.assign(payload.begin() + snapshot_chunk_header_bytes, payload.end());
|
||||
return m;
|
||||
}
|
||||
case static_cast<std::uint8_t>(SessionMessageType::snapshot_ack): {
|
||||
if (!expect(snapshot_ack_bytes))
|
||||
return std::unexpected(SessionCodecError::wrong_length);
|
||||
return SnapshotAck{get(payload, 0, 8), get(payload, 8, 8)};
|
||||
}
|
||||
default:
|
||||
return std::unexpected(SessionCodecError::unknown_type);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user