feat(admin): read-only admin portal and API (ADR-0182 step 1, schema 61)
evo-admin-api serves the portal at srs.aeternalisgames.com and read-only JSON for world 100 behind Keycloak (realm role aevolution-admin, audience aevolution-admin, client aevolution-admin-portal): accounts with session, status, lives, deaths, resets and mutation choices; one account's lives; the world's regions; and a live 2D region view of cells, wildlife, pools and bubbles. The portal is plain HTML/CSS/JS with PKCE sign-in, a strict CSP and no third-party code. - Schema 61: three bounded SECURITY DEFINER read functions, fenced in the privilege audit; no table or existing function changes. - Cellular regions answer GET /admin/view on the ops port (NetworkPolicy: Prometheus and the admin portal only); CellularLives::extent_of reads the existing phenotype budget. No simulation, checkpoint or wire change. - TokenVerifier takes an optional realm role and returns the email; the ops server's response bound is configurable (16 KiB default unchanged). - DEV component admin-portal-dev (Deployment, Service, NetworkPolicies); the Ingress and the aevolution-admin-pg Secret are created out of band. - CI scripts pinned to schema 60 now expect 61. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,375 @@
|
||||
#include "evo/server/admin/admin_api.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <charconv>
|
||||
#include <netdb.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace evo::server::admin {
|
||||
namespace {
|
||||
using broker::TokenError;
|
||||
|
||||
OpsResponse json(int status, std::string body) {
|
||||
return {status, std::move(body), "application/json"};
|
||||
}
|
||||
OpsResponse error(int status, std::string_view code) {
|
||||
return json(status, "{\"error\":\"" + std::string(code) + "\"}\n");
|
||||
}
|
||||
const char* token_error(TokenError e) {
|
||||
switch (e) {
|
||||
case TokenError::expired:
|
||||
return "token_expired";
|
||||
case TokenError::missing_role:
|
||||
return "not_an_admin";
|
||||
case TokenError::wrong_audience:
|
||||
case TokenError::wrong_party:
|
||||
case TokenError::wrong_issuer:
|
||||
case TokenError::wrong_type:
|
||||
return "token_not_for_this_service";
|
||||
default:
|
||||
return "invalid_token";
|
||||
}
|
||||
}
|
||||
bool is_uuid(std::string_view text) {
|
||||
if (text.size() != 36)
|
||||
return false;
|
||||
for (std::size_t i = 0; i < text.size(); ++i) {
|
||||
const char ch = text[i];
|
||||
if (i == 8 || i == 13 || i == 18 || i == 23
|
||||
? ch != '-'
|
||||
: !((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::optional<std::uint64_t> number(std::string_view text) {
|
||||
std::uint64_t value{};
|
||||
const auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), value);
|
||||
if (text.empty() || ec != std::errc{} || end != text.data() + text.size())
|
||||
return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
// Columns as JSON values: absent is null. Identities and ticks go out as strings (they may
|
||||
// exceed 2^53); counts and wall seconds as numbers.
|
||||
std::string text_value(const std::optional<std::string>& value) {
|
||||
return value ? json_string(*value) : "null";
|
||||
}
|
||||
std::string count_value(const std::optional<std::string>& value) {
|
||||
return value && number(*value) ? *value : "null";
|
||||
}
|
||||
std::string seconds_value(const std::optional<std::string>& value) {
|
||||
// Wall seconds before 1970 do not occur; a negative or absent value is null.
|
||||
return value && number(*value) ? *value : "null";
|
||||
}
|
||||
std::string bool_value(const std::optional<std::string>& value) {
|
||||
return value == "t" ? "true" : value == "f" ? "false" : "null";
|
||||
}
|
||||
const std::optional<std::string>& at(const std::vector<std::optional<std::string>>& row,
|
||||
std::size_t index) {
|
||||
static const std::optional<std::string> none;
|
||||
return index < row.size() ? row[index] : none;
|
||||
}
|
||||
|
||||
std::string account_json(const std::vector<std::optional<std::string>>& row) {
|
||||
// 0 account, 1 created, 2 issuer, 3 subject, 4 control region, 5 control expires,
|
||||
// 6 logged in, 7 lives, 8 deaths, 9 active life, 10 active region, 11 mutation choices.
|
||||
const auto lives = number(at(row, 7).value_or("0")).value_or(0);
|
||||
const bool alive = at(row, 9).has_value();
|
||||
const char* status = alive ? "alive" : lives > 0 ? "dead" : "no_life";
|
||||
return "{\"account\":" + text_value(at(row, 0)) +
|
||||
",\"created_at\":" + seconds_value(at(row, 1)) +
|
||||
",\"issuer\":" + text_value(at(row, 2)) + ",\"subject\":" + text_value(at(row, 3)) +
|
||||
",\"control_region\":" + text_value(at(row, 4)) +
|
||||
",\"control_expires\":" + seconds_value(at(row, 5)) +
|
||||
",\"logged_in\":" + (at(row, 6) == "t" ? "true" : "false") + ",\"status\":\"" + status +
|
||||
"\",\"lives\":" + std::to_string(lives) + ",\"deaths\":" + count_value(at(row, 8)) +
|
||||
",\"resets\":" + std::to_string(lives > 0 ? lives - 1 : 0) +
|
||||
",\"active_life\":" + text_value(at(row, 9)) +
|
||||
",\"active_region\":" + text_value(at(row, 10)) +
|
||||
",\"mutation_choices\":" + count_value(at(row, 11)) + "}";
|
||||
}
|
||||
|
||||
const std::string accounts_sql =
|
||||
"SELECT account_id::text, floor(extract(epoch FROM created_at))::bigint, issuer, subject, "
|
||||
"control_region, floor(extract(epoch FROM control_expires))::bigint, "
|
||||
"control_expires > clock_timestamp(), lives, deaths, active_life, active_region, "
|
||||
"mutation_choices FROM evolution.admin_accounts_v1($1)";
|
||||
|
||||
struct Socket {
|
||||
int fd{-1};
|
||||
Socket(const Socket&) = delete;
|
||||
Socket& operator=(const Socket&) = delete;
|
||||
explicit Socket(int value) : fd{value} {}
|
||||
~Socket() {
|
||||
if (fd >= 0)
|
||||
::close(fd);
|
||||
}
|
||||
};
|
||||
// Waits for `events` on the socket until the deadline.
|
||||
bool wait(int fd, short events, std::chrono::steady_clock::time_point deadline) {
|
||||
for (;;) {
|
||||
const auto left = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
deadline - std::chrono::steady_clock::now());
|
||||
if (left.count() <= 0)
|
||||
return false;
|
||||
pollfd entry{fd, events, 0};
|
||||
const int ready = ::poll(&entry, 1, static_cast<int>(left.count()));
|
||||
if (ready > 0)
|
||||
return true;
|
||||
if (ready < 0 && errno != EINTR)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string json_string(std::string_view text) {
|
||||
constexpr std::string_view digits = "0123456789abcdef";
|
||||
std::string out = "\"";
|
||||
for (const char ch : text) {
|
||||
const auto byte = static_cast<unsigned char>(ch);
|
||||
if (ch == '"' || ch == '\\') {
|
||||
out.push_back('\\');
|
||||
out.push_back(ch);
|
||||
} else if (byte < 0x20 || byte == 0x7F) {
|
||||
out += "\\u00";
|
||||
out.push_back(digits[byte >> 4U]);
|
||||
out.push_back(digits[byte & 0x0FU]);
|
||||
} else {
|
||||
out.push_back(ch);
|
||||
}
|
||||
}
|
||||
return out + "\"";
|
||||
}
|
||||
|
||||
std::optional<std::string> http_get(std::string_view address, std::string_view path,
|
||||
std::chrono::milliseconds timeout, std::size_t limit) {
|
||||
const auto colon = address.rfind(':');
|
||||
if (colon == std::string_view::npos || colon == 0 || colon + 1 >= address.size() ||
|
||||
path.empty() || path.front() != '/')
|
||||
return std::nullopt;
|
||||
auto host = std::string(address.substr(0, colon));
|
||||
const auto port = std::string(address.substr(colon + 1));
|
||||
if (host.size() >= 2 && host.front() == '[' && host.back() == ']')
|
||||
host = host.substr(1, host.size() - 2);
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
addrinfo hints{};
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
addrinfo* found = nullptr;
|
||||
if (::getaddrinfo(host.c_str(), port.c_str(), &hints, &found) != 0 || found == nullptr)
|
||||
return std::nullopt;
|
||||
const std::unique_ptr<addrinfo, decltype(&::freeaddrinfo)> results{found, ::freeaddrinfo};
|
||||
for (const addrinfo* candidate = found; candidate != nullptr; candidate = candidate->ai_next) {
|
||||
Socket socket{::socket(candidate->ai_family,
|
||||
candidate->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC,
|
||||
candidate->ai_protocol)};
|
||||
if (socket.fd < 0)
|
||||
continue;
|
||||
if (::connect(socket.fd, candidate->ai_addr, candidate->ai_addrlen) != 0) {
|
||||
int failure = 0;
|
||||
socklen_t length = sizeof failure;
|
||||
if (errno != EINPROGRESS || !wait(socket.fd, POLLOUT, deadline) ||
|
||||
::getsockopt(socket.fd, SOL_SOCKET, SO_ERROR, &failure, &length) != 0 ||
|
||||
failure != 0)
|
||||
continue;
|
||||
}
|
||||
const std::string request = "GET " + std::string(path) + " HTTP/1.1\r\nHost: " + host +
|
||||
"\r\nConnection: close\r\n\r\n";
|
||||
std::size_t sent = 0;
|
||||
while (sent < request.size()) {
|
||||
if (!wait(socket.fd, POLLOUT, deadline))
|
||||
return std::nullopt;
|
||||
const auto n =
|
||||
::send(socket.fd, request.data() + sent, request.size() - sent, MSG_NOSIGNAL);
|
||||
if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
|
||||
return std::nullopt;
|
||||
if (n > 0)
|
||||
sent += static_cast<std::size_t>(n);
|
||||
}
|
||||
constexpr std::size_t header_room = 4096;
|
||||
std::string answer;
|
||||
for (;;) {
|
||||
if (!wait(socket.fd, POLLIN, deadline))
|
||||
return std::nullopt;
|
||||
char chunk[16384];
|
||||
const auto n = ::recv(socket.fd, chunk, sizeof chunk, 0);
|
||||
if (n == 0)
|
||||
break;
|
||||
if (n < 0) {
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
|
||||
continue;
|
||||
return std::nullopt;
|
||||
}
|
||||
answer.append(chunk, static_cast<std::size_t>(n));
|
||||
if (answer.size() > limit + header_room)
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto end = answer.find("\r\n\r\n");
|
||||
if (end == std::string::npos || answer.rfind("HTTP/1.1 200 ", 0) != 0)
|
||||
return std::nullopt;
|
||||
auto body = answer.substr(end + 4);
|
||||
if (body.size() > limit)
|
||||
return std::nullopt;
|
||||
return body;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
AdminApi::AdminApi(AdminConfig config, broker::TokenVerifier verifier, AdminConnect connect,
|
||||
AdminRegionView view, std::vector<AdminAsset> assets)
|
||||
: config_{std::move(config)}, verifier_{std::move(verifier)}, connect_{std::move(connect)},
|
||||
view_{std::move(view)}, assets_{std::move(assets)} {}
|
||||
|
||||
OpsResponse AdminApi::handle(const ApiRequest& request, std::uint64_t now_seconds,
|
||||
std::chrono::steady_clock::time_point now) {
|
||||
auto path = request.path.substr(0, request.path.find('?'));
|
||||
if (request.method != "GET")
|
||||
return {405, "method not allowed\n"};
|
||||
if (path == "/healthz")
|
||||
return {200, "ok\n"};
|
||||
if (path == "/config.json")
|
||||
return json(200, config_.portal_config_json);
|
||||
if (!path.starts_with("/api/")) {
|
||||
if (path == "/")
|
||||
path = "/index.html";
|
||||
const auto asset = std::ranges::find(assets_, path, &AdminAsset::path);
|
||||
if (asset == assets_.end())
|
||||
return {404, "not found\n"};
|
||||
OpsResponse response{200, asset->body, asset->content_type};
|
||||
response.headers = "Content-Security-Policy: " + config_.content_security_policy +
|
||||
"\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer"
|
||||
"\r\nX-Frame-Options: DENY\r\n";
|
||||
return response;
|
||||
}
|
||||
auto authorization = request.authorization;
|
||||
constexpr std::string_view scheme = "bearer ";
|
||||
if (authorization.size() <= scheme.size() ||
|
||||
!std::ranges::equal(authorization.substr(0, scheme.size()), scheme,
|
||||
[](char a, char b) { return (a | 0x20) == b; }))
|
||||
return error(401, "missing_token");
|
||||
authorization.remove_prefix(scheme.size());
|
||||
const auto claims = verifier_.verify(authorization, now_seconds);
|
||||
if (!claims)
|
||||
return error(claims.error() == TokenError::missing_role ? 403 : 401,
|
||||
token_error(claims.error()));
|
||||
return api(path, *claims, now);
|
||||
}
|
||||
|
||||
OpsResponse AdminApi::api(std::string_view path, const broker::AccessTokenClaims& admin,
|
||||
std::chrono::steady_clock::time_point now) {
|
||||
if (path == "/api/me")
|
||||
return json(200, "{\"subject\":" + json_string(admin.subject) +
|
||||
",\"email\":" + json_string(admin.email) +
|
||||
",\"world\":" + std::to_string(config_.world) + "}\n");
|
||||
if (path == "/api/accounts")
|
||||
return accounts(std::nullopt);
|
||||
constexpr std::string_view account_prefix = "/api/accounts/";
|
||||
if (path.starts_with(account_prefix)) {
|
||||
const auto id = path.substr(account_prefix.size());
|
||||
return is_uuid(id) ? accounts(id) : error(404, "not_found");
|
||||
}
|
||||
if (path == "/api/regions")
|
||||
return regions();
|
||||
constexpr std::string_view region_prefix = "/api/regions/";
|
||||
constexpr std::string_view view_suffix = "/view";
|
||||
if (path.starts_with(region_prefix) && path.ends_with(view_suffix)) {
|
||||
const auto region = number(path.substr(
|
||||
region_prefix.size(), path.size() - region_prefix.size() - view_suffix.size()));
|
||||
return region ? view(*region, now) : error(404, "not_found");
|
||||
}
|
||||
return error(404, "not_found");
|
||||
}
|
||||
|
||||
std::optional<persistence::PgRows> AdminApi::query(const std::string& sql,
|
||||
std::vector<std::string> parameters) {
|
||||
if (!db_ && connect_)
|
||||
db_ = connect_();
|
||||
if (!db_)
|
||||
return std::nullopt;
|
||||
auto rows = db_->query(sql, parameters, config_.db_timeout);
|
||||
if (!rows) {
|
||||
db_.reset();
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::move(*rows);
|
||||
}
|
||||
|
||||
OpsResponse AdminApi::accounts(std::optional<std::string_view> account) {
|
||||
const auto world = std::to_string(config_.world);
|
||||
if (!account) {
|
||||
const auto rows = query(accounts_sql, {world});
|
||||
if (!rows)
|
||||
return error(503, "unavailable");
|
||||
std::string out = "{\"world\":" + world + ",\"accounts\":[";
|
||||
for (std::size_t i = 0; i < rows->size(); ++i)
|
||||
out += (i == 0 ? "" : ",") + account_json((*rows)[i]);
|
||||
return json(200, out + "]}\n");
|
||||
}
|
||||
const auto rows =
|
||||
query(accounts_sql + " WHERE account_id = $2::uuid", {world, std::string(*account)});
|
||||
if (!rows)
|
||||
return error(503, "unavailable");
|
||||
if (rows->empty())
|
||||
return error(404, "not_found");
|
||||
const auto lives = query("SELECT request_id, identity, region_id, rejection, born, ended_tick, "
|
||||
"floor(extract(epoch FROM ended_at))::bigint "
|
||||
"FROM evolution.admin_account_lives_v1($1, $2::uuid)",
|
||||
{world, std::string(*account)});
|
||||
if (!lives)
|
||||
return error(503, "unavailable");
|
||||
std::string out =
|
||||
"{\"world\":" + world + ",\"account\":" + account_json(rows->front()) + ",\"lives\":[";
|
||||
for (std::size_t i = 0; i < lives->size(); ++i) {
|
||||
const auto& row = (*lives)[i];
|
||||
out += std::string(i == 0 ? "" : ",") + "{\"request\":" + text_value(at(row, 0)) +
|
||||
",\"identity\":" + text_value(at(row, 1)) + ",\"region\":" + text_value(at(row, 2)) +
|
||||
",\"rejection\":" + count_value(at(row, 3)) + ",\"born\":" + text_value(at(row, 4)) +
|
||||
",\"ended_tick\":" + text_value(at(row, 5)) +
|
||||
",\"ended_at\":" + seconds_value(at(row, 6)) + "}";
|
||||
}
|
||||
return json(200, out + "]}\n");
|
||||
}
|
||||
|
||||
OpsResponse AdminApi::regions() {
|
||||
const auto world = std::to_string(config_.world);
|
||||
const auto rows = query("SELECT region_id, frame_id, lease_epoch, lease_held, "
|
||||
"floor(extract(epoch FROM lease_expires))::bigint, commit_sequence, "
|
||||
"end_tick, floor(extract(epoch FROM committed_at))::bigint, "
|
||||
"build_identity FROM evolution.admin_regions_v1($1)",
|
||||
{world});
|
||||
if (!rows)
|
||||
return error(503, "unavailable");
|
||||
std::string out = "{\"world\":" + world + ",\"regions\":[";
|
||||
for (std::size_t i = 0; i < rows->size(); ++i) {
|
||||
const auto& row = (*rows)[i];
|
||||
const auto region = number(at(row, 0).value_or(""));
|
||||
const bool viewable = region && std::ranges::contains(config_.view_regions, *region);
|
||||
out += std::string(i == 0 ? "" : ",") + "{\"region\":" + text_value(at(row, 0)) +
|
||||
",\"frame\":" + text_value(at(row, 1)) +
|
||||
",\"lease_epoch\":" + text_value(at(row, 2)) +
|
||||
",\"lease_held\":" + bool_value(at(row, 3)) +
|
||||
",\"lease_expires\":" + seconds_value(at(row, 4)) +
|
||||
",\"sequence\":" + text_value(at(row, 5)) + ",\"tick\":" + text_value(at(row, 6)) +
|
||||
",\"committed_at\":" + seconds_value(at(row, 7)) +
|
||||
",\"build\":" + text_value(at(row, 8)) +
|
||||
",\"viewable\":" + (viewable ? "true" : "false") + "}";
|
||||
}
|
||||
return json(200, out + "]}\n");
|
||||
}
|
||||
|
||||
OpsResponse AdminApi::view(std::uint64_t region, std::chrono::steady_clock::time_point now) {
|
||||
if (!std::ranges::contains(config_.view_regions, region))
|
||||
return error(404, "not_viewable");
|
||||
const auto cached = views_.find(region);
|
||||
if (cached != views_.end() && now - cached->second.at < config_.view_cache)
|
||||
return json(200, cached->second.body);
|
||||
auto body = view_ ? view_(region) : std::nullopt;
|
||||
if (!body)
|
||||
return error(503, "region_unavailable");
|
||||
views_[region] = {now, *body};
|
||||
return json(200, std::move(*body));
|
||||
}
|
||||
} // namespace evo::server::admin
|
||||
@@ -211,6 +211,17 @@ TokenVerifier::verify(std::string_view token, std::uint64_t now_seconds) const {
|
||||
const auto subject = text("sub");
|
||||
if (!subject || subject->empty() || subject->size() > 255)
|
||||
return std::unexpected{TokenError::missing_subject};
|
||||
return AccessTokenClaims{rules_.issuer, std::string(*subject), *expires};
|
||||
if (!rules_.realm_role.empty()) {
|
||||
const auto* realm = payload->member("realm_access");
|
||||
const auto* roles = realm ? realm->member("roles") : nullptr;
|
||||
if (!roles || !roles->array() ||
|
||||
std::ranges::none_of(*roles->array(), [&](const JsonValue& role) {
|
||||
return role.string() == rules_.realm_role;
|
||||
}))
|
||||
return std::unexpected{TokenError::missing_role};
|
||||
}
|
||||
const auto email = text("email");
|
||||
return AccessTokenClaims{rules_.issuer, std::string(*subject), *expires,
|
||||
email && email->size() <= 254 ? std::string(*email) : std::string{}};
|
||||
}
|
||||
} // namespace evo::server::broker
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
#include "evo/server/lifecycle/cellular_admin_view.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace evo::server {
|
||||
namespace {
|
||||
void append(std::string& out, std::uint64_t value) {
|
||||
out += std::to_string(value);
|
||||
}
|
||||
void append_inventory(std::string& out, const accounting::Inventory& inventory) {
|
||||
append(out, inventory.energy.value);
|
||||
for (const auto& channel : inventory.matter) {
|
||||
out.push_back(',');
|
||||
append(out, channel.value);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string cellular_account_text(const LifeAccount& account) {
|
||||
constexpr std::string_view digits = "0123456789abcdef";
|
||||
std::string out;
|
||||
out.reserve(36);
|
||||
for (std::size_t i = 0; i < account.size(); ++i) {
|
||||
if (i == 4 || i == 6 || i == 8 || i == 10)
|
||||
out.push_back('-');
|
||||
out.push_back(digits[account[i] >> 4U]);
|
||||
out.push_back(digits[account[i] & 0x0FU]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string render_cellular_admin_view(const CellularLives& state,
|
||||
const CellularAdminOnline& online,
|
||||
CellularAdminViewLimits limits) {
|
||||
const auto lives = state.lives();
|
||||
const auto patches = state.habitat().patches();
|
||||
std::string out;
|
||||
out.reserve(256 + std::min(lives.size(), limits.cells) * 128 +
|
||||
std::min(patches.size(), limits.deposits) * 64);
|
||||
out += "{\"world\":";
|
||||
append(out, state.world());
|
||||
out += ",\"region\":";
|
||||
append(out, state.region());
|
||||
out += ",\"tick\":";
|
||||
append(out, state.tick());
|
||||
out += ",\"rules\":";
|
||||
append(out, state.rules_version());
|
||||
out += ",\"area\":[";
|
||||
append(out, state.area().width_um);
|
||||
out.push_back(',');
|
||||
append(out, state.area().height_um);
|
||||
out += "],\"spent\":[";
|
||||
append_inventory(out, state.spent());
|
||||
out += "],\"cells_total\":";
|
||||
append(out, lives.size());
|
||||
out += ",\"deposits_total\":";
|
||||
append(out, patches.size());
|
||||
|
||||
// Lives are kept in ascending life id; a prefix is the lowest ids.
|
||||
out += ",\"cells\":[";
|
||||
const auto cells = std::min(lives.size(), limits.cells);
|
||||
for (std::size_t i = 0; i < cells; ++i) {
|
||||
const auto& life = lives[i];
|
||||
const bool wildlife = life.account == LifeAccount{};
|
||||
std::uint64_t flags = wildlife ? 1U : 0U;
|
||||
if (!wildlife && online && online(life.account))
|
||||
flags |= 2U;
|
||||
if (life.presence == CellularPresence::lingering)
|
||||
flags |= 4U;
|
||||
if (life.presence == CellularPresence::suspended)
|
||||
flags |= 8U;
|
||||
std::uint64_t body_mass{};
|
||||
for (const auto& channel : life.body.matter)
|
||||
body_mass += channel.value;
|
||||
if (i != 0)
|
||||
out.push_back(',');
|
||||
out += "[\"";
|
||||
append(out, life.identity.life);
|
||||
out += "\",\"";
|
||||
append(out, life.identity.organism);
|
||||
out += "\",\"";
|
||||
if (!wildlife)
|
||||
out += cellular_account_text(life.account);
|
||||
out += "\",";
|
||||
append(out, life.position.x_um);
|
||||
out.push_back(',');
|
||||
append(out, life.position.y_um);
|
||||
out.push_back(',');
|
||||
append(out, state.extent_of(life).value_or(0));
|
||||
out.push_back(',');
|
||||
append(out, flags);
|
||||
out.push_back(',');
|
||||
append(out, life.revamp.members);
|
||||
out.push_back(',');
|
||||
append_inventory(out, life.reserve);
|
||||
out.push_back(',');
|
||||
append(out, body_mass);
|
||||
out.push_back(']');
|
||||
}
|
||||
|
||||
// Patches are kept by address; the view lists them by ascending id.
|
||||
std::vector<const biology::CellularPatch*> listed;
|
||||
listed.reserve(patches.size());
|
||||
for (const auto& patch : patches)
|
||||
listed.push_back(&patch);
|
||||
const auto deposits = std::min(listed.size(), limits.deposits);
|
||||
std::ranges::partial_sort(listed, listed.begin() + static_cast<std::ptrdiff_t>(deposits), {},
|
||||
[](const biology::CellularPatch* patch) { return patch->id; });
|
||||
out += "],\"deposits\":[";
|
||||
for (std::size_t i = 0; i < deposits; ++i) {
|
||||
const auto& patch = *listed[i];
|
||||
if (i != 0)
|
||||
out.push_back(',');
|
||||
out.push_back('[');
|
||||
append(out, patch.id);
|
||||
out.push_back(',');
|
||||
append(out, static_cast<std::uint64_t>(patch.kind));
|
||||
out.push_back(',');
|
||||
append(out, patch.address.x_um);
|
||||
out.push_back(',');
|
||||
append(out, patch.address.y_um);
|
||||
out.push_back(',');
|
||||
append(out, patch.radius_um);
|
||||
out.push_back(',');
|
||||
append_inventory(out, patch.stock);
|
||||
out.push_back(']');
|
||||
}
|
||||
out += "]}\n";
|
||||
return out;
|
||||
}
|
||||
} // namespace evo::server
|
||||
@@ -1127,6 +1127,13 @@ accounting::Inventory CellularLives::heat() const noexcept {
|
||||
accounting::Inventory CellularLives::spent() const noexcept {
|
||||
return state_->spent;
|
||||
}
|
||||
std::optional<std::uint32_t> CellularLives::extent_of(const CellularOwnedLife& life) const {
|
||||
const auto budget = budget_for(
|
||||
state_->archive, life, state_->config.ambient_temperature_millikelvin, state_->revamp.body);
|
||||
if (!budget)
|
||||
return std::nullopt;
|
||||
return budget->phenotype.extent;
|
||||
}
|
||||
accounting::Inventory CellularLives::opening_total() const noexcept {
|
||||
return state_->opening_total;
|
||||
}
|
||||
|
||||
+10
-4
@@ -17,6 +17,8 @@ const char* reason(int status) {
|
||||
return "Bad Request";
|
||||
case 401:
|
||||
return "Unauthorized";
|
||||
case 403:
|
||||
return "Forbidden";
|
||||
case 404:
|
||||
return "Not Found";
|
||||
case 429:
|
||||
@@ -40,6 +42,7 @@ std::string encode(const OpsResponse& r) {
|
||||
out += "Allow: GET, POST\r\n";
|
||||
if (r.status == 401)
|
||||
out += "WWW-Authenticate: Bearer\r\n";
|
||||
out += r.headers;
|
||||
return out + "\r\n" + r.body;
|
||||
}
|
||||
bool printable(std::string_view s) {
|
||||
@@ -50,7 +53,10 @@ bool printable(std::string_view s) {
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::expected<std::unique_ptr<OpsServer>, OpsError> OpsServer::listen(std::string_view address) {
|
||||
std::expected<std::unique_ptr<OpsServer>, OpsError> OpsServer::listen(std::string_view address,
|
||||
std::size_t response_limit) {
|
||||
if (response_limit == 0 || response_limit > max_configurable_response_bytes)
|
||||
return std::unexpected{OpsError::address};
|
||||
const auto colon = address.rfind(':');
|
||||
if (colon == std::string_view::npos || colon + 1 >= address.size())
|
||||
return std::unexpected{OpsError::address};
|
||||
@@ -96,7 +102,7 @@ std::expected<std::unique_ptr<OpsServer>, OpsError> OpsServer::listen(std::strin
|
||||
const auto actual = family == AF_INET6
|
||||
? ntohs(reinterpret_cast<sockaddr_in6*>(&bound)->sin6_port)
|
||||
: ntohs(reinterpret_cast<sockaddr_in*>(&bound)->sin_port);
|
||||
return std::unique_ptr<OpsServer>(new OpsServer(fd, actual));
|
||||
return std::unique_ptr<OpsServer>(new OpsServer(fd, actual, response_limit));
|
||||
}
|
||||
|
||||
OpsServer::~OpsServer() {
|
||||
@@ -123,7 +129,7 @@ void OpsServer::respond(Connection& c, const OpsHandler& handler) {
|
||||
else
|
||||
response = handler(path);
|
||||
}
|
||||
if (response.body.size() > max_response_bytes)
|
||||
if (response.body.size() > response_limit_)
|
||||
response = {500, "response too large\n"};
|
||||
c.out = encode(response);
|
||||
}
|
||||
@@ -172,7 +178,7 @@ void OpsServer::respond_api(Connection& c, const ApiHandler& handler) {
|
||||
response = {400, "bad request\n"};
|
||||
else
|
||||
response = handler({method, path, authorization});
|
||||
if (response.body.size() > max_response_bytes)
|
||||
if (response.body.size() > response_limit_)
|
||||
response = {500, "response too large\n"};
|
||||
c.out = encode(response);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user