Compare commits
31
Commits
bc1eeb970b
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d9cc122aa | ||
|
|
9de55e352d | ||
|
|
2ce8c3afb1 | ||
|
|
6de2b7b1ca | ||
|
|
8085392122 | ||
|
|
3c753970c8 | ||
|
|
8005e7c4ae | ||
|
|
757304437e | ||
|
|
51aa08446d | ||
|
|
9b854e6960 | ||
|
|
e0f9512567 | ||
|
|
23ea24080e | ||
|
|
8dedde454d | ||
|
|
cc2eaf2e05 | ||
|
|
944f6719cf | ||
|
|
c481a7fe5e | ||
|
|
2fc50df26c | ||
|
|
6338cc9142 | ||
|
|
68f2567253 | ||
|
|
7273b157d6 | ||
|
|
7041c947a9 | ||
|
|
018b4b1817 | ||
|
|
2485a028bb | ||
|
|
070c458dc5 | ||
|
|
b3eca78549 | ||
|
|
b1cc3b121b | ||
|
|
b075198040 | ||
|
|
46c106409e | ||
|
|
510ecaee80 | ||
|
|
4adcc7b638 | ||
|
|
d851717b7b |
@@ -25,7 +25,6 @@ limits in docs/engineering/VALIDATION.md. Preserve uncommitted work by others.
|
|||||||
|
|
||||||
After each completed and validated gate segment, commit its scoped changes and push
|
After each completed and validated gate segment, commit its scoped changes and push
|
||||||
to the configured Git remote. Preserve unrelated untracked work; never stage secrets.
|
to the configured Git remote. Preserve unrelated untracked work; never stage secrets.
|
||||||
Immediately before each push, refresh REGION_SESSION_WINDOW in
|
The dev session window lives in SQL and is opened from the admin portal (ADR-0087
|
||||||
deploy/kubernetes/region/dev-session-route/listener.yaml with a unique activation
|
amendment of 2026-10-27); Git carries no window. Do not deploy or claim live
|
||||||
and absolute UTC expiry four hours ahead (ADR-0087). Include it in that push;
|
reachability from a Git update alone.
|
||||||
do not deploy or claim live reachability from a Git update alone.
|
|
||||||
|
|||||||
+5
-2
@@ -312,8 +312,11 @@ if(EVO_BUILD_POSTGRES)
|
|||||||
target_link_libraries(evo-grant-broker PRIVATE evo_grant_broker)
|
target_link_libraries(evo-grant-broker PRIVATE evo_grant_broker)
|
||||||
evo_owned_target(evo-grant-broker)
|
evo_owned_target(evo-grant-broker)
|
||||||
# ADR-0182 read-only admin API and portal host (schema v61).
|
# ADR-0182 read-only admin API and portal host (schema v61).
|
||||||
add_library(evo_admin_api STATIC src/server/admin/admin_api.cpp)
|
# Section 15: its HTTPS client to Gitea and Argo CD (OpenSSL libssl) and the region switch.
|
||||||
target_link_libraries(evo_admin_api PUBLIC evo_grant_broker)
|
find_package(OpenSSL 3 REQUIRED COMPONENTS Crypto SSL)
|
||||||
|
add_library(evo_admin_api STATIC src/server/admin/admin_api.cpp
|
||||||
|
src/server/admin/https_client.cpp src/server/admin/region_switch.cpp)
|
||||||
|
target_link_libraries(evo_admin_api PUBLIC evo_grant_broker PRIVATE OpenSSL::SSL OpenSSL::Crypto)
|
||||||
evo_owned_target(evo_admin_api)
|
evo_owned_target(evo_admin_api)
|
||||||
add_executable(evo-admin-api apps/evo-admin-api/main.cpp)
|
add_executable(evo-admin-api apps/evo-admin-api/main.cpp)
|
||||||
target_link_libraries(evo-admin-api PRIVATE evo_admin_api)
|
target_link_libraries(evo-admin-api PRIVATE evo_admin_api)
|
||||||
|
|||||||
@@ -2,10 +2,16 @@
|
|||||||
//
|
//
|
||||||
// evo-admin-api --listen ADDRESS:PORT --world N --jwks JSON --oidc-issuer URL
|
// evo-admin-api --listen ADDRESS:PORT --world N --jwks JSON --oidc-issuer URL
|
||||||
// --audience NAME --client NAME --role NAME --assets DIR
|
// --audience NAME --client NAME --role NAME --assets DIR
|
||||||
// --pg-passfile F --pg-service F [--region REGION=HOST:PORT ...]
|
// --pg-passfile F --pg-service F [--region REGION=HOST:PORT ...] [--baseline-tuning F]
|
||||||
|
// [--region-tuning F] [--deploy-config DIR]
|
||||||
//
|
//
|
||||||
// --assets holds the portal's index.html, app.js and style.css. Each --region names a
|
// --assets holds the portal's index.html, app.js and style.css. Each --region names a
|
||||||
// region's operations address, whose /admin/view the portal may show. No token is printed.
|
// region's operations address, whose /admin/view the portal may show; those regions adopt
|
||||||
|
// tuning revisions. --baseline-tuning is the revamp tuning file they opened with, shown
|
||||||
|
// until the first revision; --region-tuning the region tuning file they start with, shown
|
||||||
|
// read only. --deploy-config is the mounted Secret holding the Gitea and Argo CD settings and
|
||||||
|
// tokens (one file per key) that let the portal open a region (ADR-0182 section 15); without
|
||||||
|
// it, or with a key missing, that feature stays off. No token is printed.
|
||||||
#include "evo/persistence/postgres.hpp"
|
#include "evo/persistence/postgres.hpp"
|
||||||
#include "evo/server/admin/admin_api.hpp"
|
#include "evo/server/admin/admin_api.hpp"
|
||||||
|
|
||||||
@@ -33,7 +39,8 @@ void on_stop(int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct Options {
|
struct Options {
|
||||||
std::string listen, jwks, oidc_issuer, audience, client, role, assets;
|
std::string listen, jwks, oidc_issuer, audience, client, role, assets, baseline_tuning,
|
||||||
|
region_tuning, deploy_config;
|
||||||
std::uint64_t world{};
|
std::uint64_t world{};
|
||||||
std::map<std::uint64_t, std::string> regions; // Region to its operations address.
|
std::map<std::uint64_t, std::string> regions; // Region to its operations address.
|
||||||
persistence::PgOptions pg;
|
persistence::PgOptions pg;
|
||||||
@@ -70,6 +77,12 @@ std::optional<Options> parse(int argc, char** argv) {
|
|||||||
o.role = value;
|
o.role = value;
|
||||||
else if (flag == "--assets")
|
else if (flag == "--assets")
|
||||||
o.assets = value;
|
o.assets = value;
|
||||||
|
else if (flag == "--baseline-tuning")
|
||||||
|
o.baseline_tuning = value;
|
||||||
|
else if (flag == "--region-tuning")
|
||||||
|
o.region_tuning = value;
|
||||||
|
else if (flag == "--deploy-config")
|
||||||
|
o.deploy_config = value;
|
||||||
else if (flag == "--pg-service")
|
else if (flag == "--pg-service")
|
||||||
pg_service = value;
|
pg_service = value;
|
||||||
else if (flag == "--pg-passfile")
|
else if (flag == "--pg-passfile")
|
||||||
@@ -157,6 +170,22 @@ int main(int argc, char** argv) {
|
|||||||
config.world = options->world;
|
config.world = options->world;
|
||||||
for (const auto& [region, address] : options->regions)
|
for (const auto& [region, address] : options->regions)
|
||||||
config.view_regions.push_back(region);
|
config.view_regions.push_back(region);
|
||||||
|
if (!options->baseline_tuning.empty()) {
|
||||||
|
auto baseline = read_file(options->baseline_tuning);
|
||||||
|
if (!baseline) {
|
||||||
|
std::puts("error baseline-tuning");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
config.baseline_tuning = std::move(*baseline);
|
||||||
|
}
|
||||||
|
if (!options->region_tuning.empty()) {
|
||||||
|
auto region = read_file(options->region_tuning);
|
||||||
|
if (!region) {
|
||||||
|
std::puts("error region-tuning");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
config.region_tuning = std::move(*region);
|
||||||
|
}
|
||||||
config.portal_config_json = "{\"issuer\":\"" + options->oidc_issuer + "\",\"client_id\":\"" +
|
config.portal_config_json = "{\"issuer\":\"" + options->oidc_issuer + "\",\"client_id\":\"" +
|
||||||
options->client + "\",\"world\":" + std::to_string(options->world) +
|
options->client + "\",\"world\":" + std::to_string(options->world) +
|
||||||
"}\n";
|
"}\n";
|
||||||
@@ -187,13 +216,44 @@ int main(int argc, char** argv) {
|
|||||||
server::OpsServer::max_configurable_response_bytes);
|
server::OpsServer::max_configurable_response_bytes);
|
||||||
},
|
},
|
||||||
std::move(assets)};
|
std::move(assets)};
|
||||||
|
// ADR-0182 section 15: the portal opens regions only when every deploy key is present.
|
||||||
|
if (!options->deploy_config.empty()) {
|
||||||
|
const auto key = [&](const char* name) {
|
||||||
|
auto text = read_file(options->deploy_config + "/" + name).value_or("");
|
||||||
|
while (!text.empty() &&
|
||||||
|
(text.back() == '\n' || text.back() == '\r' || text.back() == ' '))
|
||||||
|
text.pop_back();
|
||||||
|
return text;
|
||||||
|
};
|
||||||
|
server::admin::AdminDeployConfig deploy{.gitea_base = key("GITEA_BASE_URL"),
|
||||||
|
.gitea_repository = key("GITEA_REPOSITORY"),
|
||||||
|
.gitea_token = key("GITEA_TOKEN"),
|
||||||
|
.branch = "main",
|
||||||
|
.argo_server = key("ARGOCD_SERVER"),
|
||||||
|
.argo_application = key("ARGOCD_APPLICATION"),
|
||||||
|
.argo_token = key("ARGOCD_TOKEN"),
|
||||||
|
.argo_verify = key("ARGOCD_TLS_VERIFY") != "false"};
|
||||||
|
if (deploy.gitea_base.empty() || deploy.gitea_repository.empty() ||
|
||||||
|
deploy.gitea_token.empty() || deploy.argo_server.empty() ||
|
||||||
|
deploy.argo_application.empty() || deploy.argo_token.empty()) {
|
||||||
|
std::puts("deploy disabled (incomplete configuration)");
|
||||||
|
} else {
|
||||||
|
std::printf("deploy enabled repository %s application %s argo-verify %s\n",
|
||||||
|
deploy.gitea_repository.c_str(), deploy.argo_application.c_str(),
|
||||||
|
deploy.argo_verify ? "yes" : "no");
|
||||||
|
api.enable_deploy(std::move(deploy), server::admin::https_request);
|
||||||
|
}
|
||||||
|
}
|
||||||
std::printf("admin api listening %u world %llu\n", static_cast<unsigned>((*listening)->port()),
|
std::printf("admin api listening %u world %llu\n", static_cast<unsigned>((*listening)->port()),
|
||||||
static_cast<unsigned long long>(options->world));
|
static_cast<unsigned long long>(options->world));
|
||||||
std::fflush(stdout);
|
std::fflush(stdout);
|
||||||
while (stop_requested == 0) {
|
while (stop_requested == 0) {
|
||||||
(*listening)->serve_api([&](const server::ApiRequest& request) {
|
(*listening)
|
||||||
|
->serve_api(
|
||||||
|
[&](const server::ApiRequest& request) {
|
||||||
return api.handle(request, wall_seconds(), std::chrono::steady_clock::now());
|
return api.handle(request, wall_seconds(), std::chrono::steady_clock::now());
|
||||||
});
|
},
|
||||||
|
server::OpsServer::max_api_body_bytes); // Tuning texts (ADR-0182 section 13).
|
||||||
std::this_thread::sleep_for(5ms);
|
std::this_thread::sleep_for(5ms);
|
||||||
}
|
}
|
||||||
std::puts("admin api stopped");
|
std::puts("admin api stopped");
|
||||||
|
|||||||
+1574
-139
File diff suppressed because it is too large
Load Diff
@@ -16,10 +16,17 @@
|
|||||||
<span class="section-name">Cellular</span>
|
<span class="section-name">Cellular</span>
|
||||||
<a href="#/accounts" data-route="accounts">Accounts</a>
|
<a href="#/accounts" data-route="accounts">Accounts</a>
|
||||||
<a href="#/regions" data-route="regions">Regions</a>
|
<a href="#/regions" data-route="regions">Regions</a>
|
||||||
|
<a href="#/tuning" data-route="tuning">Tuning</a>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
<div class="who">
|
<div class="who">
|
||||||
<span id="who" class="muted"></span>
|
<span id="env" class="env" hidden></span>
|
||||||
|
<div class="theme-switch" role="group" aria-label="Theme">
|
||||||
|
<button type="button" data-theme-choice="system" title="Follow the system">Auto</button>
|
||||||
|
<button type="button" data-theme-choice="light" title="Light">☀</button>
|
||||||
|
<button type="button" data-theme-choice="dark" title="Dark">☾</button>
|
||||||
|
</div>
|
||||||
|
<span id="who" class="muted small"></span>
|
||||||
<button id="sign-out" class="ghost" hidden>Sign out</button>
|
<button id="sign-out" class="ghost" hidden>Sign out</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
+543
-102
@@ -1,184 +1,625 @@
|
|||||||
/* ADR-0182 admin portal. Tokens first; dark is the default, light follows the system. */
|
/* ADR-0182 admin portal. Tokens first: light by default, dark from the system or the header's
|
||||||
|
theme switch (html[data-theme]). The region map reads the map tokens when it paints. */
|
||||||
:root {
|
:root {
|
||||||
--bg: #0f1419;
|
--bg: #f3f5f8;
|
||||||
--panel: #161d24;
|
--panel: #ffffff;
|
||||||
--panel-2: #1c252e;
|
--panel-2: #f6f8fa;
|
||||||
--line: #2a3640;
|
--panel-3: #eef1f5;
|
||||||
--text: #dbe3ea;
|
--line: #e1e6ec;
|
||||||
--muted: #8a99a6;
|
--line-strong: #cfd6de;
|
||||||
--accent: #4fb3ff;
|
--text: #17202a;
|
||||||
|
--muted: #5f6c79;
|
||||||
|
--faint: #8b96a2;
|
||||||
|
--accent: #2563eb;
|
||||||
|
--accent-soft: rgba(37, 99, 235, 0.1);
|
||||||
|
--on-accent: #ffffff;
|
||||||
|
--good: #15925f;
|
||||||
|
--good-soft: rgba(21, 146, 95, 0.1);
|
||||||
|
--warn: #b7791f;
|
||||||
|
--warn-soft: rgba(183, 121, 31, 0.12);
|
||||||
|
--bad: #d64545;
|
||||||
|
--bad-soft: rgba(214, 69, 69, 0.1);
|
||||||
|
--shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 1px 3px rgba(16, 24, 40, 0.06);
|
||||||
|
--shadow-pop: 0 8px 24px rgba(16, 24, 40, 0.14);
|
||||||
|
/* Region map. */
|
||||||
|
--map-bg: #fbfcfd;
|
||||||
|
--map-grid: rgba(23, 32, 42, 0.05);
|
||||||
|
--map-edge: #cfd6de;
|
||||||
|
--map-glass: rgba(255, 255, 255, 0.86);
|
||||||
|
--player: #2f6fed;
|
||||||
|
--online: #06b6d4;
|
||||||
|
--wildlife: #16a34a;
|
||||||
|
--pool: rgba(37, 99, 235, 0.1);
|
||||||
|
--pool-edge: rgba(37, 99, 235, 0.45);
|
||||||
|
--patch: rgba(120, 90, 40, 0.14);
|
||||||
|
--select: #f59e0b;
|
||||||
|
--energy: #eab308;
|
||||||
|
--carbon: #4b5563;
|
||||||
|
--nitrogen: #8b5cf6;
|
||||||
|
--phosphorus: #f97316;
|
||||||
|
--other: #ec4899;
|
||||||
|
--radius: 10px;
|
||||||
|
--radius-sm: 7px;
|
||||||
|
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) {
|
||||||
|
--bg: #0b0f14;
|
||||||
|
--panel: #121820;
|
||||||
|
--panel-2: #161e27;
|
||||||
|
--panel-3: #1c2531;
|
||||||
|
--line: #232d3a;
|
||||||
|
--line-strong: #2f3b4b;
|
||||||
|
--text: #e4eaf0;
|
||||||
|
--muted: #8d9aa8;
|
||||||
|
--faint: #64717f;
|
||||||
|
--accent: #5b9dff;
|
||||||
|
--accent-soft: rgba(91, 157, 255, 0.14);
|
||||||
|
--on-accent: #06101f;
|
||||||
--good: #3ecf8e;
|
--good: #3ecf8e;
|
||||||
|
--good-soft: rgba(62, 207, 142, 0.12);
|
||||||
--warn: #f2b84b;
|
--warn: #f2b84b;
|
||||||
|
--warn-soft: rgba(242, 184, 75, 0.13);
|
||||||
--bad: #ff6b6b;
|
--bad: #ff6b6b;
|
||||||
--player: #4f8dff;
|
--bad-soft: rgba(255, 107, 107, 0.12);
|
||||||
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||||
|
--shadow-pop: 0 10px 30px rgba(0, 0, 0, 0.55);
|
||||||
|
--map-bg: #070b10;
|
||||||
|
--map-grid: rgba(140, 170, 200, 0.06);
|
||||||
|
--map-edge: #2a3646;
|
||||||
|
--map-glass: rgba(18, 24, 32, 0.86);
|
||||||
|
--player: #5b9dff;
|
||||||
--online: #5ff2ff;
|
--online: #5ff2ff;
|
||||||
--wildlife: #3ecf8e;
|
--wildlife: #3ecf8e;
|
||||||
--pool: rgba(120, 170, 255, 0.16);
|
--pool: rgba(91, 157, 255, 0.12);
|
||||||
|
--pool-edge: rgba(91, 157, 255, 0.5);
|
||||||
|
--patch: rgba(200, 160, 90, 0.14);
|
||||||
|
--select: #ffd166;
|
||||||
--energy: #ffd84d;
|
--energy: #ffd84d;
|
||||||
--carbon: #b0b7bf;
|
--carbon: #a3adb8;
|
||||||
--nitrogen: #9b7bff;
|
--nitrogen: #a78bfa;
|
||||||
--phosphorus: #ff9a3c;
|
--phosphorus: #ff9a3c;
|
||||||
--other: #ff6fb5;
|
--other: #ff6fb5;
|
||||||
--radius: 8px;
|
|
||||||
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
}
|
|
||||||
@media (prefers-color-scheme: light) {
|
|
||||||
:root {
|
|
||||||
--bg: #f5f7f9;
|
|
||||||
--panel: #ffffff;
|
|
||||||
--panel-2: #eef2f5;
|
|
||||||
--line: #d6dde3;
|
|
||||||
--text: #18212a;
|
|
||||||
--muted: #5d6b77;
|
|
||||||
--accent: #0b6bcb;
|
|
||||||
--pool: rgba(30, 90, 200, 0.12);
|
|
||||||
--carbon: #59626b;
|
|
||||||
color-scheme: light;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--bg: #0b0f14;
|
||||||
|
--panel: #121820;
|
||||||
|
--panel-2: #161e27;
|
||||||
|
--panel-3: #1c2531;
|
||||||
|
--line: #232d3a;
|
||||||
|
--line-strong: #2f3b4b;
|
||||||
|
--text: #e4eaf0;
|
||||||
|
--muted: #8d9aa8;
|
||||||
|
--faint: #64717f;
|
||||||
|
--accent: #5b9dff;
|
||||||
|
--accent-soft: rgba(91, 157, 255, 0.14);
|
||||||
|
--on-accent: #06101f;
|
||||||
|
--good: #3ecf8e;
|
||||||
|
--good-soft: rgba(62, 207, 142, 0.12);
|
||||||
|
--warn: #f2b84b;
|
||||||
|
--warn-soft: rgba(242, 184, 75, 0.13);
|
||||||
|
--bad: #ff6b6b;
|
||||||
|
--bad-soft: rgba(255, 107, 107, 0.12);
|
||||||
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||||
|
--shadow-pop: 0 10px 30px rgba(0, 0, 0, 0.55);
|
||||||
|
--map-bg: #070b10;
|
||||||
|
--map-grid: rgba(140, 170, 200, 0.06);
|
||||||
|
--map-edge: #2a3646;
|
||||||
|
--map-glass: rgba(18, 24, 32, 0.86);
|
||||||
|
--player: #5b9dff;
|
||||||
|
--online: #5ff2ff;
|
||||||
|
--wildlife: #3ecf8e;
|
||||||
|
--pool: rgba(91, 157, 255, 0.12);
|
||||||
|
--pool-edge: rgba(91, 157, 255, 0.5);
|
||||||
|
--patch: rgba(200, 160, 90, 0.14);
|
||||||
|
--select: #ffd166;
|
||||||
|
--energy: #ffd84d;
|
||||||
|
--carbon: #a3adb8;
|
||||||
|
--nitrogen: #a78bfa;
|
||||||
|
--phosphorus: #ff9a3c;
|
||||||
|
--other: #ff6fb5;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Base ---------- */
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
|
[hidden] { display: none !important; }
|
||||||
html, body { margin: 0; }
|
html, body { margin: 0; }
|
||||||
body {
|
body {
|
||||||
background: var(--bg);
|
background: var(--bg);
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
}
|
}
|
||||||
a { color: var(--accent); text-decoration: none; }
|
a { color: var(--accent); text-decoration: none; }
|
||||||
a:hover { text-decoration: underline; }
|
a:hover { text-decoration: underline; }
|
||||||
|
h1 { font-size: 22px; font-weight: 650; letter-spacing: -0.01em; margin: 0; }
|
||||||
|
h2 { font-size: 15px; font-weight: 600; margin: 0 0 10px; }
|
||||||
|
h3 { font-size: 13px; font-weight: 600; margin: 0; }
|
||||||
|
.muted { color: var(--muted); }
|
||||||
|
.faint { color: var(--faint); }
|
||||||
|
.mono { font-family: var(--mono); font-size: 12.5px; }
|
||||||
|
.num { font-variant-numeric: tabular-nums; }
|
||||||
|
.error { color: var(--bad); }
|
||||||
|
.good { color: var(--good); }
|
||||||
|
.small { font-size: 12px; }
|
||||||
|
.center { display: grid; place-items: center; min-height: 55vh; text-align: center; }
|
||||||
|
.center h1 { margin-bottom: 6px; }
|
||||||
|
.center .muted { margin-bottom: 18px; }
|
||||||
|
|
||||||
button {
|
button {
|
||||||
font: inherit;
|
font: inherit;
|
||||||
|
font-weight: 500;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
background: var(--panel-2);
|
background: var(--panel);
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line-strong);
|
||||||
border-radius: 6px;
|
border-radius: var(--radius-sm);
|
||||||
padding: 5px 12px;
|
padding: 6px 13px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
button:hover { border-color: var(--accent); }
|
button:hover { border-color: var(--accent); color: var(--accent); }
|
||||||
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
button:disabled { opacity: 0.5; cursor: default; }
|
||||||
button.ghost { background: transparent; }
|
button:disabled:hover { border-color: var(--line-strong); color: var(--text); }
|
||||||
input[type="search"] {
|
button.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
|
||||||
|
button.primary:hover { filter: brightness(1.08); color: var(--on-accent); }
|
||||||
|
button.ghost { background: transparent; border-color: transparent; color: var(--muted); }
|
||||||
|
button.ghost:hover { background: var(--panel-3); color: var(--text); }
|
||||||
|
button.danger { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 45%, transparent); }
|
||||||
|
button.danger:hover { background: var(--bad-soft); border-color: var(--bad); }
|
||||||
|
button.icon { padding: 5px 9px; line-height: 1; }
|
||||||
|
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
|
||||||
|
input[type="search"], input[type="text"], input[type="number"], select {
|
||||||
font: inherit;
|
font: inherit;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
background: var(--panel);
|
background: var(--panel);
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line-strong);
|
||||||
border-radius: 6px;
|
border-radius: var(--radius-sm);
|
||||||
padding: 5px 10px;
|
padding: 6px 10px;
|
||||||
min-width: 240px;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
.muted { color: var(--muted); }
|
input:focus, select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
|
||||||
.mono { font-family: var(--mono); font-size: 12.5px; }
|
input[type="search"] { width: 280px; }
|
||||||
|
input[type="checkbox"] { accent-color: var(--accent); }
|
||||||
|
|
||||||
|
/* ---------- Top bar ---------- */
|
||||||
.bar {
|
.bar {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 24px;
|
gap: 28px;
|
||||||
padding: 10px 20px;
|
height: 56px;
|
||||||
background: var(--panel);
|
padding: 0 22px;
|
||||||
|
background: color-mix(in srgb, var(--panel) 88%, transparent);
|
||||||
|
backdrop-filter: saturate(1.4) blur(10px);
|
||||||
border-bottom: 1px solid var(--line);
|
border-bottom: 1px solid var(--line);
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: 0;
|
top: 0;
|
||||||
z-index: 2;
|
z-index: 10;
|
||||||
}
|
}
|
||||||
.brand { font-weight: 700; color: var(--text); letter-spacing: 0.02em; }
|
.brand { display: flex; align-items: center; gap: 9px; font-weight: 700; color: var(--text); letter-spacing: 0.01em; }
|
||||||
.brand span { color: var(--accent); font-weight: 500; }
|
.brand:hover { text-decoration: none; }
|
||||||
|
.brand::before {
|
||||||
|
content: "";
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: radial-gradient(circle at 35% 35%, var(--online), var(--player) 55%, var(--wildlife));
|
||||||
|
box-shadow: 0 0 12px color-mix(in srgb, var(--online) 45%, transparent);
|
||||||
|
}
|
||||||
|
.brand span { color: var(--muted); font-weight: 500; }
|
||||||
.sections { display: flex; gap: 20px; flex: 1; }
|
.sections { display: flex; gap: 20px; flex: 1; }
|
||||||
.section { display: flex; align-items: center; gap: 4px; }
|
.section { display: flex; align-items: center; gap: 2px; }
|
||||||
.section-name {
|
.section-name {
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
font-size: 11px;
|
font-size: 10.5px;
|
||||||
letter-spacing: 0.08em;
|
font-weight: 600;
|
||||||
color: var(--muted);
|
letter-spacing: 0.1em;
|
||||||
margin-right: 6px;
|
color: var(--faint);
|
||||||
|
margin-right: 10px;
|
||||||
}
|
}
|
||||||
.section a { padding: 5px 10px; border-radius: 6px; color: var(--text); }
|
.section a { padding: 6px 12px; border-radius: var(--radius-sm); color: var(--muted); font-weight: 500; }
|
||||||
.section a.active { background: var(--panel-2); color: var(--accent); }
|
.section a:hover { color: var(--text); background: var(--panel-3); text-decoration: none; }
|
||||||
.who { display: flex; align-items: center; gap: 10px; }
|
.section a.active { background: var(--accent-soft); color: var(--accent); }
|
||||||
|
.who { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.env {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--warn);
|
||||||
|
background: var(--warn-soft);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 2px 9px;
|
||||||
|
}
|
||||||
|
.theme-switch { display: flex; background: var(--panel-3); border-radius: 999px; padding: 2px; }
|
||||||
|
.theme-switch button {
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--muted);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 3px 9px;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
.theme-switch button:hover { color: var(--text); }
|
||||||
|
.theme-switch button.on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
|
||||||
|
|
||||||
main { padding: 20px; max-width: 1600px; margin: 0 auto; }
|
/* ---------- Page ---------- */
|
||||||
h1 { font-size: 20px; margin: 0 0 4px; }
|
main { padding: 22px 24px 40px; max-width: 1760px; margin: 0 auto; }
|
||||||
h2 { font-size: 15px; margin: 20px 0 8px; }
|
main:focus { outline: none; }
|
||||||
.head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }
|
.head { display: flex; align-items: flex-end; justify-content: space-between; gap: 14px; flex-wrap: wrap; margin-bottom: 18px; }
|
||||||
|
.head .crumb { display: inline-block; font-size: 12.5px; margin-bottom: 4px; color: var(--muted); }
|
||||||
|
.head .crumb:hover { color: var(--accent); }
|
||||||
|
.title-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||||
.tools { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
.tools { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
||||||
|
.subtitle { color: var(--muted); margin-top: 3px; }
|
||||||
|
|
||||||
.card {
|
.card {
|
||||||
background: var(--panel);
|
background: var(--panel);
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line);
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
padding: 14px 16px;
|
padding: 16px 18px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
}
|
}
|
||||||
.stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin-bottom: 14px; }
|
.card + .card { margin-top: 14px; }
|
||||||
.stat { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 12px; }
|
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; }
|
||||||
.stat .label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); }
|
.card-head h2 { margin: 0; }
|
||||||
.stat .value { font-size: 18px; font-weight: 600; margin-top: 2px; }
|
|
||||||
.stat .value small { font-size: 12px; font-weight: 400; color: var(--muted); }
|
|
||||||
|
|
||||||
.table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); }
|
.stats, .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-bottom: 18px; }
|
||||||
|
.stat, .kpi {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 12px 14px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.stat .label, .kpi .label {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.07em;
|
||||||
|
color: var(--muted);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.stat .value, .kpi .value { font-size: 21px; font-weight: 650; margin-top: 4px; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.stat .value small { font-size: 12px; font-weight: 400; color: var(--muted); }
|
||||||
|
.kpi .sub { font-size: 12px; color: var(--muted); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.kpi.warn { border-color: color-mix(in srgb, var(--warn) 55%, var(--line)); }
|
||||||
|
.kpi.warn .value { color: var(--warn); }
|
||||||
|
.kpi.bad { border-color: color-mix(in srgb, var(--bad) 55%, var(--line)); }
|
||||||
|
.kpi.bad .value { color: var(--bad); }
|
||||||
|
.kpi .meter { margin-top: 8px; }
|
||||||
|
|
||||||
|
.meter { height: 5px; border-radius: 999px; background: var(--panel-3); overflow: hidden; }
|
||||||
|
.meter > span { display: block; height: 100%; background: var(--accent); border-radius: 999px; }
|
||||||
|
.meter.warn > span { background: var(--warn); }
|
||||||
|
.meter.bad > span { background: var(--bad); }
|
||||||
|
.meter.smooth > span { transition: width 0.25s linear; }
|
||||||
|
|
||||||
|
/* ---------- Tables ---------- */
|
||||||
|
.table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); background: var(--panel); }
|
||||||
table { border-collapse: collapse; width: 100%; background: var(--panel); }
|
table { border-collapse: collapse; width: 100%; background: var(--panel); }
|
||||||
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; }
|
th, td { text-align: left; padding: 9px 12px; border-bottom: 1px solid var(--line); white-space: nowrap; }
|
||||||
th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--panel-2); cursor: pointer; user-select: none; }
|
tbody tr:last-child td { border-bottom: 0; }
|
||||||
|
th { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--panel-2); cursor: pointer; user-select: none; }
|
||||||
|
th.sorted { color: var(--text); }
|
||||||
th.sorted::after { content: " ▾"; }
|
th.sorted::after { content: " ▾"; }
|
||||||
th.sorted.up::after { content: " ▴"; }
|
th.sorted.up::after { content: " ▴"; }
|
||||||
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||||
tbody tr:hover { background: var(--panel-2); }
|
tbody tr:hover { background: var(--panel-2); }
|
||||||
tbody tr.clickable { cursor: pointer; }
|
tbody tr.clickable { cursor: pointer; }
|
||||||
|
table.compact { font-size: 12.5px; background: transparent; }
|
||||||
|
table.compact td { padding: 6px 4px; white-space: normal; vertical-align: top; }
|
||||||
|
table.compact tr:hover { background: transparent; }
|
||||||
|
|
||||||
.badge {
|
.badge {
|
||||||
display: inline-block;
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
font-size: 11.5px;
|
font-size: 11.5px;
|
||||||
padding: 1px 8px;
|
font-weight: 500;
|
||||||
|
padding: 1px 9px;
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
border: 1px solid var(--line);
|
background: var(--panel-3);
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
.badge.alive { color: var(--good); border-color: var(--good); }
|
.badge.alive { color: var(--good); background: var(--good-soft); }
|
||||||
.badge.dead { color: var(--bad); border-color: var(--bad); }
|
.badge.dead { color: var(--bad); background: var(--bad-soft); }
|
||||||
.badge.online { color: var(--online); border-color: var(--online); }
|
.badge.online { color: var(--accent); background: var(--accent-soft); }
|
||||||
.badge.warn { color: var(--warn); border-color: var(--warn); }
|
.badge.warn { color: var(--warn); background: var(--warn-soft); }
|
||||||
|
.badge .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
|
||||||
|
.badge .dot.pulse { animation: pulse 1.6s ease-in-out infinite; }
|
||||||
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
|
||||||
|
|
||||||
dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; margin: 0; }
|
dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 7px 18px; margin: 0; }
|
||||||
dl.facts dt { color: var(--muted); }
|
dl.facts dt { color: var(--muted); }
|
||||||
dl.facts dd { margin: 0; }
|
dl.facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
|
||||||
|
.window-controls { display: flex; gap: 8px; margin: 12px 0 8px; flex-wrap: wrap; }
|
||||||
|
|
||||||
.region-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 14px; }
|
/* ---------- Region page ---------- */
|
||||||
@media (max-width: 1000px) { .region-layout { grid-template-columns: 1fr; } }
|
.region-grid { display: grid; grid-template-columns: minmax(0, 1fr) clamp(420px, 30vw, 560px); gap: 16px; align-items: start; }
|
||||||
.canvas-wrap {
|
@media (max-width: 1150px) { .region-grid { grid-template-columns: minmax(0, 1fr); } }
|
||||||
position: relative;
|
|
||||||
background: var(--panel);
|
.map-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: max(560px, calc(100vh - 250px));
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line);
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
|
background: var(--panel);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
aspect-ratio: 1 / 1;
|
box-shadow: var(--shadow);
|
||||||
max-height: calc(100vh - 230px);
|
}
|
||||||
width: 100%;
|
.map-toolbar { display: flex; align-items: flex-start; gap: 12px; padding: 10px 12px; border-bottom: 1px solid var(--line); }
|
||||||
|
.map-stage { position: relative; flex: 1; min-height: 0; background: var(--map-bg); overflow: hidden; }
|
||||||
|
.map-stage canvas { position: absolute; inset: 0; display: block; width: 100%; height: 100%; cursor: crosshair; }
|
||||||
|
.map-stage canvas.dragging { cursor: grabbing; }
|
||||||
|
.glass {
|
||||||
|
background: var(--map-glass);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
.map-layers { flex: 1; display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.chip {
|
||||||
|
display: inline-flex;
|
||||||
|
background: var(--panel-2);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 500;
|
||||||
|
padding: 4px 10px 4px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
color: var(--text);
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.chip .count { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||||
|
.chip.off { opacity: 0.45; }
|
||||||
|
.chip.off .swatch { background: transparent !important; }
|
||||||
|
.chip:hover { border-color: var(--accent); }
|
||||||
|
.map-zoom { display: flex; overflow: hidden; flex: none; border: 1px solid var(--line-strong); border-radius: var(--radius-sm); }
|
||||||
|
.map-zoom button { border: 0; border-radius: 0; background: transparent; padding: 5px 11px; font-size: 15px; line-height: 1.2; }
|
||||||
|
.map-zoom button + button { border-left: 1px solid var(--line); }
|
||||||
|
.map-zoom button:hover { background: var(--panel-3); }
|
||||||
|
.map-foot { position: absolute; left: 12px; right: 12px; bottom: 10px; display: flex; justify-content: space-between; align-items: flex-end; gap: 10px; pointer-events: none; }
|
||||||
|
.map-hint { font-size: 12px; color: var(--muted); padding: 3px 9px; }
|
||||||
|
.mark-bar { position: absolute; left: 12px; top: 12px; display: flex; align-items: center; gap: 8px; padding: 6px 8px 6px 12px; font-size: 13px; font-weight: 500; }
|
||||||
|
.mark-bar button { padding: 3px 10px; }
|
||||||
|
.scale { font-size: 11.5px; color: var(--muted); padding: 4px 9px 3px; text-align: center; }
|
||||||
|
.scale .rule { height: 6px; border: 1.5px solid var(--muted); border-top: 0; margin-top: 2px; }
|
||||||
|
.map-banner {
|
||||||
|
position: absolute;
|
||||||
|
left: 50%;
|
||||||
|
top: 12px;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
padding: 6px 14px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--warn);
|
||||||
|
border-color: color-mix(in srgb, var(--warn) 50%, var(--line));
|
||||||
}
|
}
|
||||||
.canvas-wrap canvas { display: block; width: 100%; height: 100%; cursor: crosshair; }
|
|
||||||
.overlay-note { position: absolute; left: 10px; bottom: 8px; font-size: 12px; color: var(--muted); pointer-events: none; }
|
|
||||||
.tooltip {
|
.tooltip {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
background: var(--panel-2);
|
padding: 8px 10px;
|
||||||
border: 1px solid var(--line);
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 6px 8px;
|
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
max-width: 280px;
|
min-width: 170px;
|
||||||
z-index: 1;
|
max-width: 290px;
|
||||||
|
z-index: 3;
|
||||||
|
box-shadow: var(--shadow-pop);
|
||||||
}
|
}
|
||||||
.side { display: flex; flex-direction: column; gap: 12px; }
|
.tooltip .tip-title { font-weight: 600; margin-bottom: 4px; display: flex; align-items: center; gap: 6px; }
|
||||||
.legend { display: grid; grid-template-columns: 14px 1fr; gap: 6px 8px; align-items: center; font-size: 13px; }
|
.tooltip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
|
||||||
.swatch { width: 12px; height: 12px; border-radius: 50%; }
|
.tooltip .tip-row span:first-child { color: var(--muted); }
|
||||||
|
|
||||||
|
.swatch { width: 10px; height: 10px; border-radius: 50%; flex: none; display: inline-block; }
|
||||||
.swatch.player { background: var(--player); }
|
.swatch.player { background: var(--player); }
|
||||||
.swatch.online { background: var(--online); }
|
.swatch.online { background: var(--online); }
|
||||||
.swatch.wildlife { background: var(--wildlife); }
|
.swatch.wildlife { background: var(--wildlife); }
|
||||||
.swatch.pool { background: var(--pool); border: 1px solid var(--accent); }
|
.swatch.pool { background: var(--pool); border: 1.5px solid var(--pool-edge); }
|
||||||
|
.swatch.patch { background: var(--patch); border: 1.5px solid var(--faint); border-radius: 2px; }
|
||||||
.swatch.energy { background: var(--energy); }
|
.swatch.energy { background: var(--energy); }
|
||||||
.swatch.carbon { background: var(--carbon); }
|
.swatch.carbon { background: var(--carbon); }
|
||||||
.swatch.nitrogen { background: var(--nitrogen); }
|
.swatch.nitrogen { background: var(--nitrogen); }
|
||||||
.swatch.phosphorus { background: var(--phosphorus); }
|
.swatch.phosphorus { background: var(--phosphorus); }
|
||||||
.swatch.other { background: var(--other); }
|
.swatch.other { background: var(--other); }
|
||||||
.toggles { display: flex; flex-direction: column; gap: 6px; }
|
|
||||||
.toggles label { display: flex; gap: 8px; align-items: center; cursor: pointer; }
|
/* Side panel with tabs. */
|
||||||
.error { color: var(--bad); }
|
.panel {
|
||||||
.center { display: grid; place-items: center; min-height: 50vh; text-align: center; }
|
position: sticky;
|
||||||
|
top: 72px;
|
||||||
|
max-height: calc(100vh - 88px);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
@media (max-width: 1150px) { .panel { position: static; max-height: none; } }
|
||||||
|
.tabs { flex: none; display: flex; gap: 2px; padding: 8px 8px 0; border-bottom: 1px solid var(--line); background: var(--panel-2); overflow-x: auto; overflow-y: hidden; }
|
||||||
|
.tabs button {
|
||||||
|
border: 0;
|
||||||
|
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--muted);
|
||||||
|
padding: 8px 12px 9px;
|
||||||
|
font-size: 13px;
|
||||||
|
border-bottom: 2px solid transparent;
|
||||||
|
margin-bottom: -1px;
|
||||||
|
}
|
||||||
|
.tabs button:hover { color: var(--text); background: transparent; }
|
||||||
|
.tabs button.on { color: var(--accent); border-bottom-color: var(--accent); background: var(--panel); }
|
||||||
|
.tabs .tab-badge { margin-left: 6px; font-size: 10.5px; padding: 0 6px; border-radius: 999px; background: var(--warn-soft); color: var(--warn); }
|
||||||
|
.panel-body { overflow-y: auto; padding: 4px 18px 18px; flex: 1; }
|
||||||
|
.block { padding: 16px 0; border-bottom: 1px solid var(--line); }
|
||||||
|
.block:last-child { border-bottom: 0; }
|
||||||
|
.block-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
|
||||||
|
.block-head .muted { font-size: 12px; }
|
||||||
|
.hint { font-size: 12.5px; color: var(--muted); margin: 0 0 10px; }
|
||||||
|
.empty { text-align: center; color: var(--muted); padding: 26px 10px; }
|
||||||
|
.empty .big { font-size: 26px; margin-bottom: 6px; opacity: 0.6; }
|
||||||
|
|
||||||
|
/* Forms. */
|
||||||
|
.field-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
|
||||||
|
.field { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||||
|
.field label { font-size: 11.5px; color: var(--muted); display: flex; align-items: center; gap: 5px; }
|
||||||
|
.field input, .field select { width: 100%; }
|
||||||
|
.form-row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; margin-top: 10px; }
|
||||||
|
.form-row .grow { flex: 1; min-width: 120px; }
|
||||||
|
.form-row input.count { width: 84px; }
|
||||||
|
input.wide, .wide { width: 100%; }
|
||||||
|
.note { font-size: 12.5px; margin-top: 8px; min-height: 0; }
|
||||||
|
.note:empty { display: none; }
|
||||||
|
.segmented { display: inline-flex; background: var(--panel-3); border-radius: var(--radius-sm); padding: 2px; gap: 2px; flex-wrap: wrap; }
|
||||||
|
.segmented button { border: 0; background: transparent; color: var(--muted); padding: 4px 10px; font-size: 12.5px; border-radius: 5px; }
|
||||||
|
.segmented button.on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
|
||||||
|
|
||||||
|
/* Resource ledger. */
|
||||||
|
table.ledger { font-size: 12.5px; background: transparent; }
|
||||||
|
table.ledger th { background: transparent; cursor: default; padding: 6px 6px; font-size: 10.5px; }
|
||||||
|
table.ledger td { padding: 6px 6px; }
|
||||||
|
table.ledger td:first-child, table.ledger th:first-child { padding-left: 0; }
|
||||||
|
table.ledger td:last-child, table.ledger th:last-child { padding-right: 0; }
|
||||||
|
table.ledger tr.total td { font-weight: 650; border-top: 1px solid var(--line-strong); }
|
||||||
|
table.ledger tr:hover { background: transparent; }
|
||||||
|
table.ledger th .swatch { margin-right: 4px; vertical-align: -1px; width: 8px; height: 8px; }
|
||||||
|
.split { display: flex; height: 8px; border-radius: 999px; overflow: hidden; background: var(--panel-3); }
|
||||||
|
.split > span { display: block; height: 100%; }
|
||||||
|
.split-legend { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: 11.5px; color: var(--muted); margin-top: 6px; }
|
||||||
|
.split-legend span { display: inline-flex; align-items: center; gap: 5px; }
|
||||||
|
.split-row { display: grid; grid-template-columns: 80px 1fr; gap: 10px; align-items: center; margin-top: 8px; font-size: 12px; }
|
||||||
|
|
||||||
|
/* Spent pool and drip. */
|
||||||
|
.drip-card { background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 12px 14px; }
|
||||||
|
.drip-top { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; }
|
||||||
|
.drip-count { font-size: 20px; font-weight: 650; font-variant-numeric: tabular-nums; }
|
||||||
|
.channels { display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); gap: 6px; margin-top: 10px; }
|
||||||
|
.channel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 6px 8px; min-width: 0; }
|
||||||
|
.channel .name { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 5px; }
|
||||||
|
.channel .amt { font-weight: 600; font-variant-numeric: tabular-nums; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.channel .sub { font-size: 11px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.channel.empty-ch { opacity: 0.55; }
|
||||||
|
.callout {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-size: 12.5px;
|
||||||
|
background: var(--warn-soft);
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--warn) 35%, transparent);
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.callout::before { content: "!"; flex: none; width: 18px; height: 18px; border-radius: 50%; background: var(--warn); color: var(--panel); font-weight: 700; display: grid; place-items: center; font-size: 12px; }
|
||||||
|
.callout.info { background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 30%, transparent); }
|
||||||
|
.callout.info::before { content: "i"; background: var(--accent); }
|
||||||
|
|
||||||
|
/* Lists in the panel. */
|
||||||
|
.list { display: flex; flex-direction: column; }
|
||||||
|
.list-item { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--line); font-size: 12.5px; }
|
||||||
|
.list-item:last-child { border-bottom: 0; }
|
||||||
|
.list-item .grow { flex: 1; min-width: 0; }
|
||||||
|
.list-item.clickable { cursor: pointer; }
|
||||||
|
.list-item.clickable:hover .grow { color: var(--accent); }
|
||||||
|
.list-item .sub { color: var(--muted); font-size: 11.5px; }
|
||||||
|
|
||||||
|
/* Inspector. */
|
||||||
|
.inspect-head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
|
||||||
|
.inspect-head .swatch { width: 14px; height: 14px; }
|
||||||
|
.inspect-head h2 { margin: 0; }
|
||||||
|
.inspect-head .grow { flex: 1; }
|
||||||
|
|
||||||
|
/* Tuning settings. */
|
||||||
|
.settings-group { margin-top: 6px; }
|
||||||
|
.settings-group summary {
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 8px 0;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 12.5px;
|
||||||
|
text-transform: capitalize;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.settings-group summary::-webkit-details-marker { display: none; }
|
||||||
|
.settings-group summary::before { content: "▸"; color: var(--faint); margin-right: 8px; transition: transform 0.15s; display: inline-block; }
|
||||||
|
.settings-group[open] summary::before { transform: rotate(90deg); }
|
||||||
|
.settings-group summary .label { flex: 1; }
|
||||||
|
.setting { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; padding: 6px 0 6px 16px; border-bottom: 1px dashed var(--line); font-size: 12.5px; }
|
||||||
|
.setting:last-child { border-bottom: 0; }
|
||||||
|
.setting .key { font-family: var(--mono); font-size: 12px; overflow-wrap: anywhere; }
|
||||||
|
.setting .val { font-family: var(--mono); font-size: 12px; font-weight: 600; text-align: right; }
|
||||||
|
.setting .why { grid-column: 1 / -1; color: var(--muted); font-size: 11.5px; }
|
||||||
|
.setting.changed .val { color: var(--accent); }
|
||||||
|
mark { background: var(--warn-soft); color: inherit; border-radius: 2px; }
|
||||||
|
|
||||||
|
/* ---------- Tuning editor ---------- */
|
||||||
|
.tuning-layout { display: grid; grid-template-columns: minmax(0, 1fr) 400px; gap: 16px; align-items: start; }
|
||||||
|
@media (max-width: 1100px) { .tuning-layout { grid-template-columns: 1fr; } }
|
||||||
|
.tuning-layout .side { display: flex; flex-direction: column; gap: 14px; }
|
||||||
|
.tuning-layout .side .card + .card { margin-top: 0; }
|
||||||
|
textarea.tuning {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 62vh;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.55;
|
||||||
|
color: var(--text);
|
||||||
|
background: var(--panel-2);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 12px 14px;
|
||||||
|
resize: vertical;
|
||||||
|
tab-size: 4;
|
||||||
|
}
|
||||||
|
textarea.tuning:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
|
||||||
|
.action { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 12px; }
|
||||||
|
.action .row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
|
||||||
|
|
||||||
|
/* Guided tuning editor: sections, fields, changes. */
|
||||||
|
.tuning-guided { display: grid; grid-template-columns: 230px minmax(0, 1fr) 380px; gap: 16px; align-items: start; }
|
||||||
|
@media (max-width: 1250px) { .tuning-guided { grid-template-columns: 210px minmax(0, 1fr); } .tuning-guided > .side { grid-column: 1 / -1; } }
|
||||||
|
@media (max-width: 800px) { .tuning-guided { grid-template-columns: minmax(0, 1fr); } }
|
||||||
|
.tuning-guided .side { display: flex; flex-direction: column; gap: 14px; }
|
||||||
|
.tuning-guided .side .card + .card { margin-top: 0; }
|
||||||
|
.nav-card { position: sticky; top: 72px; padding: 12px; }
|
||||||
|
.section-nav { display: flex; flex-direction: column; gap: 2px; margin-top: 10px; }
|
||||||
|
.section-link { display: flex; align-items: center; gap: 8px; text-align: left; border: 0; background: transparent; color: var(--text); padding: 7px 10px; border-radius: var(--radius-sm); font-weight: 500; }
|
||||||
|
.section-link .grow { flex: 1; }
|
||||||
|
.section-link:hover { background: var(--panel-3); color: var(--text); }
|
||||||
|
.section-link.on { background: var(--accent-soft); color: var(--accent); }
|
||||||
|
.tuning-section + .tuning-section { margin-top: 14px; }
|
||||||
|
.field-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(220px, 300px); gap: 8px 20px; padding: 12px 0; border-top: 1px solid var(--line); align-items: start; }
|
||||||
|
.field-row.changed .field-label { color: var(--accent); }
|
||||||
|
.field-row.changed .input-unit input, .field-row.changed .input-unit select { border-color: var(--accent); }
|
||||||
|
.field-row.bad .input-unit input { border-color: var(--bad); }
|
||||||
|
.field-label { font-weight: 600; }
|
||||||
|
.field-key { color: var(--faint); font-size: 11.5px; margin-top: 1px; overflow-wrap: anywhere; }
|
||||||
|
.field-note { color: var(--muted); font-size: 12.5px; margin-top: 4px; }
|
||||||
|
.field-input { display: flex; flex-direction: column; gap: 3px; }
|
||||||
|
.input-unit { display: flex; align-items: center; gap: 6px; }
|
||||||
|
.input-unit input, .input-unit select { flex: 1; min-width: 0; font-family: var(--mono); font-size: 13px; text-align: right; }
|
||||||
|
.input-unit select { text-align: left; font-family: inherit; }
|
||||||
|
.input-unit .unit { color: var(--muted); font-size: 12px; white-space: nowrap; min-width: 48px; }
|
||||||
|
.gloss { color: var(--muted); font-size: 12px; text-align: right; padding-right: 86px; min-height: 0; }
|
||||||
|
.gloss:empty, .field-problem:empty { display: none; }
|
||||||
|
.field-problem { font-size: 12px; text-align: right; padding-right: 86px; color: var(--accent); }
|
||||||
|
.field-row.bad .field-problem { color: var(--bad); }
|
||||||
|
.changes-card { position: sticky; top: 72px; }
|
||||||
|
.changes-card .wide { margin-top: 10px; }
|
||||||
|
@media (max-width: 1250px) { .changes-card, .nav-card { position: static; } }
|
||||||
|
|||||||
@@ -610,7 +610,7 @@ const char* bud_text(network::CellularBudOutcome outcome) {
|
|||||||
"Bud created: a descendant split off",
|
"Bud created: a descendant split off",
|
||||||
"Bud failed: not fully grown",
|
"Bud failed: not fully grown",
|
||||||
"Bud failed: not enough resources",
|
"Bud failed: not enough resources",
|
||||||
"Bud failed: no space beside you"};
|
"Bud failed: no space beside you, or the region is full"};
|
||||||
const auto index = static_cast<std::size_t>(outcome);
|
const auto index = static_cast<std::size_t>(outcome);
|
||||||
return index < text.size() ? text.at(index) : "";
|
return index < text.size() ? text.at(index) : "";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -265,10 +265,13 @@ class RemoteSession {
|
|||||||
[[nodiscard]] bool request_cellular(CellAction kind, MutationChoice choice = {},
|
[[nodiscard]] bool request_cellular(CellAction kind, MutationChoice choice = {},
|
||||||
bool become = false) {
|
bool become = false) {
|
||||||
const auto lead = cellular_lead_.lead();
|
const auto lead = cellular_lead_.lead();
|
||||||
const auto tick =
|
// A tick takes one action per account: never one a movement already named (movement
|
||||||
kind == CellAction::mutation
|
// runs ahead of the lead after the lead shrinks).
|
||||||
|
const auto tick = kind == CellAction::mutation
|
||||||
? server_tick_
|
? server_tick_
|
||||||
: server_tick_ + lead + (sent_tick_ && *sent_tick_ == server_tick_ ? 1 : 0);
|
: std::max(server_tick_ + lead +
|
||||||
|
(sent_tick_ && *sent_tick_ == server_tick_ ? 1 : 0),
|
||||||
|
cellular_sent_tick_ + 1);
|
||||||
if (!cellular_trial_ || !cellular_play_.queue(kind, tick, choice, become))
|
if (!cellular_trial_ || !cellular_play_.queue(kind, tick, choice, become))
|
||||||
return false;
|
return false;
|
||||||
action_check_at_ = {};
|
action_check_at_ = {};
|
||||||
@@ -630,6 +633,11 @@ class RemoteSession {
|
|||||||
// trails it by the replication delay, so schedule by the adaptive lead.
|
// trails it by the replication delay, so schedule by the adaptive lead.
|
||||||
// Strictly increasing even when the lead shrinks: one movement per tick.
|
// Strictly increasing even when the lead shrinks: one movement per tick.
|
||||||
const auto tick = std::max(server_tick_ + cellular_lead_.lead(), cellular_sent_tick_ + 1);
|
const auto tick = std::max(server_tick_ + cellular_lead_.lead(), cellular_sent_tick_ + 1);
|
||||||
|
// A queued discrete action owns its tick; movement resumes after it is sent.
|
||||||
|
if (const auto& p = cellular_play_.pending(); p && p->state == CellActionState::queued &&
|
||||||
|
p->kind != CellAction::mutation &&
|
||||||
|
p->tick <= tick)
|
||||||
|
return;
|
||||||
const auto steering = steer_cellular(cellular_controls_, intention, cellular_perception(),
|
const auto steering = steer_cellular(cellular_controls_, intention, cellular_perception(),
|
||||||
organisms_.current(), cellular_feed_target_);
|
organisms_.current(), cellular_feed_target_);
|
||||||
cellular_feed_target_ = steering.patch;
|
cellular_feed_target_ = steering.patch;
|
||||||
|
|||||||
@@ -42,9 +42,16 @@ class CellularBridge {
|
|||||||
if (!options.complete())
|
if (!options.complete())
|
||||||
return fail("error cellular-session-config");
|
return fail("error cellular-session-config");
|
||||||
CellularBridge bridge;
|
CellularBridge bridge;
|
||||||
|
// A fixed --session-window must be open now; a database window (ADR-0087 amendment)
|
||||||
|
// may open, close and reopen while the region runs.
|
||||||
|
if (!options.window_from_database) {
|
||||||
const auto window = server::SessionWindow::open(options.session_window, wall_seconds());
|
const auto window = server::SessionWindow::open(options.session_window, wall_seconds());
|
||||||
if (!window)
|
if (!window)
|
||||||
return fail("error cellular-session-window");
|
return fail("error cellular-session-window");
|
||||||
|
bridge.window_ = *window;
|
||||||
|
}
|
||||||
|
bridge.window_from_database_ = options.window_from_database;
|
||||||
|
bridge.key_ = key;
|
||||||
const auto colon = options.listen.rfind(':');
|
const auto colon = options.listen.rfind(':');
|
||||||
std::uint16_t port{};
|
std::uint16_t port{};
|
||||||
if (colon == std::string::npos ||
|
if (colon == std::string::npos ||
|
||||||
@@ -85,7 +92,6 @@ class CellularBridge {
|
|||||||
std::copy(issuer.begin(), issuer.end(), public_key.begin());
|
std::copy(issuer.begin(), issuer.end(), public_key.begin());
|
||||||
config.issuer_keys.push_back({1, public_key});
|
config.issuer_keys.push_back({1, public_key});
|
||||||
|
|
||||||
bridge.window_ = *window;
|
|
||||||
bridge.slot_ = std::make_unique<server::PgSlot>(pg, std::chrono::seconds{2});
|
bridge.slot_ = std::make_unique<server::PgSlot>(pg, std::chrono::seconds{2});
|
||||||
const auto lease = [&host] { return host.authority(); };
|
const auto lease = [&host] { return host.authority(); };
|
||||||
bridge.control_ =
|
bridge.control_ =
|
||||||
@@ -126,15 +132,25 @@ class CellularBridge {
|
|||||||
: "error cellular-session-config");
|
: "error cellular-session-config");
|
||||||
bridge.sessions_ = std::move(*sessions);
|
bridge.sessions_ = std::move(*sessions);
|
||||||
bridge.sessions_->set_default_interest({0, 0, 0, 7});
|
bridge.sessions_->set_default_interest({0, 0, 0, 7});
|
||||||
|
// A database window admits nobody until it has been read.
|
||||||
|
if (bridge.window_from_database_)
|
||||||
|
bridge.sessions_->set_admission(false);
|
||||||
std::printf("cellular listening %u\n", static_cast<unsigned>(bridge.sessions_->port()));
|
std::printf("cellular listening %u\n", static_cast<unsigned>(bridge.sessions_->port()));
|
||||||
return std::optional<CellularBridge>{std::move(bridge)};
|
return std::optional<CellularBridge>{std::move(bridge)};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Applies the session window: while it is closed every Hello is refused, and closing
|
||||||
|
// closes the open sessions.
|
||||||
[[nodiscard]] bool accepting(std::uint64_t now_seconds) {
|
[[nodiscard]] bool accepting(std::uint64_t now_seconds) {
|
||||||
const bool open = window_ && window_->accepting(now_seconds);
|
if (window_from_database_)
|
||||||
if (!open && !shutdown_) {
|
read_window(now_seconds);
|
||||||
|
const bool open = window_from_database_ ? feed_.accepting(now_seconds)
|
||||||
|
: window_ && window_->accepting(now_seconds);
|
||||||
|
if (open != sessions_->admitting()) {
|
||||||
|
sessions_->set_admission(open);
|
||||||
|
if (!open)
|
||||||
sessions_->shutdown(std::chrono::steady_clock::now());
|
sessions_->shutdown(std::chrono::steady_clock::now());
|
||||||
shutdown_ = true;
|
std::printf("cellular sessions %s\n", open ? "admitted" : "closed");
|
||||||
}
|
}
|
||||||
return open;
|
return open;
|
||||||
}
|
}
|
||||||
@@ -206,6 +222,12 @@ class CellularBridge {
|
|||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
sessions_->replicate(tick, source);
|
sessions_->replicate(tick, source);
|
||||||
|
// A tuning adoption changes what a bud costs, so cached costs hold for one rules set.
|
||||||
|
if (auto rules = server::encode_cellular_revamp_rules(state.revamp_rules());
|
||||||
|
rules != bud_rules_) {
|
||||||
|
bud_rules_ = std::move(rules);
|
||||||
|
bud_costs_.clear();
|
||||||
|
}
|
||||||
for (const auto& life : state.lives()) {
|
for (const auto& life : state.lives()) {
|
||||||
if (life.presence == server::CellularPresence::suspended)
|
if (life.presence == server::CellularPresence::suspended)
|
||||||
continue;
|
continue;
|
||||||
@@ -614,12 +636,65 @@ class CellularBridge {
|
|||||||
std::puts(message);
|
std::puts(message);
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
}
|
}
|
||||||
|
// The region's newest window record, every 5 s. A failed read keeps the current window,
|
||||||
|
// which still closes at its own deadline.
|
||||||
|
void read_window(std::uint64_t now_seconds) {
|
||||||
|
constexpr std::chrono::seconds interval{5};
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
if (now < next_window_read_)
|
||||||
|
return;
|
||||||
|
next_window_read_ = now + interval;
|
||||||
|
auto* db = slot_->get();
|
||||||
|
if (db == nullptr)
|
||||||
|
return;
|
||||||
|
const std::array<std::string, 2> parameters{std::to_string(key_.world),
|
||||||
|
std::to_string(key_.region)};
|
||||||
|
const auto rows =
|
||||||
|
db->query("SELECT activation_id, floor(extract(epoch FROM expires_at))::bigint FROM "
|
||||||
|
"evolution.load_session_window_v1($1::evolution.u64, $2::evolution.u64)",
|
||||||
|
parameters, std::chrono::milliseconds{1000});
|
||||||
|
if (!rows) {
|
||||||
|
slot_->broken();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::optional<server::SessionWindowFeed::Record> record;
|
||||||
|
if (!rows->empty() && rows->front().size() == 2 && rows->front()[0]) {
|
||||||
|
record = server::SessionWindowFeed::Record{*rows->front()[0], std::nullopt};
|
||||||
|
if (const auto& expiry = rows->front()[1]) {
|
||||||
|
std::uint64_t value{};
|
||||||
|
const auto [end, ec] =
|
||||||
|
std::from_chars(expiry->data(), expiry->data() + expiry->size(), value);
|
||||||
|
if (ec == std::errc{} && end == expiry->data() + expiry->size())
|
||||||
|
record->expires_at = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch (feed_.observe(record, now_seconds)) {
|
||||||
|
case server::SessionWindowFeed::Change::opened:
|
||||||
|
std::printf("cellular window opened activation=%s expires=%llu\n",
|
||||||
|
feed_.window()->activation_id().c_str(),
|
||||||
|
static_cast<unsigned long long>(feed_.window()->deadline_seconds()));
|
||||||
|
break;
|
||||||
|
case server::SessionWindowFeed::Change::closed:
|
||||||
|
std::puts("cellular window closed");
|
||||||
|
break;
|
||||||
|
case server::SessionWindowFeed::Change::refused:
|
||||||
|
std::printf("cellular window refused activation=%s\n",
|
||||||
|
record ? record->activation_id.c_str() : "");
|
||||||
|
break;
|
||||||
|
case server::SessionWindowFeed::Change::none:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::unique_ptr<server::PgSlot> slot_;
|
std::unique_ptr<server::PgSlot> slot_;
|
||||||
std::unique_ptr<server::PostgresControlLedger> control_;
|
std::unique_ptr<server::PostgresControlLedger> control_;
|
||||||
std::unique_ptr<server::PostgresActionLedger> actions_;
|
std::unique_ptr<server::PostgresActionLedger> actions_;
|
||||||
std::unique_ptr<server::RegionSessions> sessions_;
|
std::unique_ptr<server::RegionSessions> sessions_;
|
||||||
std::optional<server::SessionWindow> window_;
|
std::optional<server::SessionWindow> window_; // A fixed --session-window.
|
||||||
|
bool window_from_database_{};
|
||||||
|
persistence::RegionKey key_{};
|
||||||
|
server::SessionWindowFeed feed_;
|
||||||
|
std::chrono::steady_clock::time_point next_window_read_{};
|
||||||
std::optional<std::uint64_t> replicated_tick_;
|
std::optional<std::uint64_t> replicated_tick_;
|
||||||
struct SentOffer {
|
struct SentOffer {
|
||||||
server::LifeAccount account{};
|
server::LifeAccount account{};
|
||||||
@@ -629,9 +704,9 @@ class CellularBridge {
|
|||||||
std::vector<SentOffer> offers_; // Last offer view sent to each owner.
|
std::vector<SentOffer> offers_; // Last offer view sent to each owner.
|
||||||
std::map<std::pair<std::uint64_t, std::uint64_t>, std::optional<accounting::Inventory>>
|
std::map<std::pair<std::uint64_t, std::uint64_t>, std::optional<accounting::Inventory>>
|
||||||
bud_costs_;
|
bud_costs_;
|
||||||
|
std::vector<std::uint8_t> bud_rules_; // The rules bud_costs_ were computed under.
|
||||||
// ADR-0136: deposit stocks seen at the last replicated tick, and this tick's.
|
// ADR-0136: deposit stocks seen at the last replicated tick, and this tick's.
|
||||||
std::map<std::uint32_t, accounting::Inventory> deposit_stock_, seen_stock_;
|
std::map<std::uint32_t, accounting::Inventory> deposit_stock_, seen_stock_;
|
||||||
std::vector<std::pair<server::LifeAccount, std::uint64_t>> owned_; // At last replication.
|
std::vector<std::pair<server::LifeAccount, std::uint64_t>> owned_; // At last replication.
|
||||||
bool shutdown_{};
|
|
||||||
};
|
};
|
||||||
} // namespace evo::server_app
|
} // namespace evo::server_app
|
||||||
|
|||||||
@@ -53,6 +53,10 @@
|
|||||||
namespace evo::server_app {
|
namespace evo::server_app {
|
||||||
struct M10Options {
|
struct M10Options {
|
||||||
std::string listen, certificate, key, issuer, environment, session_window;
|
std::string listen, certificate, key, issuer, environment, session_window;
|
||||||
|
// ADR-0087 amendment: `--session-window-source db` reads the window from
|
||||||
|
// evolution.load_session_window_v1 every few seconds instead of --session-window
|
||||||
|
// (cellular profile only). Exactly one of the two is given.
|
||||||
|
bool window_from_database{};
|
||||||
// M10.5c: dev only, 60..14400 s; 0 keeps the default (300 s, ADR-0091).
|
// M10.5c: dev only, 60..14400 s; 0 keeps the default (300 s, ADR-0091).
|
||||||
std::uint64_t max_grant_lifetime{};
|
std::uint64_t max_grant_lifetime{};
|
||||||
// M10.9 (ADR-0097, dev only): `--m10-load-governor off` keeps measuring and exposing the
|
// M10.9 (ADR-0097, dev only): `--m10-load-governor off` keeps measuring and exposing the
|
||||||
@@ -68,15 +72,16 @@ struct M10Options {
|
|||||||
std::vector<std::string> life_routes;
|
std::vector<std::string> life_routes;
|
||||||
[[nodiscard]] bool session_any() const noexcept {
|
[[nodiscard]] bool session_any() const noexcept {
|
||||||
return !listen.empty() || !certificate.empty() || !key.empty() || !issuer.empty() ||
|
return !listen.empty() || !certificate.empty() || !key.empty() || !issuer.empty() ||
|
||||||
!environment.empty() || !session_window.empty() || max_grant_lifetime != 0 ||
|
!environment.empty() || !session_window.empty() || window_from_database ||
|
||||||
!area.empty() || !handoff_key.empty() || !neighbours.empty() || !load_governor;
|
max_grant_lifetime != 0 || !area.empty() || !handoff_key.empty() ||
|
||||||
|
!neighbours.empty() || !load_governor;
|
||||||
}
|
}
|
||||||
[[nodiscard]] bool any() const noexcept {
|
[[nodiscard]] bool any() const noexcept {
|
||||||
return session_any() || !life_routes.empty();
|
return session_any() || !life_routes.empty();
|
||||||
}
|
}
|
||||||
[[nodiscard]] bool complete() const noexcept {
|
[[nodiscard]] bool complete() const noexcept {
|
||||||
return !listen.empty() && !certificate.empty() && !key.empty() && !issuer.empty() &&
|
return !listen.empty() && !certificate.empty() && !key.empty() && !issuer.empty() &&
|
||||||
!environment.empty() && !session_window.empty();
|
!environment.empty() && (session_window.empty() == window_from_database);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Actions are handed to the host as soon as they are scheduled (at most 8 ticks ahead).
|
// Actions are handed to the host as soon as they are scheduled (at most 8 ticks ahead).
|
||||||
@@ -117,6 +122,8 @@ template <typename Host> class M10Bridge {
|
|||||||
M10Bridge bridge;
|
M10Bridge bridge;
|
||||||
if (!o.any())
|
if (!o.any())
|
||||||
return bridge;
|
return bridge;
|
||||||
|
if (o.window_from_database)
|
||||||
|
return fail("error m10-window-source"); // The cellular profile only.
|
||||||
const auto window = server::SessionWindow::open(o.session_window, wall_seconds());
|
const auto window = server::SessionWindow::open(o.session_window, wall_seconds());
|
||||||
if (!window)
|
if (!window)
|
||||||
return fail(window.error() == server::SessionWindow::Error::expired
|
return fail(window.error() == server::SessionWindow::Error::expired
|
||||||
|
|||||||
+80
-11
@@ -53,6 +53,7 @@
|
|||||||
// --primitive-* flags enable the v5 new-life listener; biology ticks and genesis
|
// --primitive-* flags enable the v5 new-life listener; biology ticks and genesis
|
||||||
// provisioning remain disabled.
|
// provisioning remain disabled.
|
||||||
#include "evo/biology/founder.hpp"
|
#include "evo/biology/founder.hpp"
|
||||||
|
#include "evo/persistence/sha256.hpp"
|
||||||
#include "evo/processes/development_opening.hpp"
|
#include "evo/processes/development_opening.hpp"
|
||||||
#include "evo/server/cellular_session_batch.hpp"
|
#include "evo/server/cellular_session_batch.hpp"
|
||||||
#include "evo/server/lifecycle/cellular_admin_view.hpp"
|
#include "evo/server/lifecycle/cellular_admin_view.hpp"
|
||||||
@@ -263,6 +264,8 @@ std::optional<Options> parse(int argc, char** argv) {
|
|||||||
o.m10.environment = value;
|
o.m10.environment = value;
|
||||||
else if (flag == "--session-window")
|
else if (flag == "--session-window")
|
||||||
o.m10.session_window = value;
|
o.m10.session_window = value;
|
||||||
|
else if (flag == "--session-window-source" && value == "db")
|
||||||
|
o.m10.window_from_database = true;
|
||||||
else if (flag == "--m10-max-grant-lifetime" && n && *n >= 60 && *n <= 14400)
|
else if (flag == "--m10-max-grant-lifetime" && n && *n >= 60 && *n <= 14400)
|
||||||
o.m10.max_grant_lifetime = *n;
|
o.m10.max_grant_lifetime = *n;
|
||||||
else if (flag == "--m10-area")
|
else if (flag == "--m10-area")
|
||||||
@@ -1035,6 +1038,18 @@ int serve_cellular(Options& o) {
|
|||||||
std::printf("cellular commit ticks=%zu ms=%lld handoff_ms=%lld ok=%d\n",
|
std::printf("cellular commit ticks=%zu ms=%lld handoff_ms=%lld ok=%d\n",
|
||||||
flight_ticks, static_cast<long long>(commit_ms), flight_handoff_ms,
|
flight_ticks, static_cast<long long>(commit_ms), flight_handoff_ms,
|
||||||
*landed ? 1 : 0);
|
*landed ? 1 : 0);
|
||||||
|
if (!*landed) {
|
||||||
|
// Categories and SQLSTATE only (never server text); -1 when not reported.
|
||||||
|
const auto& failure = landed->error();
|
||||||
|
const auto store = failure.store.value_or(persistence::LeaseStoreFailure{});
|
||||||
|
std::printf("cellular commit failed host=%u publication=%d store=%d "
|
||||||
|
"sqlstate=%.5s object=%d\n",
|
||||||
|
static_cast<unsigned>(failure.kind),
|
||||||
|
failure.publication ? static_cast<int>(*failure.publication) : -1,
|
||||||
|
failure.store ? static_cast<int>(store.kind) : -1,
|
||||||
|
failure.store ? store.cause.sqlstate.data() : "-",
|
||||||
|
failure.object ? static_cast<int>(*failure.object) : -1);
|
||||||
|
}
|
||||||
if (*landed) {
|
if (*landed) {
|
||||||
host.refuse_births(flight_refusals);
|
host.refuse_births(flight_refusals);
|
||||||
flight_actions.clear();
|
flight_actions.clear();
|
||||||
@@ -1106,7 +1121,18 @@ int serve_cellular(Options& o) {
|
|||||||
id.bytes = account;
|
id.bytes = account;
|
||||||
return bridge->sessions().holder(id).has_value();
|
return bridge->sessions().holder(id).has_value();
|
||||||
};
|
};
|
||||||
return {200, server::render_cellular_admin_view(*state, online),
|
// The digest tuning revisions are adopted by (ADR-0182 section 13).
|
||||||
|
std::string rules_sha256;
|
||||||
|
if (state->rules_version() >= server::cellular_lives_revamp_rules)
|
||||||
|
if (const auto digest = persistence::sha256(
|
||||||
|
server::encode_cellular_revamp_rules(state->revamp_rules())))
|
||||||
|
for (const auto byte : *digest) {
|
||||||
|
constexpr std::string_view digits = "0123456789abcdef";
|
||||||
|
rules_sha256.push_back(digits[byte >> 4U]);
|
||||||
|
rules_sha256.push_back(digits[byte & 0x0FU]);
|
||||||
|
}
|
||||||
|
return {200,
|
||||||
|
server::render_cellular_admin_view(*state, online, {}, rules_sha256),
|
||||||
"application/json"};
|
"application/json"};
|
||||||
}
|
}
|
||||||
return {404, "not found\n"};
|
return {404, "not found\n"};
|
||||||
@@ -1148,9 +1174,11 @@ int serve_cellular(Options& o) {
|
|||||||
[[maybe_unused]] const auto changed = host.set_population_mode(want_population);
|
[[maybe_unused]] const auto changed = host.set_population_mode(want_population);
|
||||||
state = host.state();
|
state = host.state();
|
||||||
}
|
}
|
||||||
const bool needed = state && (player_present || birth_waiting ||
|
// A queued admin command needs a tick too: an empty region must still take a spawn.
|
||||||
server::cellular_unattended_tick_needed(*state) ||
|
const bool needed =
|
||||||
status.ecological_pending_ticks != 0);
|
state &&
|
||||||
|
(player_present || birth_waiting || server::cellular_unattended_tick_needed(*state) ||
|
||||||
|
status.ecological_pending_ticks != 0 || !host.unbound_admin_commands().empty());
|
||||||
const auto monotonic_us = [] {
|
const auto monotonic_us = [] {
|
||||||
return static_cast<std::uint64_t>(
|
return static_cast<std::uint64_t>(
|
||||||
std::chrono::duration_cast<std::chrono::microseconds>(
|
std::chrono::duration_cast<std::chrono::microseconds>(
|
||||||
@@ -1201,8 +1229,10 @@ int serve_cellular(Options& o) {
|
|||||||
provisional.digest.fill(0xFF);
|
provisional.digest.fill(0xFF);
|
||||||
if (auto created =
|
if (auto created =
|
||||||
server::CellularSessionBatchBuilder::create(candidate, provisional);
|
server::CellularSessionBatchBuilder::create(candidate, provisional);
|
||||||
created)
|
created) {
|
||||||
next.emplace(std::move(*created));
|
next.emplace(std::move(*created));
|
||||||
|
next->set_tuning_resolver(host.tuning_resolver());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
flight_ticks = batch_builder->batch().ticks.size();
|
flight_ticks = batch_builder->batch().ticks.size();
|
||||||
const auto refusals = batch_builder->refused_births();
|
const auto refusals = batch_builder->refused_births();
|
||||||
@@ -1307,12 +1337,17 @@ int serve_cellular(Options& o) {
|
|||||||
});
|
});
|
||||||
bridge->dropped(departed, true);
|
bridge->dropped(departed, true);
|
||||||
}
|
}
|
||||||
|
// One action per account a tick; a second would refuse the whole tick.
|
||||||
|
if (const auto superseded = server::keep_one_action_per_account(actions);
|
||||||
|
!superseded.empty())
|
||||||
|
bridge->dropped(superseded, true);
|
||||||
if (!batch_builder) {
|
if (!batch_builder) {
|
||||||
auto created = server::CellularSessionBatchBuilder::create(
|
auto created = server::CellularSessionBatchBuilder::create(
|
||||||
*state, host.committed()->head);
|
*state, host.committed()->head);
|
||||||
if (created)
|
if (created) {
|
||||||
batch_builder.emplace(std::move(*created));
|
batch_builder.emplace(std::move(*created));
|
||||||
else
|
batch_builder->set_tuning_resolver(host.tuning_resolver());
|
||||||
|
} else
|
||||||
report_stall("create", created.error(), tick);
|
report_stall("create", created.error(), tick);
|
||||||
}
|
}
|
||||||
if (!batch_builder) {
|
if (!batch_builder) {
|
||||||
@@ -1336,8 +1371,34 @@ int serve_cellular(Options& o) {
|
|||||||
});
|
});
|
||||||
const std::span<const persistence::CellularMutationReservation> mutations =
|
const std::span<const persistence::CellularMutationReservation> mutations =
|
||||||
unbound;
|
unbound;
|
||||||
|
// ADR-0182: queued admin commands not already in this batch, and at
|
||||||
|
// most one tuning adoption per batch (its successor names its rules).
|
||||||
|
auto admin = host.unbound_admin_commands();
|
||||||
|
std::erase_if(admin, [&](const auto& queued) {
|
||||||
|
return std::ranges::any_of(
|
||||||
|
batch_builder->batch().ticks, [&](const auto& previous) {
|
||||||
|
return std::ranges::find(previous.admin, queued.id,
|
||||||
|
&server::CellularAdminCommand::id) !=
|
||||||
|
previous.admin.end();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
bool adopting = std::ranges::any_of(
|
||||||
|
batch_builder->batch().ticks, [](const auto& previous) {
|
||||||
|
return std::ranges::any_of(previous.admin, [](const auto& c) {
|
||||||
|
return c.kind == server::CellularAdminKind::adopt_tuning;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
std::erase_if(admin, [&](const auto& queued) {
|
||||||
|
if (queued.kind != server::CellularAdminKind::adopt_tuning)
|
||||||
|
return false;
|
||||||
|
if (adopting)
|
||||||
|
return true;
|
||||||
|
adopting = true;
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
const auto admin_before = batch_builder->admin_results().size();
|
||||||
auto appended = batch_builder->append_with_birth_refusals(
|
auto appended = batch_builder->append_with_birth_refusals(
|
||||||
tick, baseline, actions, births, mutations);
|
tick, baseline, actions, births, mutations, admin);
|
||||||
if (!appended && !actions.empty()) {
|
if (!appended && !actions.empty()) {
|
||||||
// ADR-0127: one account's unusable action (its life died, or it
|
// ADR-0127: one account's unusable action (its life died, or it
|
||||||
// names an unperceived patch) refuses only that action, never the
|
// names an unperceived patch) refuses only that action, never the
|
||||||
@@ -1352,7 +1413,7 @@ int serve_cellular(Options& o) {
|
|||||||
bridge->dropped(refused, true);
|
bridge->dropped(refused, true);
|
||||||
actions = std::move(usable);
|
actions = std::move(usable);
|
||||||
appended = batch_builder->append_with_birth_refusals(
|
appended = batch_builder->append_with_birth_refusals(
|
||||||
tick, baseline, actions, births, mutations);
|
tick, baseline, actions, births, mutations, admin);
|
||||||
}
|
}
|
||||||
if (!appended) {
|
if (!appended) {
|
||||||
const auto lives = batch_builder->last_lives_error();
|
const auto lives = batch_builder->last_lives_error();
|
||||||
@@ -1368,7 +1429,14 @@ int serve_cellular(Options& o) {
|
|||||||
actions.end());
|
actions.end());
|
||||||
batch_actions.insert(batch_actions.end(), actions.begin(),
|
batch_actions.insert(batch_actions.end(), actions.begin(),
|
||||||
actions.end());
|
actions.end());
|
||||||
const bool prompt = !births.empty() || !mutations.empty();
|
const auto results = batch_builder->admin_results();
|
||||||
|
for (std::size_t i = admin_before; i < results.size(); ++i)
|
||||||
|
std::printf("cellular admin command=%llu tick=%llu %s\n",
|
||||||
|
static_cast<unsigned long long>(results[i].id),
|
||||||
|
static_cast<unsigned long long>(tick),
|
||||||
|
results[i].applied ? "applied" : "refused");
|
||||||
|
const bool prompt =
|
||||||
|
!births.empty() || !mutations.empty() || !admin.empty();
|
||||||
if (prompt || batch_builder->batch().ticks.size() >= flush_ticks)
|
if (prompt || batch_builder->batch().ticks.size() >= flush_ticks)
|
||||||
flush();
|
flush();
|
||||||
}
|
}
|
||||||
@@ -1406,7 +1474,8 @@ int main(int argc, char** argv) {
|
|||||||
"--session-cert F --session-key F --session-grant-key F "
|
"--session-cert F --session-key F --session-grant-key F "
|
||||||
"--session-grant-ledger F --session-environment dev]] [--m10-listen "
|
"--session-grant-ledger F --session-environment dev]] [--m10-listen "
|
||||||
"ADDRESS:PORT --m10-cert F --m10-key F --m10-issuer F "
|
"ADDRESS:PORT --m10-cert F --m10-key F --m10-issuer F "
|
||||||
"--m10-environment dev|stage|world0 --session-window ACTIVATION:UTC_EXPIRY "
|
"--m10-environment dev|stage|world0 (--session-window ACTIVATION:UTC_EXPIRY | "
|
||||||
|
"--session-window-source db) "
|
||||||
"[--m10-max-grant-lifetime 60..14400] [--m10-area X0,Y0,X1,Y1] "
|
"[--m10-max-grant-lifetime 60..14400] [--m10-area X0,Y0,X1,Y1] "
|
||||||
"[--m10-handoff-key F [--m10-neighbour "
|
"[--m10-handoff-key F [--m10-neighbour "
|
||||||
"REGION=X0,Y0,X1,Y1=HOST:PORT=NAME=PUBFILE]...] "
|
"REGION=X0,Y0,X1,Y1=HOST:PORT=NAME=PUBFILE]...] "
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# ADR-0182 read-only admin API and portal. One replica; it holds no state but a short view
|
# ADR-0182 admin API and portal. One replica; it holds no state but a short view
|
||||||
# cache. The realm's public signing key is pinned below (ADMIN_JWKS, the same key as the grant
|
# cache. The realm's public signing key is pinned below (ADMIN_JWKS, the same key as the grant
|
||||||
# broker's); a Keycloak key rotation needs a Git update in both.
|
# broker's); a Keycloak key rotation needs a Git update in both.
|
||||||
apiVersion: apps/v1
|
apiVersion: apps/v1
|
||||||
@@ -47,7 +47,9 @@ spec:
|
|||||||
--audience aevolution-admin --client aevolution-admin-portal \
|
--audience aevolution-admin --client aevolution-admin-portal \
|
||||||
--role aevolution-admin --assets /usr/local/share/evo-admin-portal \
|
--role aevolution-admin --assets /usr/local/share/evo-admin-portal \
|
||||||
--pg-service /run/postgres/pg_service.conf --pg-passfile /run/postgres/pgpass \
|
--pg-service /run/postgres/pg_service.conf --pg-passfile /run/postgres/pgpass \
|
||||||
"${regions[@]}"
|
--baseline-tuning /etc/evo/tuning/cellular-revamp.tuning \
|
||||||
|
--region-tuning /etc/evo/tuning/cellular.tuning \
|
||||||
|
--deploy-config /run/deploy "${regions[@]}"
|
||||||
env:
|
env:
|
||||||
- {name: ADMIN_WORLD, value: "100"}
|
- {name: ADMIN_WORLD, value: "100"}
|
||||||
# Space-separated REGION=HOST:PORT: each region's operations address for /admin/view.
|
# Space-separated REGION=HOST:PORT: each region's operations address for /admin/view.
|
||||||
@@ -77,7 +79,33 @@ spec:
|
|||||||
capabilities: {drop: [ALL]}
|
capabilities: {drop: [ALL]}
|
||||||
volumeMounts:
|
volumeMounts:
|
||||||
- {name: connection, mountPath: /run/postgres, readOnly: true}
|
- {name: connection, mountPath: /run/postgres, readOnly: true}
|
||||||
|
# The revamp tuning file the regions opened with: the portal's baseline until the
|
||||||
|
# first tuning revision (ADR-0182 section 13); the region tuning file, shown read only.
|
||||||
|
- {name: tuning, mountPath: /etc/evo/tuning, readOnly: true}
|
||||||
|
# ADR-0182 section 15: the Gitea and Argo CD settings and tokens that let the portal
|
||||||
|
# open a region, one file per key; without the Secret that feature stays off.
|
||||||
|
- {name: deploy, mountPath: /run/deploy, readOnly: true}
|
||||||
volumes:
|
volumes:
|
||||||
|
- name: deploy
|
||||||
|
secret:
|
||||||
|
secretName: aevolution-admin
|
||||||
|
optional: true
|
||||||
|
defaultMode: 0440
|
||||||
|
items:
|
||||||
|
- {key: GITEA_BASE_URL, path: GITEA_BASE_URL}
|
||||||
|
- {key: GITEA_REPOSITORY, path: GITEA_REPOSITORY}
|
||||||
|
- {key: GITEA_TOKEN, path: GITEA_TOKEN}
|
||||||
|
- {key: ARGOCD_SERVER, path: ARGOCD_SERVER}
|
||||||
|
- {key: ARGOCD_APPLICATION, path: ARGOCD_APPLICATION}
|
||||||
|
- {key: ARGOCD_TOKEN, path: ARGOCD_TOKEN}
|
||||||
|
- {key: ARGOCD_TLS_VERIFY, path: ARGOCD_TLS_VERIFY}
|
||||||
|
- name: tuning
|
||||||
|
configMap:
|
||||||
|
name: cellular-tuning
|
||||||
|
defaultMode: 0444
|
||||||
|
items:
|
||||||
|
- {key: cellular-revamp.tuning, path: cellular-revamp.tuning}
|
||||||
|
- {key: cellular.tuning, path: cellular.tuning}
|
||||||
- name: connection
|
- name: connection
|
||||||
secret:
|
secret:
|
||||||
secretName: aevolution-admin-pg
|
secretName: aevolution-admin-pg
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
# Admin portal traffic on top of the namespace default-deny. Admins reach it only at
|
# Admin portal traffic on top of the namespace default-deny. Admins reach it only at
|
||||||
# https://srs.aeternalisgames.com on 443, where ingress-nginx terminates TLS; port 8080 is
|
# https://srs.aeternalisgames.com on 443, where ingress-nginx terminates TLS; port 8080 is
|
||||||
# admitted from the ingress-nginx pods and nothing else. Egress: PostgreSQL on pg-forge-01
|
# admitted from the ingress-nginx pods and nothing else. Egress: PostgreSQL on pg-forge-01,
|
||||||
# and the region's operations port (9100) for /admin/view.
|
# the region's operations port (9100) for /admin/view, and for opening a region (ADR-0182
|
||||||
|
# section 15, approved 2026-10-28) Gitea through the node's ingress (git.aeternalisgames.com,
|
||||||
|
# 172.10.1.160:443) and the argocd-server pods (8080, behind the Service's 443).
|
||||||
apiVersion: networking.k8s.io/v1
|
apiVersion: networking.k8s.io/v1
|
||||||
kind: NetworkPolicy
|
kind: NetworkPolicy
|
||||||
metadata:
|
metadata:
|
||||||
@@ -35,6 +37,20 @@ spec:
|
|||||||
app.kubernetes.io/name: evo-region
|
app.kubernetes.io/name: evo-region
|
||||||
ports:
|
ports:
|
||||||
- {protocol: TCP, port: 9100}
|
- {protocol: TCP, port: 9100}
|
||||||
|
- to:
|
||||||
|
- ipBlock:
|
||||||
|
cidr: 172.10.1.160/32
|
||||||
|
ports:
|
||||||
|
- {protocol: TCP, port: 443}
|
||||||
|
- to:
|
||||||
|
- namespaceSelector:
|
||||||
|
matchLabels:
|
||||||
|
kubernetes.io/metadata.name: argocd
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
app.kubernetes.io/name: argocd-server
|
||||||
|
ports:
|
||||||
|
- {protocol: TCP, port: 8080}
|
||||||
---
|
---
|
||||||
# The region's operations port also admits the admin portal (alongside Prometheus,
|
# The region's operations port also admits the admin portal (alongside Prometheus,
|
||||||
# evo-region-scrape). Only 9100: never the session port.
|
# evo-region-scrape). Only 9100: never the session port.
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ spec:
|
|||||||
if [ -n "$REGION_SESSION" ]; then
|
if [ -n "$REGION_SESSION" ]; then
|
||||||
m10=(--m10-listen "$REGION_SESSION_LISTEN" --m10-cert /run/session/server.pem
|
m10=(--m10-listen "$REGION_SESSION_LISTEN" --m10-cert /run/session/server.pem
|
||||||
--m10-key /run/session/server.key --m10-issuer /run/session/issuer.pub
|
--m10-key /run/session/server.key --m10-issuer /run/session/issuer.pub
|
||||||
--m10-environment "$REGION_SESSION" --session-window "$REGION_SESSION_WINDOW")
|
--m10-environment "$REGION_SESSION" --session-window-source db)
|
||||||
grant=(--m10-max-grant-lifetime "$REGION_M10_MAX_GRANT_LIFETIME")
|
grant=(--m10-max-grant-lifetime "$REGION_M10_MAX_GRANT_LIFETIME")
|
||||||
fi
|
fi
|
||||||
# Lineage keeps its 20 s drain. Both profiles take the overlay grant ceiling;
|
# Lineage keeps its 20 s drain. Both profiles take the overlay grant ceiling;
|
||||||
@@ -100,8 +100,6 @@ spec:
|
|||||||
# Session listener address; the policy check allows only this loopback value
|
# Session listener address; the policy check allows only this loopback value
|
||||||
# outside region/dev-session-route.
|
# outside region/dev-session-route.
|
||||||
- {name: REGION_SESSION_LISTEN, value: "127.0.0.1:7400"}
|
- {name: REGION_SESSION_LISTEN, value: "127.0.0.1:7400"}
|
||||||
# Absolute UTC expiry; route overlays must provide activation-id:unix-seconds.
|
|
||||||
- {name: REGION_SESSION_WINDOW, value: ""}
|
|
||||||
# DEV-only grant ceiling; overlays must keep this within the server contract.
|
# DEV-only grant ceiling; overlays must keep this within the server contract.
|
||||||
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "300"}
|
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "300"}
|
||||||
ports:
|
ports:
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# With the route, the opt-in M10 QUIC listener binds the pod interface. The absolute
|
# With the route, the opt-in M10 QUIC listener binds the pod interface. Its session window
|
||||||
# expiry is committed so a delayed Argo sync fails closed (ADR-0087).
|
# is not in Git: the region reads it from SQL, set in the admin portal (ADR-0087 amendment).
|
||||||
apiVersion: apps/v1
|
apiVersion: apps/v1
|
||||||
kind: Deployment
|
kind: Deployment
|
||||||
metadata:
|
metadata:
|
||||||
@@ -12,7 +12,6 @@ spec:
|
|||||||
env:
|
env:
|
||||||
- {name: REGION_SESSION, value: "dev"}
|
- {name: REGION_SESSION, value: "dev"}
|
||||||
- {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"}
|
- {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"}
|
||||||
- {name: REGION_SESSION_WINDOW, value: "dev-20261027T163211-c432220c:1793133131"}
|
|
||||||
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
|
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
|
||||||
ports:
|
ports:
|
||||||
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
|
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ components:
|
|||||||
images:
|
images:
|
||||||
- name: aevolution-server
|
- name: aevolution-server
|
||||||
newName: registry.aeternalisgames.com/aeternalis/aevolution-server
|
newName: registry.aeternalisgames.com/aeternalis/aevolution-server
|
||||||
digest: sha256:f235d14aa06924010ac9e1a4cfad6148ed24447eafb33ef2df968a285f467457
|
# Gitea run 576 (9de55e3): one action per account a tick.
|
||||||
|
digest: sha256:9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5
|
||||||
patches:
|
patches:
|
||||||
- path: region-values.yaml
|
- path: region-values.yaml
|
||||||
# The Git tuning files for the provision Job's liquid (rules 12) and revamp (rules 13)
|
# The Git tuning files for the provision Job's liquid (rules 12) and revamp (rules 13)
|
||||||
|
|||||||
@@ -18,12 +18,12 @@ spec:
|
|||||||
env:
|
env:
|
||||||
- {name: REGION_WORLD, value: "100"}
|
- {name: REGION_WORLD, value: "100"}
|
||||||
- {name: REGION_ID, value: "16"}
|
- {name: REGION_ID, value: "16"}
|
||||||
- {name: REGION_BUILD, value: f235d14aa06924010ac9e1a4cfad6148ed24447eafb33ef2df968a285f467457}
|
- {name: REGION_BUILD, value: 9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5}
|
||||||
- {name: REGION_PROFILE, value: cellular}
|
- {name: REGION_PROFILE, value: cellular}
|
||||||
# The whole world's catalog: dev world 100 has only this region.
|
# The whole world's catalog: dev world 100 has only this region.
|
||||||
- {name: REGION_LIFE_ROUTES, value: "16=void.aeternalisgames.com:7400=void.aeternalisgames.com"}
|
- {name: REGION_LIFE_ROUTES, value: "16=void.aeternalisgames.com:7400=void.aeternalisgames.com"}
|
||||||
# Keep the currently promoted build plus prior committed builds recoverable.
|
# Keep the currently promoted build plus prior committed builds recoverable.
|
||||||
- {name: REGION_RETAINED, value: "f1183f4476bac87c09504a574112df4663931f67e88cc38dc08f867ce98ff726 815153514ca4a53967932bb46456ff4cb4e1784f9db247bc3b613b7e8365c59f 21507d4369cebef83ee05152daea5ac2f581ea86a9dc85276ef54e3f9f6388c5 5a77cf9e96e7a0e40ea07e9394a3fa458184ce54f8f774a8fb59cbec1db75c54 e17c62bc8dbad089da57e8b30adc391ff8b947cc7182b3160f5e2709103ded78 6c96629eb3c26513d55207b109fe2a9873a58f43510bd067b7d5422572e3fb42 7952185d5ef96504b5793b76fe72e42cbe9c9ac19149bf912adb2c3a735f8dbf f378a43d6146eeed864110b90848df0bec9672fa4c9941a2d04de249068a4a09 ecac8f9f2489c547ce58f12ed01baaa3939c8adbf8aed05c313abbf422cdc855 4af7209941643e0c6a100e2b4e2fef8a959b87fdbfac2173b7867cfc1808bd66 edb39f956df1f481d7ba724cac4ceb3a4fe494efc02f994d31d6c96dfae04a78 0ded41070dd3e0c0daa43e13dadc58c449865eec00530cfceff3c1579c66e916 754446fe4e5f33e9c0d5a1a74a02444a01de1700673442c90827c708aba62cee c597c0bac8b4a796e1e8b70344f9866cb047cc90cfb15af774d38860594ea27a e83c333a87056c678b5e835947647ef42370b43dbfc31997744f28d993f9c4aa db2b0e6a6071502381a768d70fd9bab8c08c64e4717fc23da45dbe8adc5fa3d6 cdc10712ff8bf956f8f5900709500046493523b51dc670d5b2d01eaf604bcd38 028571f257b485acafbe79b704a80f273d899485c4bb264d9c8137bf51e33217 566c29329433934f1436faf94652a7b925df8b4587ab04470322172f47c31c02 1dd640eba3e9dbdd10106698215a0a06df89c5cdf801c53c4c26fb923116552a faeb26fc5db5c4aae9ae9eb4388e807ab4d59499d7639fcab3d878843a740037 5e13e0096eb4010253c270ab98f0e9bbc11571c221eb779d428333e8cd63c955 e891f9427d5ec81b32595d70be9d00bb66c6d8223b4747d12be8c388c2fc0c8e 58aab8aaa538c0c6e5ad7281fd27e50374b489942aa317296dbf9c2ec5ca3434 4a8b0a9dc9f6be491e9eacb464aa7ef7c0d449de3018c4172c01448ce39a5108 3e5b8cef06838821113c8bba064e9415e8c627bca552fb978f830d40027b80f2 67e6bb3d138e7d489850ac99b5915ef8659178a68140b963e282b24020a288e2 f178f7f44251fdc9ae9ccaaecc5ea6f10aa534caa25d506abc3fbde21c69db17 6532f97e9b7d1492f1a17d1228ce7e563016c2187735f44e58ff1e9f786019aa 7c5462391a9bff4f7c25f2761098e7189b7ae204af0a7be61a652e4482f63e6a 9ba005f9216a2211491afd0e335ac5c6f20af1166fbb7518bcc8cec2e536f5ce 7eb84318234e23c223d4279ac01e925ba0b08d6d6950f7ba328f0ce909af8307 0fcdbf1518b677829322dc18e1feebd354a6e39700bd9cdb60ab47dc0465c3a6 801a9ae4fe1049dd27cfd9c356f21f29c6e07238448c201c08d288b5cc8e7e9a f0869be511179866f9a71a63a6a5f65e577e851fd7851184734bb5c56940b1a6 178cd8ffcdfe9fe14f39084d78341a8705ca72e78947bada31ab0356508fc232 0fd4807f67ab317561f115f12c0d8540e04596fdea389d7c2104e97dda5a0351 effea9180d802e50abed76a5da665374f3591eda8aeb99c0fff085ed6df618ae 7a35cc170b935508b9b88379f4fb581acb852ebe769ac269f1596861aca2ffa7 2d1307493202464773734b0a2d33f4a737b0a897cb179de05bdf433cbdb1aec1 a5b70d945b63618a2897a848320e9af6b73a1a4f3bf8fb052d8286a93f6f8ada 222fa3dea0cb25335234678fa0d628222fc92c9ff38a1869330d973b8c4b4e53"}
|
- {name: REGION_RETAINED, value: "f1183f4476bac87c09504a574112df4663931f67e88cc38dc08f867ce98ff726 815153514ca4a53967932bb46456ff4cb4e1784f9db247bc3b613b7e8365c59f 21507d4369cebef83ee05152daea5ac2f581ea86a9dc85276ef54e3f9f6388c5 5a77cf9e96e7a0e40ea07e9394a3fa458184ce54f8f774a8fb59cbec1db75c54 e17c62bc8dbad089da57e8b30adc391ff8b947cc7182b3160f5e2709103ded78 6c96629eb3c26513d55207b109fe2a9873a58f43510bd067b7d5422572e3fb42 7952185d5ef96504b5793b76fe72e42cbe9c9ac19149bf912adb2c3a735f8dbf f378a43d6146eeed864110b90848df0bec9672fa4c9941a2d04de249068a4a09 ecac8f9f2489c547ce58f12ed01baaa3939c8adbf8aed05c313abbf422cdc855 4af7209941643e0c6a100e2b4e2fef8a959b87fdbfac2173b7867cfc1808bd66 edb39f956df1f481d7ba724cac4ceb3a4fe494efc02f994d31d6c96dfae04a78 0ded41070dd3e0c0daa43e13dadc58c449865eec00530cfceff3c1579c66e916 754446fe4e5f33e9c0d5a1a74a02444a01de1700673442c90827c708aba62cee c597c0bac8b4a796e1e8b70344f9866cb047cc90cfb15af774d38860594ea27a e83c333a87056c678b5e835947647ef42370b43dbfc31997744f28d993f9c4aa db2b0e6a6071502381a768d70fd9bab8c08c64e4717fc23da45dbe8adc5fa3d6 cdc10712ff8bf956f8f5900709500046493523b51dc670d5b2d01eaf604bcd38 028571f257b485acafbe79b704a80f273d899485c4bb264d9c8137bf51e33217 566c29329433934f1436faf94652a7b925df8b4587ab04470322172f47c31c02 1dd640eba3e9dbdd10106698215a0a06df89c5cdf801c53c4c26fb923116552a faeb26fc5db5c4aae9ae9eb4388e807ab4d59499d7639fcab3d878843a740037 5e13e0096eb4010253c270ab98f0e9bbc11571c221eb779d428333e8cd63c955 e891f9427d5ec81b32595d70be9d00bb66c6d8223b4747d12be8c388c2fc0c8e 58aab8aaa538c0c6e5ad7281fd27e50374b489942aa317296dbf9c2ec5ca3434 4a8b0a9dc9f6be491e9eacb464aa7ef7c0d449de3018c4172c01448ce39a5108 3e5b8cef06838821113c8bba064e9415e8c627bca552fb978f830d40027b80f2 67e6bb3d138e7d489850ac99b5915ef8659178a68140b963e282b24020a288e2 f178f7f44251fdc9ae9ccaaecc5ea6f10aa534caa25d506abc3fbde21c69db17 6532f97e9b7d1492f1a17d1228ce7e563016c2187735f44e58ff1e9f786019aa 7c5462391a9bff4f7c25f2761098e7189b7ae204af0a7be61a652e4482f63e6a 9ba005f9216a2211491afd0e335ac5c6f20af1166fbb7518bcc8cec2e536f5ce 7eb84318234e23c223d4279ac01e925ba0b08d6d6950f7ba328f0ce909af8307 0fcdbf1518b677829322dc18e1feebd354a6e39700bd9cdb60ab47dc0465c3a6 801a9ae4fe1049dd27cfd9c356f21f29c6e07238448c201c08d288b5cc8e7e9a f0869be511179866f9a71a63a6a5f65e577e851fd7851184734bb5c56940b1a6 178cd8ffcdfe9fe14f39084d78341a8705ca72e78947bada31ab0356508fc232 0fd4807f67ab317561f115f12c0d8540e04596fdea389d7c2104e97dda5a0351 effea9180d802e50abed76a5da665374f3591eda8aeb99c0fff085ed6df618ae 7a35cc170b935508b9b88379f4fb581acb852ebe769ac269f1596861aca2ffa7 2d1307493202464773734b0a2d33f4a737b0a897cb179de05bdf433cbdb1aec1 a5b70d945b63618a2897a848320e9af6b73a1a4f3bf8fb052d8286a93f6f8ada 222fa3dea0cb25335234678fa0d628222fc92c9ff38a1869330d973b8c4b4e53 f235d14aa06924010ac9e1a4cfad6148ed24447eafb33ef2df968a285f467457 1dd1ea052376c2c5daf2b0a910b1a5972474c836672f9cb61b32ecae58dabfd1 c7347c2d7aa2ea0e5d00665da81cd7d710b109e4e306dd7e09562463d33a5d8f d4b62521c57323025ed611b6873cffa5da49b84acda38081758e8a23b7b8d981 82e248426f5cb31cfe8ddc3aea84982d2fcfd34d12fbf78204de2ccffdbf2a2a 03ce069df16244e47d4c7b7ceac699949c099168f9c531f1ece08d2111d286e5 db67827962bd96ec8c19f4dbb039d29e897592db9d8e9da9ddf00bc0770a0b5f de1b4b32ef7d38785efc562a3288ed066b0be9398e4a64551d12adf423aac31f ec473b40c5958e1cd38765dcf3f52027f39ef29e5b776ba9ad03a6a25af31819 9f76430c33a33d246384dc198b4df3d7e4abf28277a2f435cce25696d01a4863 12e62108f7b920bea0b91f50b21fcabd2463af6f1e94242140bbde786e42eee5 a8edb67c9b69edb5c2c750a068c6d89553691fccc47a4241c67c12f3f9e2a0b2 2f2d5c2bd6baa68163d81cbdd75496e200e8446cf806f443834cd03bdb6eb828 87d607f5bc1cb6b8673767ad44d62d773fac4116b1f952cdb80fac61625b1d02 a7ab3f34b18c06ce17f374d662f57a19d2754f079d899fe29d4262c5b26f7855 441c25a5d728f37d257c4b7bde6d15736aa66d16b07ea088d2d1838eb01a5c55 1d0585ef57e70ab0ab8ea67a780f2a4680101a854bfab46dbb2a5092e7f2251b"}
|
||||||
---
|
---
|
||||||
apiVersion: batch/v1
|
apiVersion: batch/v1
|
||||||
kind: Job
|
kind: Job
|
||||||
@@ -37,7 +37,7 @@ spec:
|
|||||||
env:
|
env:
|
||||||
- {name: REGION_WORLD, value: "100"}
|
- {name: REGION_WORLD, value: "100"}
|
||||||
- {name: REGION_ID, value: "16"}
|
- {name: REGION_ID, value: "16"}
|
||||||
- {name: REGION_BUILD, value: f235d14aa06924010ac9e1a4cfad6148ed24447eafb33ef2df968a285f467457}
|
- {name: REGION_BUILD, value: 9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5}
|
||||||
# Region 16 (rules 13): cellular-v10, 60 x 60 mm at 20 C, taken through one empty tick,
|
# Region 16 (rules 13): cellular-v10, 60 x 60 mm at 20 C, taken through one empty tick,
|
||||||
# the durable upgrades to rules 11 with light, the liquid upgrade from the mounted
|
# the durable upgrades to rules 11 with light, the liquid upgrade from the mounted
|
||||||
# tuning file (whose region size must match) and the revamp upgrade from the mounted
|
# tuning file (whose region size must match) and the revamp upgrade from the mounted
|
||||||
|
|||||||
@@ -40,6 +40,11 @@ predation.kill_bubble_per_mille = 500 # a kill's remainder left as bubbles; th
|
|||||||
spent.drip_interval_ticks = 20 # once a second
|
spent.drip_interval_ticks = 20 # once a second
|
||||||
spent.drip_bubble_pj = 20_000_000 # largest energy bubble per drip
|
spent.drip_bubble_pj = 20_000_000 # largest energy bubble per drip
|
||||||
spent.drip_bubble_fg = 1_000_000 # largest matter bubble per drip and channel
|
spent.drip_bubble_fg = 1_000_000 # largest matter bubble per drip and channel
|
||||||
|
# Energy cycle (ADR-0182 section 14; optional, 0 when absent): the share of the region's heat
|
||||||
|
# (energy its cells used) returned to the spent pool every tick before the drip, and whether a
|
||||||
|
# drip at the deposit limit (8,192) joins an existing bubble instead of waiting.
|
||||||
|
spent.heat_recycle_per_mille = 1_000 # all of it: energy cycles back like matter
|
||||||
|
spent.drip_absorb = 1
|
||||||
|
|
||||||
# Mutation offers (mutation plan section 3). Chances in parts per million.
|
# Mutation offers (mutation plan section 3). Chances in parts per million.
|
||||||
mutation.options = 3
|
mutation.options = 3
|
||||||
@@ -67,6 +72,7 @@ reproduction.bud_fee_p_fg = 10_000
|
|||||||
reproduction.bud_fee_o_fg = 60_000
|
reproduction.bud_fee_o_fg = 60_000
|
||||||
reproduction.bud_fee_scale_percent = 50 # 0 disables the fee; 100 charges the listed amounts
|
reproduction.bud_fee_scale_percent = 50 # 0 disables the fee; 100 charges the listed amounts
|
||||||
reproduction.organism_cap = 256 # births refused at this many lives (an organism counts once)
|
reproduction.organism_cap = 256 # births refused at this many lives (an organism counts once)
|
||||||
|
reproduction.wildlife_cap = 200 # wildlife buds refused at this many lives: the rest are for players
|
||||||
|
|
||||||
# Multicellular organisms (reproduction plan section 6).
|
# Multicellular organisms (reproduction plan section 6).
|
||||||
organism.load_per_mille = 500 # share of the extra members' mass loading one cell's thrust
|
organism.load_per_mille = 500 # share of the extra members' mass loading one cell's thrust
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ spec:
|
|||||||
- {name: PGSERVICEFILE, value: /run/postgres/pg_service.conf}
|
- {name: PGSERVICEFILE, value: /run/postgres/pg_service.conf}
|
||||||
- {name: EVO_PGPASS_SOURCE, value: /run/postgres/pgpass}
|
- {name: EVO_PGPASS_SOURCE, value: /run/postgres/pgpass}
|
||||||
- {name: EVO_PG_RUNTIME_ROLE, value: set-by-overlay}
|
- {name: EVO_PG_RUNTIME_ROLE, value: set-by-overlay}
|
||||||
|
# ADR-0182: the admin API's group role; empty grants no admin functions.
|
||||||
|
- {name: EVO_PG_ADMIN_ROLE, value: ""}
|
||||||
resources:
|
resources:
|
||||||
requests: {cpu: 100m, memory: 64Mi}
|
requests: {cpu: 100m, memory: 64Mi}
|
||||||
limits: {memory: 128Mi}
|
limits: {memory: 128Mi}
|
||||||
|
|||||||
@@ -10,12 +10,11 @@ resources:
|
|||||||
images:
|
images:
|
||||||
- name: aevolution-postgres-tools
|
- name: aevolution-postgres-tools
|
||||||
newName: registry.aeternalisgames.com/aeternalis/aevolution-postgres-tools
|
newName: registry.aeternalisgames.com/aeternalis/aevolution-postgres-tools
|
||||||
# Gitea CI run 540 for d46de25 (schema v60, bundle 15, reproduction safety revision 1);
|
# Gitea CI run 576 for 9de55e3 (schema v69: one action per account a tick; bundle 15).
|
||||||
# the server image is from the same run.
|
digest: sha256:c200bd438376abf49292c63691bca8cd8adc097a9e1f94cf926250f50be1fba8
|
||||||
digest: sha256:dc3e43ede086f3a8ab8e966fa57bb03766f9d39975681b5848b9f9245db9f04e
|
|
||||||
- name: aevolution-server
|
- name: aevolution-server
|
||||||
newName: registry.aeternalisgames.com/aeternalis/aevolution-server
|
newName: registry.aeternalisgames.com/aeternalis/aevolution-server
|
||||||
digest: sha256:f235d14aa06924010ac9e1a4cfad6148ed24447eafb33ef2df968a285f467457
|
digest: sha256:9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5
|
||||||
patches:
|
patches:
|
||||||
- target:
|
- target:
|
||||||
kind: Job
|
kind: Job
|
||||||
@@ -24,3 +23,7 @@ patches:
|
|||||||
- op: replace
|
- op: replace
|
||||||
path: /spec/template/spec/containers/0/env/3/value
|
path: /spec/template/spec/containers/0/env/3/value
|
||||||
value: aevolution_runtime
|
value: aevolution_runtime
|
||||||
|
# Operator-created NOLOGIN group of the admin portal's login (ADR-0182).
|
||||||
|
- op: replace
|
||||||
|
path: /spec/template/spec/containers/0/env/4/value
|
||||||
|
value: aevolution_admin
|
||||||
|
|||||||
+106
@@ -1,5 +1,111 @@
|
|||||||
# Project status and next steps
|
# Project status and next steps
|
||||||
|
|
||||||
|
## One action per account a tick - 2026-10-29
|
||||||
|
|
||||||
|
Region 16 playtest: a bud was shown, then undone, and several were "refused". The client
|
||||||
|
scheduled a bud at the server tick plus its lead, while movement had run ahead of that after the
|
||||||
|
lead shrank, so both named one tick. A tick takes one action per account, so the region refused
|
||||||
|
the whole tick and dropped every player's actions on it (`tick stalled ... error=4`). The region
|
||||||
|
now keeps each account's discrete action (else its newest) and refuses only the others; the client
|
||||||
|
schedules a discrete action after every tick it already sent and holds movement off that tick.
|
||||||
|
Failed commits now log their category and SQLSTATE.
|
||||||
|
|
||||||
|
## Ending a stranded life - 2026-10-29
|
||||||
|
|
||||||
|
The portal's account page can end a published life whose reservation was never ended, which
|
||||||
|
refused every new birth ("Existing cell is already bound to this account"). The admin API first
|
||||||
|
checks the region's live view for any cell holding the account; schema 69 records who ended it
|
||||||
|
and why. A region with no ticking cells now still applies queued admin commands, such as a
|
||||||
|
spawn. See [ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 18.
|
||||||
|
|
||||||
|
## Larger region ticks for testing - 2026-10-28
|
||||||
|
|
||||||
|
A region tick may hold up to 4,096 lives (was 256), for testing limits only, and
|
||||||
|
`reproduction.organism_cap` accepts up to 4,096; the DEV file keeps 256. Schema 68 raises the
|
||||||
|
database's per-tick trace counts and lets one spawn command place 256 wildlife. The region page
|
||||||
|
shows the lineage archive's fill, which stops a region at 65,536 births. See
|
||||||
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 17.
|
||||||
|
|
||||||
|
## Testing a full region - 2026-10-28
|
||||||
|
|
||||||
|
The Bud button follows a tuning adoption at once (the region's bud-cost cache was keyed by
|
||||||
|
genome only). `reproduction.wildlife_cap` keeps lives above it for players' buds. Two admin
|
||||||
|
commands (schema 67): take reserve from a cell, and remove all wildlife; the region map marks
|
||||||
|
cells (shift+click, shift+drag) for bulk removal. See
|
||||||
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 16.
|
||||||
|
|
||||||
|
## Opening regions from the portal - 2026-10-28
|
||||||
|
|
||||||
|
The Regions page can open a fresh region in place of the one DEV serves: the admin API
|
||||||
|
commits the region switch to `main` as aevolution-bot (through Secret `aevolution-admin`) and
|
||||||
|
runs a full Argo sync, and the page follows the sync until the new region is live. See
|
||||||
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 15.
|
||||||
|
|
||||||
|
## Guided tuning editor - 2026-10-28
|
||||||
|
|
||||||
|
The Tuning page is a guided editor: pick a section, edit a setting's value (units and plain
|
||||||
|
readings shown), review the changes and apply. Only the changed values are sent and applied to
|
||||||
|
the newest revision on the server, which keeps the file's comments and refuses a stale base;
|
||||||
|
the whole-file text editor remains as Text mode.
|
||||||
|
|
||||||
|
## Energy cycle - 2026-10-28
|
||||||
|
|
||||||
|
Energy now cycles like matter: the heat cells produce (upkeep, motion, growth, feeding and
|
||||||
|
predation losses) returns to the spent pool every tick and drips back as bubbles, and a drip at
|
||||||
|
the deposit limit joins an existing bubble. Both are optional rules-13 tuning keys
|
||||||
|
(`spent.heat_recycle_per_mille`, `spent.drip_absorb`), adoptable live; the DEV revamp file
|
||||||
|
turns them on. See [ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 14.
|
||||||
|
|
||||||
|
## Admin region page - 2026-10-28
|
||||||
|
|
||||||
|
The admin portal's region page is reorganized around the map: a KPI strip (tick pace,
|
||||||
|
population, deposit capacity, region energy and matter, spent pool, next drip), a map with
|
||||||
|
layer toggles, zoom and a scale, and tabs for inspecting cells and deposits, the region's
|
||||||
|
resources (where every channel sits, the spent pool and its drip), actions, the running
|
||||||
|
tuning and session access. The region view adds complete counts and totals and the drip
|
||||||
|
rules; the portal has light and dark themes. See
|
||||||
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 13.
|
||||||
|
|
||||||
|
## Live tuning - 2026-10-27
|
||||||
|
|
||||||
|
The admin portal's Tuning page edits the world's rules-13 tuning (the Git revamp file
|
||||||
|
format) and adopts it in every region at a recorded tick, without a new image or region:
|
||||||
|
upkeep, burn, feeding, predation, the spent-pool drip, mutation offers and costs,
|
||||||
|
reproduction and organisms. Revisions are append-only with author and reason (schema 66);
|
||||||
|
the reproduction safety revision stays fixed. See
|
||||||
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 13.
|
||||||
|
|
||||||
|
## Resource schedules - 2026-10-27
|
||||||
|
|
||||||
|
The admin portal can schedule recurring bubbles (the game source), spent-pool releases and
|
||||||
|
wildlife spawns per region, every 1 s to 24 h, and stop or restart them. Each run is an
|
||||||
|
ordinary recorded admin command (schema 65). See
|
||||||
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 12.
|
||||||
|
|
||||||
|
## Account administration: bans, logout, time played - 2026-10-27
|
||||||
|
|
||||||
|
The admin portal can ban (and unban) an account, which also logs it out and stops new
|
||||||
|
grants; log an account out; and shows time played, sessions, last seen and living
|
||||||
|
offspring (wildlife descended from its lives). Schema 64; see
|
||||||
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 11.
|
||||||
|
|
||||||
|
## Admin commands: spawn wildlife, resources, remove and grant - 2026-10-27
|
||||||
|
|
||||||
|
The admin portal can now spawn wildlife, add bubbles, add to or release the spent pool,
|
||||||
|
remove a cell and grant a cell's reserve, live. Commands are queued in SQL (schema 63) and
|
||||||
|
the region applies each once, recording it in its history (trace 5) so replay and recovery
|
||||||
|
reproduce it. Imports are counted in the region's boundary ledger. No new region is needed.
|
||||||
|
See [ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 10 and
|
||||||
|
[validation](engineering/VALIDATION.md).
|
||||||
|
|
||||||
|
## Session windows from the admin portal - 2026-10-27
|
||||||
|
|
||||||
|
The dev session window now lives in SQL (schema 62) instead of Git: the admin portal opens,
|
||||||
|
extends (up to four hours from now) and closes it, and the region applies the change within
|
||||||
|
about five seconds without a push, sync or restart. A closed window refuses every new
|
||||||
|
session and the region keeps running. The admin API moves to its own database role. See the
|
||||||
|
[ADR-0087 amendment](adr/0087-dev-session-route.md) and [validation](engineering/VALIDATION.md).
|
||||||
|
|
||||||
## Read-only admin portal - 2026-10-27
|
## Read-only admin portal - 2026-10-27
|
||||||
|
|
||||||
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) records the admin portal direction
|
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) records the admin portal direction
|
||||||
|
|||||||
@@ -197,3 +197,34 @@ the pod-side checks (ready, listener bound) could not show this. Decision:
|
|||||||
Service UDP 7400 -> NetworkPolicy UDP 7400 -> evo-region M10 listener`, with the dev CA
|
Service UDP 7400 -> NetworkPolicy UDP 7400 -> evo-region M10 listener`, with the dev CA
|
||||||
and issuer key read from the authorized cluster Secret without printing or persisting
|
and issuer key read from the authorized cluster Secret without printing or persisting
|
||||||
them. Until that is recorded in VALIDATION.md the route is not declared working.
|
them. Until that is recorded in VALIDATION.md the route is not declared working.
|
||||||
|
|
||||||
|
## Amendment 2026-10-27: Session windows in SQL, opened from the admin portal
|
||||||
|
|
||||||
|
Maintainer decision (ADR-0182 discussion). Committing the window to Git meant a push and a
|
||||||
|
full Argo sync for every opening or extension, and an expired window made the region exit
|
||||||
|
and crash-loop until the next sync. The window moves to the database:
|
||||||
|
|
||||||
|
- **Record.** Schema 62 adds the append-only `evolution.session_windows` (world, region,
|
||||||
|
activation id, absolute UTC expiry or none, author, reason, time written). A row with an
|
||||||
|
expiry opens or replaces the window until then; a row without one closes it. The table
|
||||||
|
refuses updates, deletes and truncation, and a window may end at most **four hours** after
|
||||||
|
it is written (the maximum is unchanged).
|
||||||
|
- **Writing.** Only the admin group role, through `admin_set_session_window_v1`, from the
|
||||||
|
admin portal (Open or Extend for 30 min to 4 h, Close). The author is the signed-in
|
||||||
|
admin's email and Keycloak subject. The runtime group may only read the newest row
|
||||||
|
(`load_session_window_v1`).
|
||||||
|
- **Reading.** The cellular region runs with `--session-window-source db` and reads the newest
|
||||||
|
row every 5 s on its session-ledger connection. A newer activation replaces the window
|
||||||
|
without disturbing open sessions; a closing, expired, over-long or missing row closes it.
|
||||||
|
Each admitted window keeps its own absolute deadline, a window once closed never reopens
|
||||||
|
(only a newer activation opens sessions again), and an unreadable database leaves the
|
||||||
|
current window to close at its deadline.
|
||||||
|
- **Closed means closed.** While no window is open, every Hello is refused with `shutdown`
|
||||||
|
before signature work, and closing closes the open sessions. Previously the cellular
|
||||||
|
bridge closed the sessions once at expiry but still admitted new ones. The region keeps
|
||||||
|
running while closed instead of exiting.
|
||||||
|
- **Git.** `REGION_SESSION_WINDOW` and the pre-push refresh are removed; the policy check
|
||||||
|
requires `--session-window-source db` and refuses a committed window. A fixed
|
||||||
|
`--session-window` remains for the lineage/primitive bridge and process tests.
|
||||||
|
|
||||||
|
The elapsed-time guard of the 2026-10-08 clock amendment is still pending.
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
## Status and scope
|
## Status and scope
|
||||||
|
|
||||||
Accepted direction, 2026-10-27, from the maintainer's decisions in chat; implementation
|
Accepted direction, 2026-10-27, from the maintainer's decisions in chat; delivered in parts
|
||||||
pending. DEV (world 100) only; stage and World0 need their own review. Applies to a new owner
|
(sections 8-13). DEV (world 100) only; stage and World0 need their own review. Supersedes, for
|
||||||
format and new openings only:
|
rules-13 regions, ADR-0181's "Git tuning affects future openings only. No live retune": since
|
||||||
regions 12-16 keep their recorded rules and Git-mounted tuning. Supersedes, for that new
|
schema 66 (section 13) a running rules-13 region adopts tuning revisions at recorded ticks.
|
||||||
format, ADR-0181's "Git tuning affects future openings only. No live retune."
|
Regions on older rules keep their recorded rules.
|
||||||
|
|
||||||
## Context
|
## Context
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ may change a running region except an event recorded at a tick.
|
|||||||
|
|
||||||
### 1. World tuning lives in SQL
|
### 1. World tuning lives in SQL
|
||||||
|
|
||||||
- Schema 62 adds append-only `world_tuning_revisions(world, revision, parent_revision,
|
- Schema 63 adds append-only `world_tuning_revisions(world, revision, parent_revision,
|
||||||
format, canonical_text, digest, author_subject, reason, created_at)`. A revision is the
|
format, canonical_text, digest, author_subject, reason, created_at)`. A revision is the
|
||||||
complete canonical tuning text (`encode_cellular_revamp_tuning`), never a diff, so the
|
complete canonical tuning text (`encode_cellular_revamp_tuning`), never a diff, so the
|
||||||
existing parser and validator are the only interpretation.
|
existing parser and validator are the only interpretation.
|
||||||
@@ -51,7 +51,7 @@ may change a running region except an event recorded at a tick.
|
|||||||
|
|
||||||
### 3. Admin commands
|
### 3. Admin commands
|
||||||
|
|
||||||
- Schema 62 adds `admin_commands(world, region, command_id, kind, payload, author_subject,
|
- Schema 63 adds `admin_commands(world, region, command_id, kind, payload, author_subject,
|
||||||
reason, created_at, applied_tick, outcome)`. The admin API inserts and the region host
|
reason, created_at, applied_tick, outcome)`. The admin API inserts and the region host
|
||||||
drains them at tick boundaries in id order, publishing each with that tick. This is the
|
drains them at tick boundaries in id order, publishing each with that tick. This is the
|
||||||
same pattern as the durable mutation queue (schema 59).
|
same pattern as the durable mutation queue (schema 59).
|
||||||
@@ -160,14 +160,286 @@ pool holds. For the source, scale multiplies the import.
|
|||||||
(`'self'` scripts and styles, connections only to this origin and the realm), `nosniff`,
|
(`'self'` scripts and styles, connections only to this origin and the realm), `nosniff`,
|
||||||
`no-referrer` and `DENY` framing; every answer is `no-store`. The access token stays in
|
`no-referrer` and `DENY` framing; every answer is `no-store`. The access token stays in
|
||||||
page memory and the rotating refresh token in the tab's sessionStorage.
|
page memory and the rotating refresh token in the tab's sessionStorage.
|
||||||
- **Not yet available** (they need the schema-62 records): time played, bans, current
|
- **Not yet available** (they need the schema-63 records): time played, bans, current
|
||||||
mutations and living offspring.
|
mutations and living offspring.
|
||||||
|
|
||||||
|
### 9. Session windows and the admin role (schema 62)
|
||||||
|
|
||||||
|
The dev session window moves from Git to SQL and is opened, extended and closed from the
|
||||||
|
portal; see the [ADR-0087 amendment](0087-dev-session-route.md). Schema 62 also moves the
|
||||||
|
admin functions to a dedicated, operator-created NOLOGIN group role (`aevolution_admin` in
|
||||||
|
DEV, `EVO_PG_ADMIN_ROLE` for the migration): every migration run grants it exactly the admin
|
||||||
|
functions and audits it like the runtime group (no table privilege, no privileged
|
||||||
|
attribute, no membership outside it, not the runtime role). Schema 61's read views are
|
||||||
|
revoked from the runtime group. The admin API logs in with its own login in that group.
|
||||||
|
Writes go through POST without a body (`?minutes=M&reason=R`); the bearer token in the
|
||||||
|
`Authorization` header, never a cookie, is the only credential.
|
||||||
|
|
||||||
|
### 10. Admin commands (delivered, schema 63, trace 5)
|
||||||
|
|
||||||
|
The commands of section 3 are delivered without a new owner format or region opening:
|
||||||
|
|
||||||
|
- **Trace 5.** A rules-13 batch may record operator commands: trace 4 plus 64-byte records
|
||||||
|
(id, kind, count, target, energy and four matter amounts) counted in the tick header's last
|
||||||
|
word, which trace 4 keeps zero. A batch without commands stays trace 4, so builds before
|
||||||
|
this one still replay it; only commits that carry commands need this build or later.
|
||||||
|
Bundle 15 admits trace 5 (`cellular_checkpoint_trace_admits`); the manifest is unchanged.
|
||||||
|
- **Application.** `CellularLives::admin_candidate` applies a tick's commands after its
|
||||||
|
births, by ascending id, each on a copy kept only if it applies and still closes:
|
||||||
|
`remove_cell` (body and reserve to the spent pool, a corpse with the new `removed` cause;
|
||||||
|
a player's life then ends as any death does), `grant_reserve`, `add_bubbles` and
|
||||||
|
`add_pool` (imports in the boundary ledger), `release_pool` (moves at most what the pool
|
||||||
|
holds into bubbles) and `spawn_wildlife` (1-64 randomized founder roots, the ADR-0180 seed
|
||||||
|
with an exact import for their reserve, body and construction). A command whose target is
|
||||||
|
gone, or that does not fit (region cap, deposit limit, a taken identity), is refused and
|
||||||
|
changes nothing.
|
||||||
|
- **Queue and binding.** `admin_enqueue_command_v1` (admin role) stores the exact command;
|
||||||
|
spawning reserves its identities from the world's life allocator. The region reads
|
||||||
|
`load_pending_admin_commands_v1` every 2 s and appends up to 16 per tick. Both cellular
|
||||||
|
publishers bind every recorded command to its queue row exactly once, in the publishing
|
||||||
|
transaction; a differing or already-applied command refuses the publication. The SQL trace
|
||||||
|
parsers read a trace 5 through its trace-4 normal form, after binding the real trace to
|
||||||
|
the manifest.
|
||||||
|
- **Portal.** Region actions (spawn wildlife, add bubbles, add to or release the spent pool),
|
||||||
|
per-cell Remove and Grant reserve, and the command history with the tick each applied at.
|
||||||
|
Amounts are entered in µJ and ng.
|
||||||
|
|
||||||
|
### 11. Account administration (delivered, schema 64)
|
||||||
|
|
||||||
|
- **Bans.** Append-only `account_bans` rows; the newest per account decides. A banned
|
||||||
|
account's grant request fails with SQLSTATE EVL20 (the broker answers 403
|
||||||
|
`account_banned`), and banning also revokes its grants, so a live session closes at its
|
||||||
|
next control renewal. Lifting a ban is another row.
|
||||||
|
- **Logout.** `admin_logout_account_v1` revokes by account id, as the player's own logout
|
||||||
|
does by Keycloak identity.
|
||||||
|
- **Time played.** The session-control functions keep their signatures and also record
|
||||||
|
`session_intervals`: a claim opens one, a renewal moves its last-seen time, a release ends
|
||||||
|
it; an unreleased session ends at its last renewal. History starts with schema 64.
|
||||||
|
- **Living offspring.** The region view adds each cell's lineage root; the portal counts
|
||||||
|
living wildlife whose root is one of the account's lives.
|
||||||
|
|
||||||
|
### 12. Resource schedules (delivered, schema 65)
|
||||||
|
|
||||||
|
The game source of section 4 without a new owner format: a schedule repeats an
|
||||||
|
`add_bubbles`, `release_pool` or `spawn_wildlife` command (count, amounts per resource)
|
||||||
|
every 1 s to 24 h while enabled. When the region reads its pending commands, each due
|
||||||
|
schedule queues its next command as an operator would, so it is recorded in the trace and
|
||||||
|
bound once; a schedule never has two commands waiting, so an idle region (no living cells,
|
||||||
|
no ticks) accumulates nothing. Versions are append-only; the newest decides.
|
||||||
|
|
||||||
|
The spent pool's own drip (interval, bubble caps, bubbles per drip, per-channel scale) is a
|
||||||
|
rules setting and stays with the tuning amendments.
|
||||||
|
|
||||||
|
### 13. Tuning amendments (delivered, schema 66)
|
||||||
|
|
||||||
|
Sections 1-2 are delivered without a new owner format or opening, so running rules-13 regions
|
||||||
|
(region 16 included) can be retuned:
|
||||||
|
|
||||||
|
- **Revisions.** Append-only `tuning_revisions(revision, world, text, rules_sha256, author,
|
||||||
|
reason, created_at)`. The text is the Git revamp tuning file format, kept as the admin wrote
|
||||||
|
it (comments included); `rules_sha256` is the SHA-256 of `encode_cellular_revamp_rules` for
|
||||||
|
the rules it produces, the same canonical bytes the owner snapshot stores. The admin API
|
||||||
|
parses and validates the text (`parse_cellular_revamp_tuning`, `cellular_revamp_rules`,
|
||||||
|
`cellular_revamp_valid`) before storing it, and `admin_set_tuning_v1` queues the adoption
|
||||||
|
in every region of the world in the same transaction.
|
||||||
|
- **Adoption is an admin command.** Kind 7 `adopt_tuning` carries the revision as its target
|
||||||
|
and the rules digest in its four amount words (little-endian; `other` zero). It is queued
|
||||||
|
only through a revision, never by kind. The region fetches the revision's text
|
||||||
|
(`load_tuning_revision_v1`), rebuilds the rules with its own parser and appends the command
|
||||||
|
only when the digest matches; a text it cannot parse or a mismatch is logged and the command
|
||||||
|
stays pending (section 2's `tuning_refused`). Applied at a tick after births, the command
|
||||||
|
replaces the region's rules; it is recorded in trace 5 and bound once like any command.
|
||||||
|
- **Replay and recovery.** Applying or replaying an adoption needs whoever does it to name
|
||||||
|
the rules for that revision and digest (`CellularTuningResolver`): the host from its
|
||||||
|
verified revisions, the publisher and recovery from the successor state, checked against
|
||||||
|
the recorded digest. A batch carries at most one adoption, so its successor names exactly
|
||||||
|
one set of rules. Nothing reads "the latest" revision.
|
||||||
|
- **What cannot change live.** `reproduction.safety_version` is a law of the opening
|
||||||
|
(ADR-0181): the admin API refuses a text that changes it, and a region would refuse the
|
||||||
|
command. `playtest.*` only matters when a region opens. Heritable values already in genomes
|
||||||
|
are not rewritten.
|
||||||
|
- **Portal.** A Tuning page: the editor starts from the newest revision or the baseline file
|
||||||
|
the regions opened with (`--baseline-tuning`, the mounted Git revamp file), Check reports
|
||||||
|
the line, key and kind of a problem, Adopt stores the revision with a reason, the revision
|
||||||
|
list shows how many regions adopted each, and each region shows which revision its live
|
||||||
|
rules match (`rules_sha256` in the region view).
|
||||||
|
- **Guided editor (2026-10-28).** The Tuning page edits by section: each setting as a field
|
||||||
|
with its unit, a reading in plain units and its comment, changed values listed against the
|
||||||
|
base. `POST /api/tuning?base=baseline|REV` takes only the changed `key = value` lines and
|
||||||
|
applies them to the baseline file or to revision REV, which must be the newest (409
|
||||||
|
`stale_base` otherwise), keeping the base's comments; the result is checked and stored as
|
||||||
|
any full text. DEV's ingress admits request bodies of about 1 KB, below a whole revamp
|
||||||
|
file, so the full-text editor (kept as Text mode) reports that proxy refusal plainly.
|
||||||
|
- **Region page (2026-10-28).** The region view also carries the rules-13 drip
|
||||||
|
(`drip`: interval, energy and matter bubble caps) and, over every life and deposit whatever
|
||||||
|
the listing limits, `counts` (players, wildlife, patches, pools, bubbles) and `totals`
|
||||||
|
(reserve, body, patch, pool and bubble stock). The region page shows where the region's
|
||||||
|
stock sits, the spent pool with each channel's next drip and time to empty, a countdown to
|
||||||
|
the next drip at the measured tick pace, the deposit capacity (8,192) and whether the tick
|
||||||
|
is advancing. Its Tuning tab lists the settings the region runs (the matching revision or
|
||||||
|
baseline text) and the region tuning file (`--region-tuning`, the mounted `cellular.tuning`,
|
||||||
|
read only). The portal has light and dark themes.
|
||||||
|
|
||||||
|
Live today: everything the revamp file holds, including the drip (`spent.drip_interval_ticks`,
|
||||||
|
`spent.drip_bubble_pj`, `spent.drip_bubble_fg`). Section 4's new drip settings (bubbles per
|
||||||
|
drip, per-channel scale) are new rules fields, so they need a rules format change; the
|
||||||
|
resource schedules of section 12 cover the game source meanwhile.
|
||||||
|
|
||||||
|
Still pending from this ADR: section 4's new drip settings,
|
||||||
|
data-defined mutations (section 5) and the account's current mutations; opening new regions
|
||||||
|
or worlds from the portal (a later gate: Git-generated manifests through the Gitea API and an
|
||||||
|
Argo sync for one more region in the world; several concurrent regions or worlds need
|
||||||
|
per-region Deployments, volumes and routes).
|
||||||
|
|
||||||
|
### 14. Energy cycle (delivered 2026-10-28, live-tunable)
|
||||||
|
|
||||||
|
Matter a cell burns returns to the spent pool and drips back; energy it uses (upkeep, motion,
|
||||||
|
growth, mutation rebuilds, the share of a bubble lost in feeding, predation losses) went to the
|
||||||
|
region's heat store and never came back. Light is the only new energy, so a region without
|
||||||
|
photosynthesizers drained into heat: region 16's wildlife ate the region's energy and starved,
|
||||||
|
its spent pool held only matter, and the matter-only bubbles it dripped filled the 8,192
|
||||||
|
deposits.
|
||||||
|
|
||||||
|
- **Heat recycling.** `spent.heat_recycle_per_mille` (rules field `heat_recycle_per_thousand`,
|
||||||
|
0..1,000): at the end of every tick, before the drip, that share of the region's whole heat
|
||||||
|
store moves to the spent pool. 1,000 closes the loop, and adopting it also returns the heat
|
||||||
|
a region built up before. Energy is conserved as before (heat and spent are both region
|
||||||
|
stock). Below 1,000 the heat returns more slowly; nothing is lost.
|
||||||
|
- **Absorbing drip.** `spent.drip_absorb` (0/1): a drip at the deposit limit adds its amount
|
||||||
|
to an existing bubble, the first at or after its seeded spot in address order (wrapping),
|
||||||
|
instead of waiting. A habitat with no bubble at all still waits.
|
||||||
|
- **Encoding.** Both fields use the reserved word after the offer interval (the recycle share
|
||||||
|
in the low 16 bits, the absorbing drip in bit 16), so rules without them keep their exact
|
||||||
|
bytes, digests, checkpoints and replays. Both keys are optional in the tuning file and can be
|
||||||
|
adopted live as a tuning revision; the DEV file sets 1,000 and 1.
|
||||||
|
- **View and portal.** The region view reports `heat` and the drip's recycle share and absorb
|
||||||
|
flag; the region page counts heat in the region's energy and its ledger, and says when energy
|
||||||
|
is being lost as heat.
|
||||||
|
|
||||||
|
Not changed: a region with no living cell does not tick, so it neither recycles nor drips; an
|
||||||
|
empty region needs a spawn or a player before the cycle restarts.
|
||||||
|
|
||||||
|
### 15. Opening a region from the portal (delivered 2026-10-28, DEV)
|
||||||
|
|
||||||
|
The portal opens a fresh region in place of the one DEV serves, as was done by hand for
|
||||||
|
regions 14, 15 and 16. Concurrent regions and new worlds remain later work (per-region
|
||||||
|
Deployments, routes and ports; a multi-world admin API and broker).
|
||||||
|
|
||||||
|
- **Decisions (2026-10-28).** Replace the served region; commit straight to `main` and run a
|
||||||
|
full Argo sync at once (CI runs on the commit afterwards); the admin portal pod may reach
|
||||||
|
Gitea and argocd-server; the in-cluster Argo hop may skip TLS verification
|
||||||
|
(`ARGOCD_TLS_VERIFY=false`).
|
||||||
|
- **Credentials.** Secret `aevolution-admin` (created by the operator: Gitea base URL,
|
||||||
|
repository and repository-scoped token for `aevolution-bot`; Argo CD server, Application and
|
||||||
|
token) is mounted read-only as files at `/run/deploy` (`--deploy-config`), never as
|
||||||
|
environment; optional, so the portal runs without it and the feature stays off. Tokens travel
|
||||||
|
only in request headers and are never logged.
|
||||||
|
- **The change.** Four files, read at one commit of `main` with their blob shas
|
||||||
|
(`region_switch_paths`): the region overlay's `region-values.yaml` (REGION_ID for the
|
||||||
|
Deployment and the provision Job, REGION_LIFE_ROUTES, the opening's `--commit` and
|
||||||
|
`--playtest-wildlife-first-id`, and a one-line note above the opening), its kustomization
|
||||||
|
header, and the region named in the grant broker's routes and the portal's `ADMIN_REGIONS`.
|
||||||
|
Nothing else changes; a file whose expected lines are missing, repeated or inconsistent is
|
||||||
|
refused. The next region is one above every region with a lease in the world; its seeded
|
||||||
|
wildlife range follows the previous one by `playtest.starting_wildlife_cells`; its genesis
|
||||||
|
commit is 16 random bytes. One Gitea multi-file commit (the shas guard concurrent edits),
|
||||||
|
then `POST /api/v1/applications/<app>/sync` for exactly that commit with prune: the
|
||||||
|
provision hook opens the region before the region host restarts on it.
|
||||||
|
- **Guards.** The request names the region the portal showed (409 if another is next now);
|
||||||
|
a running Argo operation refuses (409); the portal asks the admin to type the number. The
|
||||||
|
earlier region stays in the stores, unserved; a new region's session window starts closed.
|
||||||
|
- **Network.** The portal's NetworkPolicy adds egress to 172.10.1.160:443 (Gitea through the
|
||||||
|
node's ingress) and to the argocd-server pods on 8080.
|
||||||
|
|
||||||
|
### 16. Testing a full region (delivered 2026-10-28, schema 67)
|
||||||
|
|
||||||
|
Playtesting region 16 (230 spawned wildlife under the 256-life cap) found three gaps.
|
||||||
|
|
||||||
|
- **Stale bud costs.** The region host caches each genome's bud cost for the client's Bud
|
||||||
|
button. The cache was keyed by genome only, so after a tuning adoption players saw the old
|
||||||
|
cost (or "cannot bud") until the region restarted. The cache now clears when the rules'
|
||||||
|
encoding changes.
|
||||||
|
- **Wildlife cap.** Wildlife bud whenever they can pay, so at the organism cap every slot a
|
||||||
|
death freed went to a wildlife bud before a player's bud arrived; the player saw "no space".
|
||||||
|
`reproduction.wildlife_cap` (rules field `wildlife_cap`, 0..organism cap, 0 = the organism
|
||||||
|
cap) refuses buds of a parent without an account at that many lives, keeping the slots above
|
||||||
|
it for players. Spawning still answers to the organism cap. It takes bits 17-31 of the
|
||||||
|
word holding the energy cycle (section 14), so rules without it keep their bytes and digests;
|
||||||
|
the key is optional, adoptable live, and the DEV file sets 200. The region view reports
|
||||||
|
both caps (`caps`), and the region page's Population shows lives against the cap.
|
||||||
|
- **Take and cull.** Two admin command kinds: `take_reserve` (8) moves up to the given amounts
|
||||||
|
from one life's reserve to the spent pool, per channel never more than it holds (the inverse
|
||||||
|
of `grant_reserve`); `remove_wildlife` (9) removes every life without an account in one
|
||||||
|
command, each as `remove_cell` does (body and reserve to the spent pool, a removed corpse).
|
||||||
|
Schema 67 widens the kind check and `admin_enqueue_command_v1`. The portal adds Take reserve
|
||||||
|
to the cell inspector, Remove all wildlife to Actions, and marking on the map (shift+click,
|
||||||
|
shift+drag a box) to remove the marked cells, one `remove_cell` each.
|
||||||
|
|
||||||
|
The organism cap itself is section 17.
|
||||||
|
|
||||||
|
### 17. Larger region ticks for testing (delivered 2026-10-28, schema 68)
|
||||||
|
|
||||||
|
The region/movement plan set a 2,000-organism region cap, but the rules-12 key it became
|
||||||
|
(`region.organism_cap`) was parsed and never enforced. The real bound was the engine's
|
||||||
|
`max_cellular_tick_lives = 256`, a per-tick safety bound from ADR-0106 that the batch trace,
|
||||||
|
checkpoints and database trace checks were sized from; rules 13's `reproduction.organism_cap`
|
||||||
|
was capped at it.
|
||||||
|
|
||||||
|
- **Decision (2026-10-28).** The tick bound is 4,096 lives, for testing limits only; regions
|
||||||
|
are not meant to run that many. The DEV tuning file keeps 256.
|
||||||
|
- **Split bound.** `max_cellular_tick_lives` (4,096) bounds the raw region path: the step, the
|
||||||
|
owner state, the batch trace (`cellular_batch_bytes_for`) and current checkpoint traces.
|
||||||
|
`max_cellular_frozen_lives` (256) keeps the formats whose database checks are fixed: cohort
|
||||||
|
populations, population batches, migration traces and pre-v3 cellular traces. Rules 12 and
|
||||||
|
13 never use those paths.
|
||||||
|
- **Tuning.** `reproduction.organism_cap` and `reproduction.wildlife_cap` accept up to 4,096.
|
||||||
|
- **Schema 68.** The trace checker under the current publishers (schema 43's, renamed
|
||||||
|
`cellular_births_v45` by schema 46) accepts up to 4,096 intents, births and mutation choices
|
||||||
|
per tick; `spawn_wildlife` takes up to 256 cells a command (sixteen commands fill a tick).
|
||||||
|
- **Archive.** The lineage archive never forgets: a region stops ticking at 65,536 recorded
|
||||||
|
births or 4,096 genomes. The region view reports both (`archive`) and the portal's
|
||||||
|
Population shows the fuller one, warning at 80%. A crowded region reaches them sooner.
|
||||||
|
- **Not changed.** Performance: region 16 ran at about 5 of 20 ticks per second with about
|
||||||
|
250 lives, so a region near the bound will run far below real time. The client snapshot is
|
||||||
|
budgeted (nearest changes first), so it degrades rather than fails.
|
||||||
|
|
||||||
|
### 18. Ending a stranded life (delivered 2026-10-29, schema 69)
|
||||||
|
|
||||||
|
Region 16 playtest: the region refused every birth for an account with "Existing cell is
|
||||||
|
already bound to this account", although no cell in it held the account. The database refuses
|
||||||
|
a birth while the account has an open life reservation anywhere in the world; this one was
|
||||||
|
published and never ended. How it was left open is not yet known. Until 2026-10-29 the only
|
||||||
|
remedy was `tools/ops/end-account-life.sql` as the database owner.
|
||||||
|
|
||||||
|
- **Account action.** `POST /api/accounts/<uuid>/end-life?request=N[&reason=R]`. The admin API
|
||||||
|
reads the life's region from the account's lives, fetches that region's live view and refuses
|
||||||
|
(409 `life_in_region`) while any listed cell holds the account, including a bud, a split's
|
||||||
|
offspring or an organism that control moved to. It also refuses a region it cannot view, a
|
||||||
|
view that does not list every cell, a request never published (404) and a life no longer open
|
||||||
|
(409 `not_open`).
|
||||||
|
- **Schema 69.** `admin_end_account_life_v1` (admin role only) ends the reservation at the
|
||||||
|
region's latest commit, as `end_cellular_lives` does, and appends who and why to
|
||||||
|
`admin_life_endings` (immutable). Unpublished reservations stay with the region, which still
|
||||||
|
holds them as queued births. Checkpoints and history are unchanged.
|
||||||
|
- **Safety.** If the check were wrong, the region still refuses a birth for an account that holds
|
||||||
|
a cell in its state (`life_exists`), which records an existing-life refusal.
|
||||||
|
- **Existing-life refusals are recorded.** That refusal could never be recorded:
|
||||||
|
`reject_primitive_life` (schema 15) accepted only reasons 1 to 3, and existing_life is 4.
|
||||||
|
The region dropped the birth from its queue but left the reservation open and unpublished,
|
||||||
|
which then refused every later birth for the account. Schema 69 accepts 4, both in the
|
||||||
|
function and in its C++ wrapper.
|
||||||
|
- **Portal.** The account page shows an End life button for each published life that has not
|
||||||
|
ended.
|
||||||
|
- **Idle regions take commands.** A region ticks only while something needs it: a player, a
|
||||||
|
waiting birth, a cell not suspended, or ecological work. A command queued in an empty region,
|
||||||
|
such as a spawn of wildlife, waited until something else woke it. A queued admin command now
|
||||||
|
keeps the region ticking until it is applied.
|
||||||
|
|
||||||
## Delivery order
|
## Delivery order
|
||||||
|
|
||||||
1. Read-only portal: login, accounts (from existing data), regions, region view (schema 61,
|
1. Read-only portal: login, accounts (from existing data), regions, region view (schema 61,
|
||||||
section 8).
|
section 8).
|
||||||
2. Schema 62 and the new owner format: world revisions, adoption records, admin commands,
|
2. Schema 63 and the new owner format: world revisions, adoption records, admin commands,
|
||||||
game source, drip settings, the score vector, session intervals and bans. One new
|
game source, drip settings, the score vector, session intervals and bans. One new
|
||||||
opening on that format.
|
opening on that format.
|
||||||
3. Admin commands and account actions in the portal.
|
3. Admin commands and account actions in the portal.
|
||||||
|
|||||||
@@ -10471,3 +10471,106 @@ Keycloak client, Ingress, Secret and a new server image are not in place yet); a
|
|||||||
lives and deaths were checked only on accounts without lives. The MSVC and sanitizer
|
lives and deaths were checked only on accounts without lives. The MSVC and sanitizer
|
||||||
presets and the image build/smoke were not run locally. Nothing was deployed, pushed or
|
presets and the image build/smoke were not run locally. Nothing was deployed, pushed or
|
||||||
synced; no World0, stage or live database operation occurred.
|
synced; no World0, stage or live database operation occurred.
|
||||||
|
|
||||||
|
## 2026-10-27 - Session windows in SQL and the admin role (schema 62)
|
||||||
|
|
||||||
|
Scope: the ADR-0087 amendment and ADR-0182 section 9. Schema 62 adds the append-only
|
||||||
|
`session_windows` table, `load_session_window_v1` (runtime), `admin_set_session_window_v1`
|
||||||
|
and `admin_session_windows_v1` (admin), and moves schema 61's views to the optional
|
||||||
|
operator-created admin group role, granted and audited on every migration run. The cellular
|
||||||
|
region reads the window every 5 s with `--session-window-source db`; `RegionSessions` gains
|
||||||
|
an admission switch so a closed window refuses Hellos before signature work (previously new
|
||||||
|
sessions were still admitted after expiry). The portal opens, extends and closes windows.
|
||||||
|
Git no longer carries `REGION_SESSION_WINDOW`. No simulation, checkpoint or wire change.
|
||||||
|
|
||||||
|
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres):
|
||||||
|
|
||||||
|
- Full build of the tree with -Werror (one -Wshadow fix in the new test).
|
||||||
|
- CTest `session`: 5/5 passed, including the new SessionWindowFeed cases (no record, open,
|
||||||
|
same-record no-op, extension by a newer activation, own deadline, no reopening, closing
|
||||||
|
row, expired and over-long refusals, a vanished record).
|
||||||
|
- `tools/ci/postgres-check.sh --full` passed (637 s, every phase). The admin API tests now
|
||||||
|
log in as the new admin login: open with reason, history and author, extend, close,
|
||||||
|
regions list state, 400s for bad minutes and reasons, 403 without the role, 405 on other
|
||||||
|
POST paths, 503 for an unknown region; the runtime role reads only the current window and
|
||||||
|
can no longer call the admin views or the writer; the table refuses UPDATE, DELETE and a
|
||||||
|
window over four hours. The test cluster gained an admin group role and login; the
|
||||||
|
private verify-backup cluster ignores the admin role; the schema-50 rewind and the
|
||||||
|
future-version probe move up to 62/63.
|
||||||
|
- clang-tidy 19 (warnings as errors) on the changed sources; one unchecked-optional fix in
|
||||||
|
the window test. A pre-existing finding in region_sessions.cpp:291 under the standalone
|
||||||
|
invocation is outside this change. clang-format 19.1.5 applied; `node --check` on the
|
||||||
|
portal script.
|
||||||
|
- Deploy suite passed: the policy check now requires `--session-window-source db` and
|
||||||
|
refuses a committed `REGION_SESSION_WINDOW` (self-test cases added for both).
|
||||||
|
|
||||||
|
Limits: no live region has read a SQL window yet, and no process test drives the database
|
||||||
|
window through a real session; the elapsed-time guard of the 2026-10-08 clock amendment is
|
||||||
|
still pending. Applying it needs the DEV `aevolution_admin` role and the admin portal's own
|
||||||
|
login first.
|
||||||
|
|
||||||
|
## 2026-10-27 - Admin commands in trace 5 (schema 63)
|
||||||
|
|
||||||
|
Scope: ADR-0182 section 10. Operators queue commands in the admin portal (remove a cell,
|
||||||
|
grant a reserve, add bubbles, add to or release the spent pool, spawn wildlife); the
|
||||||
|
cellular region applies each once after a tick's births and records it in trace 5, which
|
||||||
|
bundle 15 admits beside trace 4. Publication binds each recorded command to its queue row
|
||||||
|
in the same transaction. No owner format, rules, manifest bundle, genome, wire version or
|
||||||
|
golden changed; a corpse may carry the new `removed` cause (refused by older readers).
|
||||||
|
The ADR-0180 seeding loop moved into a shared helper with identical draws.
|
||||||
|
|
||||||
|
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres):
|
||||||
|
|
||||||
|
- `cellular-revamp-owner-contracts`: new case applying all six kinds plus a refused one
|
||||||
|
(missing target): results, closure through the boundary ledger, the exact spent pool,
|
||||||
|
bubble counts, the removed corpse, spawned wildlife, restore, determinism, trace-5
|
||||||
|
round trip and replay equality, trace 4 refusing commands; the existing starting-wildlife
|
||||||
|
and trace cases still pass after the seeding refactor.
|
||||||
|
- `tools/ci/postgres-check.sh --full` passed (637 s, every phase). New PostgreSQL cases: on
|
||||||
|
the starting-wildlife region, commands queued through `admin_enqueue_command_v1` (spawn
|
||||||
|
identities from the life allocator), a tampered trace-5 batch refused by the binding, the
|
||||||
|
exact batch published with three bindings at its tick and no pending commands left,
|
||||||
|
recovery equal to the applied state, and a second publication of the same commands
|
||||||
|
refused; admin API command endpoints (shape refusals, unknown region, author/reason,
|
||||||
|
history order, runtime role limited to the pending read, rows immutable).
|
||||||
|
- An existing test bug surfaced: the starting-wildlife publication test did not advance its
|
||||||
|
head after its tick commit; it now does before the command batch.
|
||||||
|
- clang-tidy 19 (warnings as errors) on the changed sources after narrowing the command kind
|
||||||
|
to a byte (the trace keeps a u16 and refuses values over 255); clang-format 19.1.5;
|
||||||
|
`node --check` on the portal script.
|
||||||
|
|
||||||
|
Limits: no live region has applied a command yet; the portal's command forms were not
|
||||||
|
driven in a browser.
|
||||||
|
|
||||||
|
## 2026-10-27 - Account administration (schema 64)
|
||||||
|
|
||||||
|
Scope: ADR-0182 section 11. Bans (append-only, a ban also revokes grants), an admin logout,
|
||||||
|
time played from session intervals recorded by the unchanged-signature control functions,
|
||||||
|
the broker's 403 `account_banned`, and each cell's lineage root in the region view for the
|
||||||
|
portal's living-offspring count. No simulation, trace, checkpoint or wire change.
|
||||||
|
|
||||||
|
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres): full build; CTest
|
||||||
|
119/119; `tools/ci/postgres-check.sh --full` passed (637 s, every phase, including the
|
||||||
|
schema-50 rewind restoring the four wrapped control and grant functions, the permission
|
||||||
|
audit and checksum drift with the probe at 65). New PostgreSQL cases: sessions recorded from
|
||||||
|
the broker test's control claims, ban with reason (listed in the account and its history),
|
||||||
|
`issue_account_grant` refused with the banned error while banned and allowed after lifting,
|
||||||
|
admin logout, refused shapes (bad flag, unknown action, POST on the account itself).
|
||||||
|
|
||||||
|
Limits: no live ban or logout was exercised against a connected client; time played starts
|
||||||
|
at this schema.
|
||||||
|
|
||||||
|
## 2026-10-27 - Resource schedules (schema 65)
|
||||||
|
|
||||||
|
Scope: ADR-0182 section 12. Recurring add_bubbles, release_pool and spawn_wildlife commands
|
||||||
|
queued by the pending-command read when due (one outstanding per schedule); append-only
|
||||||
|
schedule versions; admin API and portal card. No C++ simulation, trace or wire change.
|
||||||
|
|
||||||
|
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG): full build; CTest 119/119;
|
||||||
|
`tools/ci/postgres-check.sh --full` passed (639 s, every phase; the schema-50 rewind restores
|
||||||
|
the pending-command read, and the probe moves to 66). New PostgreSQL cases: refused shapes
|
||||||
|
(disallowed kind, zero and over-long intervals, missing amounts, unknown schedule), a due
|
||||||
|
schedule queuing exactly one command across repeated reads, its run count and author in the
|
||||||
|
listings, and stopping it by a new version.
|
||||||
|
|
||||||
|
Limits: no live schedule has run on a region yet.
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ void capacity(std::uint32_t count) {
|
|||||||
std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - start).count()));
|
std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - start).count()));
|
||||||
require(population->state().lives().size() == count, "capacity silently culled a life");
|
require(population->state().lives().size() == count, "capacity silently culled a life");
|
||||||
}
|
}
|
||||||
if (count == biology::max_cellular_tick_lives) {
|
if (count == biology::max_cellular_frozen_lives) {
|
||||||
const auto before = population->state().snapshot();
|
const auto before = population->state().snapshot();
|
||||||
LifeRequest request{};
|
LifeRequest request{};
|
||||||
request.account.front() = 1;
|
request.account.front() = 1;
|
||||||
|
|||||||
@@ -12,7 +12,11 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace evo::biology {
|
namespace evo::biology {
|
||||||
inline constexpr std::size_t max_cellular_tick_lives = 256;
|
// Lives one region tick may hold (ADR-0182 section 17: 4,096 for testing; regions run far
|
||||||
|
// fewer). Formats frozen at the original 256 (cohort populations, migration traces and the
|
||||||
|
// pre-v3 cellular traces) keep max_cellular_frozen_lives.
|
||||||
|
inline constexpr std::size_t max_cellular_tick_lives = 4'096;
|
||||||
|
inline constexpr std::size_t max_cellular_frozen_lives = 256;
|
||||||
|
|
||||||
// ADR-0124 (rules 3): a predator needs total mass >= ratio x prey total mass, with the
|
// ADR-0124 (rules 3): a predator needs total mass >= ratio x prey total mass, with the
|
||||||
// ratio in thousandths per micrometre of prey membrane (tunable; 1.5 for 1 um).
|
// ratio in thousandths per micrometre of prey membrane (tunable; 1.5 for 1 um).
|
||||||
@@ -120,7 +124,8 @@ enum class CellularDeathCause : std::uint8_t {
|
|||||||
starved = 1,
|
starved = 1,
|
||||||
engulfed = 2,
|
engulfed = 2,
|
||||||
merged = 3,
|
merged = 3,
|
||||||
emerged = 4
|
emerged = 4,
|
||||||
|
removed = 5 // ADR-0182: an operator removed the cell (rules 13).
|
||||||
};
|
};
|
||||||
struct CellularCorpseCandidate {
|
struct CellularCorpseCandidate {
|
||||||
std::uint64_t life_id{};
|
std::uint64_t life_id{};
|
||||||
|
|||||||
@@ -41,6 +41,9 @@ struct CellularRevampTuning {
|
|||||||
predation_kill_bubble_per_mille{};
|
predation_kill_bubble_per_mille{};
|
||||||
// The spent pool's drip back into the region.
|
// The spent pool's drip back into the region.
|
||||||
std::int64_t spent_drip_interval_ticks{}, spent_drip_bubble_pj{}, spent_drip_bubble_fg{};
|
std::int64_t spent_drip_interval_ticks{}, spent_drip_bubble_pj{}, spent_drip_bubble_fg{};
|
||||||
|
// Optional energy cycle (ADR-0182 section 14): the share of the region's heat returned to
|
||||||
|
// the spent pool each tick, and whether a drip at the deposit limit joins an existing bubble.
|
||||||
|
std::int64_t spent_heat_recycle_per_mille{}, spent_drip_absorb{};
|
||||||
// Mutation offers (Cellular_mutation_plan.md section 3).
|
// Mutation offers (Cellular_mutation_plan.md section 3).
|
||||||
std::int64_t mutation_options{}, mutation_floor_ppm{}, mutation_cap_ppm{};
|
std::int64_t mutation_options{}, mutation_floor_ppm{}, mutation_cap_ppm{};
|
||||||
std::int64_t mutation_score_min{}, mutation_score_max{};
|
std::int64_t mutation_score_min{}, mutation_score_max{};
|
||||||
@@ -54,6 +57,7 @@ struct CellularRevampTuning {
|
|||||||
std::int64_t reproduction_bud_fee_e_pj{}, reproduction_bud_fee_c_fg{},
|
std::int64_t reproduction_bud_fee_e_pj{}, reproduction_bud_fee_c_fg{},
|
||||||
reproduction_bud_fee_n_fg{}, reproduction_bud_fee_p_fg{}, reproduction_bud_fee_o_fg{};
|
reproduction_bud_fee_n_fg{}, reproduction_bud_fee_p_fg{}, reproduction_bud_fee_o_fg{};
|
||||||
std::int64_t reproduction_bud_fee_scale_percent{}, reproduction_organism_cap{};
|
std::int64_t reproduction_bud_fee_scale_percent{}, reproduction_organism_cap{};
|
||||||
|
std::int64_t reproduction_wildlife_cap{}; // Optional; 0 is the organism cap.
|
||||||
// Multicellular organisms.
|
// Multicellular organisms.
|
||||||
std::int64_t organism_load_per_mille{}, organism_emerge_members{}, organism_emerge_mass_fg{},
|
std::int64_t organism_load_per_mille{}, organism_emerge_members{}, organism_emerge_mass_fg{},
|
||||||
organism_emerge_reserve_pj{};
|
organism_emerge_reserve_pj{};
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
namespace evo::persistence {
|
namespace evo::persistence {
|
||||||
enum class AccountIdentityError : std::uint8_t {
|
enum class AccountIdentityError : std::uint8_t {
|
||||||
invalid, // Arguments refused.
|
invalid, // Arguments refused.
|
||||||
|
banned, // ADR-0182: the account is banned (schema 64); nothing changed.
|
||||||
store, // Other failure; nothing changed.
|
store, // Other failure; nothing changed.
|
||||||
unknown // May have executed: reconnect before relying on the serial.
|
unknown // May have executed: reconnect before relying on the serial.
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -118,6 +118,14 @@ cellular_checkpoint_trace_format(const CellularVersionBundle& b) noexcept {
|
|||||||
: server::cellular_batch_v2_format;
|
: server::cellular_batch_v2_format;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ADR-0182: a bundle-15 commit may carry admin commands in trace 5; every other format is
|
||||||
|
// exactly the bundle's.
|
||||||
|
[[nodiscard]] constexpr bool cellular_checkpoint_trace_admits(const CellularVersionBundle& b,
|
||||||
|
std::uint32_t format) noexcept {
|
||||||
|
return format == cellular_checkpoint_trace_format(b) ||
|
||||||
|
(format == server::cellular_batch_admin_format && b == cellular_v15_versions);
|
||||||
|
}
|
||||||
|
|
||||||
// Batch evidence bound by manifest v2 (ADR-0063); all zero at genesis.
|
// Batch evidence bound by manifest v2 (ADR-0063); all zero at genesis.
|
||||||
struct BatchDigests {
|
struct BatchDigests {
|
||||||
std::uint64_t trace_bytes{};
|
std::uint64_t trace_bytes{};
|
||||||
|
|||||||
@@ -30,8 +30,10 @@ class JsonValue {
|
|||||||
[[nodiscard]] const JsonValue* member(std::string_view name) const;
|
[[nodiscard]] const JsonValue* member(std::string_view name) const;
|
||||||
[[nodiscard]] const std::vector<JsonValue>* array() const;
|
[[nodiscard]] const std::vector<JsonValue>* array() const;
|
||||||
|
|
||||||
// Whole-document parse; nullopt for anything malformed or out of bounds.
|
// Whole-document parse; nullopt for anything malformed or out of bounds. `limit` bounds
|
||||||
[[nodiscard]] static std::optional<JsonValue> parse(std::string_view text);
|
// the text: access tokens and keys keep the default; a service's answer may allow more.
|
||||||
|
[[nodiscard]] static std::optional<JsonValue> parse(std::string_view text,
|
||||||
|
std::size_t limit = max_json_bytes);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
friend class JsonParser;
|
friend class JsonParser;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "evo/persistence/postgres.hpp"
|
#include "evo/persistence/postgres.hpp"
|
||||||
|
#include "evo/server/admin/https_client.hpp"
|
||||||
#include "evo/server/broker/access_token.hpp"
|
#include "evo/server/broker/access_token.hpp"
|
||||||
#include "evo/server/ops_http.hpp"
|
#include "evo/server/ops_http.hpp"
|
||||||
|
|
||||||
@@ -23,9 +24,49 @@
|
|||||||
// GET /config.json issuer, client id and world for the portal's sign-in
|
// GET /config.json issuer, client id and world for the portal's sign-in
|
||||||
// GET /api/me the signed-in admin's subject and email
|
// GET /api/me the signed-in admin's subject and email
|
||||||
// GET /api/accounts every account with session, lives, deaths and resets
|
// GET /api/accounts every account with session, lives, deaths and resets
|
||||||
// GET /api/accounts/<uuid> one account and its life requests
|
// GET /api/accounts/<uuid> one account, its life requests and ban history
|
||||||
|
// POST /api/accounts/<uuid>/ban?banned=1|0[&reason=R] bans (and logs out) or lifts a ban
|
||||||
|
// POST /api/accounts/<uuid>/logout ends the account's sessions now
|
||||||
|
// POST /api/accounts/<uuid>/end-life?request=N[&reason=R]
|
||||||
|
// ends a stranded published life (its reservation was
|
||||||
|
// never ended), refused while a cell in its region still
|
||||||
|
// holds the account (ADR-0182 section 18)
|
||||||
// GET /api/regions the world's regions, leases and heads
|
// GET /api/regions the world's regions, leases and heads
|
||||||
// GET /api/regions/<n>/view the region's live view (render_cellular_admin_view)
|
// GET /api/regions/<n>/view the region's live view (render_cellular_admin_view)
|
||||||
|
// GET /api/regions/<n>/session-window the current session window and its last changes
|
||||||
|
// POST /api/regions/<n>/session-window?minutes=M[&reason=R]
|
||||||
|
// opens or extends the window for M (1..240) minutes
|
||||||
|
// from now, or closes it (M = 0), as the signed-in admin
|
||||||
|
// (ADR-0087 amendment). No request body.
|
||||||
|
// GET /api/regions/<n>/commands the region's last admin commands and where they applied
|
||||||
|
// POST /api/regions/<n>/commands?kind=K[&count=N][&target=ID][&energy=PJ][&carbon=FG]
|
||||||
|
// [&nitrogen=FG][&phosphorus=FG][&other=FG][&reason=R]
|
||||||
|
// queues a command (remove_cell, grant_reserve,
|
||||||
|
// add_bubbles, add_pool, release_pool, spawn_wildlife)
|
||||||
|
// GET /api/regions/<n>/schedules the region's resource schedules (schema 65)
|
||||||
|
// POST /api/regions/<n>/schedules?kind=K&count=N&interval=S[&id=ID][&enabled=0|1]
|
||||||
|
// [&energy=PJ][&carbon=FG]...[&reason=R]
|
||||||
|
// creates (no id) or replaces a schedule repeating
|
||||||
|
// add_bubbles, release_pool or spawn_wildlife
|
||||||
|
// GET /api/tuning the world's rules-13 tuning revisions, the newest text,
|
||||||
|
// the baseline file regions opened with (schema 66) and
|
||||||
|
// the region tuning file they restart with (read only)
|
||||||
|
// GET /api/tuning/<revision> one revision's text
|
||||||
|
// POST /api/tuning[?check=1][&reason=R] the request body is a tuning text (the Git
|
||||||
|
// revamp file format): checked, then stored as a new
|
||||||
|
// revision that every region of the world adopts at its
|
||||||
|
// next tick (check=1: checked only, nothing stored)
|
||||||
|
// POST /api/tuning?base=baseline|REV[&check=1][&reason=R] the body holds only changed
|
||||||
|
// `key = value` lines, applied to the baseline file or to
|
||||||
|
// revision REV (which must be the newest: 409 stale_base),
|
||||||
|
// keeping its comments; then as above
|
||||||
|
// GET /api/deploy[?argo=1] ADR-0182 section 15: whether opening a region is
|
||||||
|
// configured, the region Git main serves, the next region
|
||||||
|
// and its seeded wildlife range, and the Argo Application's
|
||||||
|
// sync (argo=1: the Argo status only)
|
||||||
|
// POST /api/deploy/region?region=N[&reason=R] opens region N (the next one) in place of
|
||||||
|
// the served region: one Gitea commit to the region,
|
||||||
|
// broker and portal files, then a full Argo sync
|
||||||
namespace evo::server::admin {
|
namespace evo::server::admin {
|
||||||
struct AdminAsset {
|
struct AdminAsset {
|
||||||
std::string path; // "/index.html", ...; "/" serves "/index.html".
|
std::string path; // "/index.html", ...; "/" serves "/index.html".
|
||||||
@@ -33,12 +74,29 @@ struct AdminAsset {
|
|||||||
};
|
};
|
||||||
struct AdminConfig {
|
struct AdminConfig {
|
||||||
std::uint64_t world{};
|
std::uint64_t world{};
|
||||||
std::vector<std::uint64_t> view_regions; // Regions whose live view can be fetched.
|
// The world's regions: their live view can be fetched and they adopt tuning revisions.
|
||||||
|
std::vector<std::uint64_t> view_regions;
|
||||||
|
// The revamp tuning file the world's regions opened with (empty: unknown).
|
||||||
|
std::string baseline_tuning;
|
||||||
|
// The region tuning file (shape, movement, currents) they read at startup (empty: unknown).
|
||||||
|
std::string region_tuning;
|
||||||
std::string portal_config_json; // Served at /config.json.
|
std::string portal_config_json; // Served at /config.json.
|
||||||
std::string content_security_policy; // Sent with every portal file.
|
std::string content_security_policy; // Sent with every portal file.
|
||||||
std::chrono::milliseconds db_timeout{3000};
|
std::chrono::milliseconds db_timeout{3000};
|
||||||
std::chrono::milliseconds view_cache{750}; // A fetched view answers repeats this long.
|
std::chrono::milliseconds view_cache{750}; // A fetched view answers repeats this long.
|
||||||
};
|
};
|
||||||
|
// ADR-0182 section 15: where the admin API commits a region switch and what it syncs. The
|
||||||
|
// tokens come from mounted Secret files and are only ever sent in request headers.
|
||||||
|
struct AdminDeployConfig {
|
||||||
|
std::string gitea_base; // https://git.example[:port][/prefix]
|
||||||
|
std::string gitea_repository; // owner/name
|
||||||
|
std::string gitea_token;
|
||||||
|
std::string branch{"main"};
|
||||||
|
std::string argo_server; // host:port, https assumed
|
||||||
|
std::string argo_application;
|
||||||
|
std::string argo_token;
|
||||||
|
bool argo_verify{true};
|
||||||
|
};
|
||||||
using AdminConnect = std::function<std::unique_ptr<persistence::Postgres>()>;
|
using AdminConnect = std::function<std::unique_ptr<persistence::Postgres>()>;
|
||||||
// The region's /admin/view body, or nullopt when it cannot be reached or is not ready.
|
// The region's /admin/view body, or nullopt when it cannot be reached or is not ready.
|
||||||
using AdminRegionView = std::function<std::optional<std::string>(std::uint64_t region)>;
|
using AdminRegionView = std::function<std::optional<std::string>(std::uint64_t region)>;
|
||||||
@@ -50,13 +108,39 @@ class AdminApi {
|
|||||||
// `now_seconds` is wall time (token expiry); `now` paces the view cache.
|
// `now_seconds` is wall time (token expiry); `now` paces the view cache.
|
||||||
[[nodiscard]] OpsResponse handle(const ApiRequest& request, std::uint64_t now_seconds,
|
[[nodiscard]] OpsResponse handle(const ApiRequest& request, std::uint64_t now_seconds,
|
||||||
std::chrono::steady_clock::time_point now);
|
std::chrono::steady_clock::time_point now);
|
||||||
|
// Turns on /api/deploy with the given services and transport (tests pass a fake).
|
||||||
|
void enable_deploy(AdminDeployConfig config, HttpsTransport transport);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
[[nodiscard]] OpsResponse api(std::string_view path, const broker::AccessTokenClaims& admin,
|
[[nodiscard]] OpsResponse api(std::string_view method, std::string_view path,
|
||||||
|
std::string_view query, std::string_view body,
|
||||||
|
const broker::AccessTokenClaims& admin,
|
||||||
std::chrono::steady_clock::time_point now);
|
std::chrono::steady_clock::time_point now);
|
||||||
[[nodiscard]] OpsResponse accounts(std::optional<std::string_view> account);
|
[[nodiscard]] OpsResponse accounts(std::optional<std::string_view> account);
|
||||||
|
[[nodiscard]] OpsResponse account_action(std::string_view account, std::string_view action,
|
||||||
|
std::string_view query,
|
||||||
|
const broker::AccessTokenClaims& admin);
|
||||||
|
[[nodiscard]] OpsResponse end_life(std::string_view account, std::string_view query,
|
||||||
|
const broker::AccessTokenClaims& admin);
|
||||||
[[nodiscard]] OpsResponse regions();
|
[[nodiscard]] OpsResponse regions();
|
||||||
[[nodiscard]] OpsResponse view(std::uint64_t region, std::chrono::steady_clock::time_point now);
|
[[nodiscard]] OpsResponse view(std::uint64_t region, std::chrono::steady_clock::time_point now);
|
||||||
|
[[nodiscard]] OpsResponse window(std::uint64_t region);
|
||||||
|
[[nodiscard]] OpsResponse commands(std::uint64_t region);
|
||||||
|
[[nodiscard]] OpsResponse schedules(std::uint64_t region);
|
||||||
|
[[nodiscard]] OpsResponse set_schedule(std::uint64_t region, std::string_view query,
|
||||||
|
const broker::AccessTokenClaims& admin);
|
||||||
|
[[nodiscard]] OpsResponse enqueue(std::uint64_t region, std::string_view query,
|
||||||
|
const broker::AccessTokenClaims& admin);
|
||||||
|
[[nodiscard]] OpsResponse set_window(std::uint64_t region, std::string_view query,
|
||||||
|
const broker::AccessTokenClaims& admin);
|
||||||
|
[[nodiscard]] OpsResponse tuning();
|
||||||
|
[[nodiscard]] OpsResponse tuning_text(std::uint64_t revision);
|
||||||
|
[[nodiscard]] OpsResponse set_tuning(std::string_view query, std::string_view text,
|
||||||
|
const broker::AccessTokenClaims& admin);
|
||||||
|
[[nodiscard]] OpsResponse deploy_status(std::string_view query);
|
||||||
|
[[nodiscard]] OpsResponse open_region(std::string_view query,
|
||||||
|
const broker::AccessTokenClaims& admin);
|
||||||
|
[[nodiscard]] std::optional<std::uint64_t> next_region(std::uint64_t served);
|
||||||
[[nodiscard]] std::optional<persistence::PgRows> query(const std::string& sql,
|
[[nodiscard]] std::optional<persistence::PgRows> query(const std::string& sql,
|
||||||
std::vector<std::string> parameters);
|
std::vector<std::string> parameters);
|
||||||
|
|
||||||
@@ -65,6 +149,8 @@ class AdminApi {
|
|||||||
AdminConnect connect_;
|
AdminConnect connect_;
|
||||||
AdminRegionView view_;
|
AdminRegionView view_;
|
||||||
std::vector<AdminAsset> assets_;
|
std::vector<AdminAsset> assets_;
|
||||||
|
std::optional<AdminDeployConfig> deploy_;
|
||||||
|
HttpsTransport https_;
|
||||||
std::unique_ptr<persistence::Postgres> db_;
|
std::unique_ptr<persistence::Postgres> db_;
|
||||||
struct CachedView {
|
struct CachedView {
|
||||||
std::chrono::steady_clock::time_point at;
|
std::chrono::steady_clock::time_point at;
|
||||||
@@ -80,4 +166,8 @@ class AdminApi {
|
|||||||
std::size_t limit);
|
std::size_t limit);
|
||||||
// JSON string literal (quotes included) with control characters escaped.
|
// JSON string literal (quotes included) with control characters escaped.
|
||||||
[[nodiscard]] std::string json_string(std::string_view text);
|
[[nodiscard]] std::string json_string(std::string_view text);
|
||||||
|
// The decoded value of `name` in a URL query ("a=1&b=x%20y"), or nullopt when absent or
|
||||||
|
// malformed (bad escape, a decoded control character, over `limit` bytes).
|
||||||
|
[[nodiscard]] std::optional<std::string> query_value(std::string_view query, std::string_view name,
|
||||||
|
std::size_t limit = 200);
|
||||||
} // namespace evo::server::admin
|
} // namespace evo::server::admin
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
// ADR-0182 section 15: a bounded, blocking HTTPS/1.1 client for the admin API's two outbound
|
||||||
|
// services (Gitea and Argo CD). One request per connection (Connection: close); the system
|
||||||
|
// trust store and host name check unless `verify` is false. Credentials travel only in the
|
||||||
|
// request headers and are never logged.
|
||||||
|
namespace evo::server::admin {
|
||||||
|
struct HttpsRequest {
|
||||||
|
std::string host;
|
||||||
|
std::uint16_t port{443};
|
||||||
|
std::string method{"GET"};
|
||||||
|
std::string target{"/"}; // Path and query, already percent-encoded.
|
||||||
|
std::vector<std::pair<std::string, std::string>> headers;
|
||||||
|
std::string body;
|
||||||
|
bool verify{true};
|
||||||
|
std::chrono::milliseconds timeout{10'000};
|
||||||
|
std::size_t limit{std::size_t{4} << 20U}; // Largest body accepted.
|
||||||
|
};
|
||||||
|
struct HttpsResponse {
|
||||||
|
int status{};
|
||||||
|
std::string body;
|
||||||
|
};
|
||||||
|
// The transport the admin API uses; tests substitute a fake.
|
||||||
|
using HttpsTransport = std::function<std::optional<HttpsResponse>(const HttpsRequest&)>;
|
||||||
|
|
||||||
|
// Sends `request` over TLS: the answer, or nullopt on any connection, TLS, timeout, size or
|
||||||
|
// framing failure.
|
||||||
|
[[nodiscard]] std::optional<HttpsResponse> https_request(const HttpsRequest& request);
|
||||||
|
// An HTTP/1.1 response read to the end of the connection: the status and the body (by
|
||||||
|
// Content-Length, chunked, or to the end), or nullopt when malformed or over `limit`.
|
||||||
|
[[nodiscard]] std::optional<HttpsResponse> parse_http_response(std::string_view raw,
|
||||||
|
std::size_t limit);
|
||||||
|
// "https://host[:port][/...]" split into host, port and the path prefix (no trailing slash).
|
||||||
|
struct HttpsBase {
|
||||||
|
std::string host;
|
||||||
|
std::uint16_t port{443};
|
||||||
|
std::string prefix;
|
||||||
|
};
|
||||||
|
[[nodiscard]] std::optional<HttpsBase> parse_https_base(std::string_view url);
|
||||||
|
} // namespace evo::server::admin
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
// ADR-0182 section 15: the admin portal opens a fresh region in place of the one DEV serves.
|
||||||
|
// The change is four Git files edited in place: the region overlay's values (world, region,
|
||||||
|
// life routes, the opening's genesis commit and seeded wildlife range, both for the region
|
||||||
|
// Deployment and its provision Job), its kustomization header, and the region named by the
|
||||||
|
// grant broker's routes and the admin portal. Anything else is left exactly as it is; a file
|
||||||
|
// whose layout differs from the expected lines is refused rather than guessed at.
|
||||||
|
namespace evo::server::admin {
|
||||||
|
inline constexpr std::array<std::string_view, 4> region_switch_paths{
|
||||||
|
"deploy/kubernetes/region/dev/region-values.yaml",
|
||||||
|
"deploy/kubernetes/region/dev/kustomization.yaml",
|
||||||
|
"deploy/kubernetes/grant-broker-dev/deployment.yaml",
|
||||||
|
"deploy/kubernetes/admin-portal-dev/deployment.yaml",
|
||||||
|
};
|
||||||
|
// The four files' text, in region_switch_paths order.
|
||||||
|
using RegionSwitchFiles = std::array<std::string, 4>;
|
||||||
|
// What the files say DEV serves: the world and region, the opening's genesis commit (32
|
||||||
|
// lowercase hex digits) and the first seeded wildlife identity.
|
||||||
|
struct RegionLayout {
|
||||||
|
std::uint64_t world{}, region{};
|
||||||
|
std::string commit;
|
||||||
|
std::uint64_t wildlife_first{};
|
||||||
|
auto operator<=>(const RegionLayout&) const = default;
|
||||||
|
};
|
||||||
|
// The served layout, or the name of the line that is missing, repeated or inconsistent.
|
||||||
|
[[nodiscard]] std::expected<RegionLayout, std::string>
|
||||||
|
read_region_layout(const RegionSwitchFiles& files);
|
||||||
|
// The files serving `to` (same world) instead, with `note` (one line, no line breaks) recorded
|
||||||
|
// as a comment above the opening; or why the files or `to` cannot be switched.
|
||||||
|
[[nodiscard]] std::expected<RegionSwitchFiles, std::string>
|
||||||
|
switch_region(const RegionSwitchFiles& files, const RegionLayout& to, std::string_view note);
|
||||||
|
} // namespace evo::server::admin
|
||||||
@@ -13,6 +13,7 @@
|
|||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <expected>
|
#include <expected>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <span>
|
#include <span>
|
||||||
@@ -152,6 +153,11 @@ class CellularRegionHost {
|
|||||||
}
|
}
|
||||||
// Queued choices not carried by the commit in flight: the open batch binds these.
|
// Queued choices not carried by the commit in flight: the open batch binds these.
|
||||||
[[nodiscard]] std::vector<persistence::CellularMutationReservation> unbound_mutations() const;
|
[[nodiscard]] std::vector<persistence::CellularMutationReservation> unbound_mutations() const;
|
||||||
|
// ADR-0182: queued admin commands (rules 13) not carried by the commit in flight, oldest
|
||||||
|
// first, at most one tick's worth. Publication binds each to its queue row once.
|
||||||
|
[[nodiscard]] std::vector<CellularAdminCommand> unbound_admin_commands() const;
|
||||||
|
// ADR-0182: the tuning revisions this host fetched and verified, for adopt_tuning commands.
|
||||||
|
[[nodiscard]] CellularTuningResolver tuning_resolver() const;
|
||||||
[[nodiscard]] std::vector<FinalCellularMutation> take_finalized_mutations();
|
[[nodiscard]] std::vector<FinalCellularMutation> take_finalized_mutations();
|
||||||
// v5 requests allocate durably, then wait for the scheduler to include the exact
|
// v5 requests allocate durably, then wait for the scheduler to include the exact
|
||||||
// reservation in a profile-4 batch. Repeating the request is idempotent.
|
// reservation in a profile-4 batch. Repeating the request is idempotent.
|
||||||
@@ -207,6 +213,7 @@ class CellularRegionHost {
|
|||||||
void finalize_births(std::span<const CellularTickIntents::Birth> births);
|
void finalize_births(std::span<const CellularTickIntents::Birth> births);
|
||||||
void queue_birth(const CellularTickIntents::Birth& birth);
|
void queue_birth(const CellularTickIntents::Birth& birth);
|
||||||
void reload_mutations();
|
void reload_mutations();
|
||||||
|
void reload_admin_commands();
|
||||||
// ADR-0127: owned lives that died record their ending so the account may start again.
|
// ADR-0127: owned lives that died record their ending so the account may start again.
|
||||||
void note_endings(const CellularLives& before, const CellularLives& after,
|
void note_endings(const CellularLives& before, const CellularLives& after,
|
||||||
const persistence::Uuid& commit);
|
const persistence::Uuid& commit);
|
||||||
@@ -285,6 +292,9 @@ class CellularRegionHost {
|
|||||||
std::vector<CellularTickIntents::Birth> queued_births_;
|
std::vector<CellularTickIntents::Birth> queued_births_;
|
||||||
std::vector<CellularBirthRefusal> pending_birth_refusals_;
|
std::vector<CellularBirthRefusal> pending_birth_refusals_;
|
||||||
std::vector<persistence::CellularMutationReservation> queued_mutations_;
|
std::vector<persistence::CellularMutationReservation> queued_mutations_;
|
||||||
|
std::vector<CellularAdminCommand> queued_admin_;
|
||||||
|
std::map<std::uint64_t, CellularRevampRules> verified_tuning_; // By revision.
|
||||||
|
std::chrono::steady_clock::time_point next_admin_reload_{};
|
||||||
// A reservation may exist that the queue does not show; reload before publishing.
|
// A reservation may exist that the queue does not show; reload before publishing.
|
||||||
bool mutations_uncertain_{};
|
bool mutations_uncertain_{};
|
||||||
std::vector<FinalCellularMutation> finalized_mutations_;
|
std::vector<FinalCellularMutation> finalized_mutations_;
|
||||||
|
|||||||
@@ -47,6 +47,13 @@ prepare_cellular_session_tick(
|
|||||||
std::span<const network::CarriedAction> actions,
|
std::span<const network::CarriedAction> actions,
|
||||||
std::span<const persistence::CellularMutationReservation> mutations = {});
|
std::span<const persistence::CellularMutationReservation> mutations = {});
|
||||||
|
|
||||||
|
// A tick takes one action per account. Keeps each account's discrete action (engulf, bud,
|
||||||
|
// become, emerge), else its newest (highest id), in `actions`, and returns the others, which
|
||||||
|
// the caller refuses. A client naming a tick it already sent a movement for then loses only
|
||||||
|
// that movement, not every player's actions on the tick.
|
||||||
|
[[nodiscard]] std::vector<network::CarriedAction>
|
||||||
|
keep_one_action_per_account(std::vector<network::CarriedAction>& actions);
|
||||||
|
|
||||||
// Builds one bounded publication from the last durable head. Its working copy is private;
|
// Builds one bounded publication from the last durable head. Its working copy is private;
|
||||||
// only the host may publish, and callers must discard it after uncertainty until the host
|
// only the host may publish, and callers must discard it after uncertainty until the host
|
||||||
// resolves that exact prepared batch.
|
// resolves that exact prepared batch.
|
||||||
@@ -58,7 +65,8 @@ class CellularSessionBatchBuilder {
|
|||||||
append(std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
append(std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||||
std::span<const network::CarriedAction> actions,
|
std::span<const network::CarriedAction> actions,
|
||||||
std::span<const CellularTickIntents::Birth> births = {},
|
std::span<const CellularTickIntents::Birth> births = {},
|
||||||
std::span<const persistence::CellularMutationReservation> mutations = {});
|
std::span<const persistence::CellularMutationReservation> mutations = {},
|
||||||
|
std::span<const CellularAdminCommand> admin = {});
|
||||||
// Scheduler path: expected placement/funding/existing-life refusals are reported
|
// Scheduler path: expected placement/funding/existing-life refusals are reported
|
||||||
// separately, so they cannot prevent other births or the ordinary tick. Unexpected
|
// separately, so they cannot prevent other births or the ordinary tick. Unexpected
|
||||||
// failures retain append's all-or-nothing behavior. Persist reports only after publish.
|
// failures retain append's all-or-nothing behavior. Persist reports only after publish.
|
||||||
@@ -66,13 +74,22 @@ class CellularSessionBatchBuilder {
|
|||||||
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||||
std::span<const network::CarriedAction> actions,
|
std::span<const network::CarriedAction> actions,
|
||||||
std::span<const CellularTickIntents::Birth> births = {},
|
std::span<const CellularTickIntents::Birth> births = {},
|
||||||
std::span<const persistence::CellularMutationReservation> mutations = {});
|
std::span<const persistence::CellularMutationReservation> mutations = {},
|
||||||
|
std::span<const CellularAdminCommand> admin = {});
|
||||||
[[nodiscard]] std::span<const CellularBirthRefusal> refused_births() const noexcept {
|
[[nodiscard]] std::span<const CellularBirthRefusal> refused_births() const noexcept {
|
||||||
return refused_births_;
|
return refused_births_;
|
||||||
}
|
}
|
||||||
[[nodiscard]] const CellularBatch& batch() const noexcept {
|
[[nodiscard]] const CellularBatch& batch() const noexcept {
|
||||||
return batch_;
|
return batch_;
|
||||||
}
|
}
|
||||||
|
// ADR-0182: names the rules of adopt_tuning commands (the host's verified revisions).
|
||||||
|
void set_tuning_resolver(CellularTuningResolver tuning) {
|
||||||
|
tuning_ = std::move(tuning);
|
||||||
|
}
|
||||||
|
// ADR-0182: each admin command appended so far and whether it applied, in trace order.
|
||||||
|
[[nodiscard]] std::span<const CellularAdminResult> admin_results() const noexcept {
|
||||||
|
return admin_results_;
|
||||||
|
}
|
||||||
[[nodiscard]] std::span<const CellularActionRecord> actions() const noexcept {
|
[[nodiscard]] std::span<const CellularActionRecord> actions() const noexcept {
|
||||||
return actions_;
|
return actions_;
|
||||||
}
|
}
|
||||||
@@ -106,7 +123,7 @@ class CellularSessionBatchBuilder {
|
|||||||
std::span<const network::CarriedAction> actions,
|
std::span<const network::CarriedAction> actions,
|
||||||
std::span<const CellularTickIntents::Birth> births,
|
std::span<const CellularTickIntents::Birth> births,
|
||||||
std::span<const persistence::CellularMutationReservation> mutations,
|
std::span<const persistence::CellularMutationReservation> mutations,
|
||||||
bool allow_refusals);
|
std::span<const CellularAdminCommand> admin, bool allow_refusals);
|
||||||
explicit CellularSessionBatchBuilder(std::unique_ptr<CellularLives> working)
|
explicit CellularSessionBatchBuilder(std::unique_ptr<CellularLives> working)
|
||||||
: working_{std::move(working)} {}
|
: working_{std::move(working)} {}
|
||||||
std::unique_ptr<CellularLives> working_;
|
std::unique_ptr<CellularLives> working_;
|
||||||
@@ -114,6 +131,8 @@ class CellularSessionBatchBuilder {
|
|||||||
std::vector<CellularActionRecord> actions_;
|
std::vector<CellularActionRecord> actions_;
|
||||||
std::vector<CellularMutationActionRecord> mutation_actions_;
|
std::vector<CellularMutationActionRecord> mutation_actions_;
|
||||||
std::vector<CellularBirthRefusal> refused_births_;
|
std::vector<CellularBirthRefusal> refused_births_;
|
||||||
|
std::vector<CellularAdminResult> admin_results_;
|
||||||
|
CellularTuningResolver tuning_;
|
||||||
std::optional<CellularLivesError> last_lives_error_;
|
std::optional<CellularLivesError> last_lives_error_;
|
||||||
};
|
};
|
||||||
} // namespace evo::server
|
} // namespace evo::server
|
||||||
|
|||||||
@@ -5,23 +5,35 @@
|
|||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
// ADR-0182 read-only region view for the admin portal: every cell, pool and bubble of a
|
// ADR-0182 read-only region view for the admin portal: every cell, pool and bubble of a
|
||||||
// cellular owner as compact JSON. It reads the committed in-memory state and changes nothing;
|
// cellular owner as compact JSON. It reads the committed in-memory state and changes nothing;
|
||||||
// it is not a simulation output, a checkpoint or a client protocol.
|
// it is not a simulation output, a checkpoint or a client protocol.
|
||||||
//
|
//
|
||||||
// {"world":W,"region":R,"tick":T,"rules":N,"area":[w,h],
|
// {"world":W,"region":R,"tick":T,"rules":N,["rules_sha256":"hex",]"area":[w,h],
|
||||||
// "spent":[e,c,n,p,o],"cells_total":N,"deposits_total":N,
|
// "spent":[e,c,n,p,o],"heat":pj,
|
||||||
|
// ["drip":[interval_ticks,bubble_pj,bubble_fg,heat_recycle_per_mille,absorb],]
|
||||||
|
// "cells_total":N,"deposits_total":N,
|
||||||
|
// "counts":[players,wildlife,patches,pools,bubbles],
|
||||||
|
// "totals":{"reserve":[e,c,n,p,o],"body":[...],"patches":[...],"pools":[...],"bubbles":[...]},
|
||||||
// "cells":[["life","organism","account",x,y,extent,flags,members,
|
// "cells":[["life","organism","account",x,y,extent,flags,members,
|
||||||
// reserve_e,reserve_c,reserve_n,reserve_p,reserve_o,body_mass],...],
|
// reserve_e,reserve_c,reserve_n,reserve_p,reserve_o,body_mass,"root"],...],
|
||||||
// "deposits":[[id,kind,x,y,radius,e,c,n,p,o],...]}
|
// "deposits":[[id,kind,x,y,radius,e,c,n,p,o],...]}
|
||||||
//
|
//
|
||||||
// Cell positions are the lower-left corner of the square footprint and deposits their centre,
|
// Cell positions are the lower-left corner of the square footprint and deposits their centre,
|
||||||
// in micrometres. Life and organism ids are decimal strings (bud ids exceed 2^53); `account`
|
// in micrometres. Life and organism ids are decimal strings (bud ids exceed 2^53); `account`
|
||||||
// is the lowercase UUID, empty for wildlife. Flags: 1 wildlife, 2 the account's session is
|
// is the lowercase UUID, empty for wildlife; `root` the lineage root (the founder whose life
|
||||||
// connected, 4 lingering, 8 suspended. Deposit kind: 0 patch, 1 pool, 2 bubble. Energy in
|
// request a lineage descends from, cellular_lineage_root). Flags: 1 wildlife, 2 the account's
|
||||||
// pJ, matter in fg. Cells and deposits beyond the limits are left out (by ascending life id
|
// session is connected, 4 lingering, 8 suspended. Deposit kind: 0 patch, 1 pool, 2 bubble. Energy
|
||||||
// and deposit id); the totals still count them.
|
// in pJ, matter in fg. Cells and deposits beyond the limits are left out (by ascending life id and
|
||||||
|
// deposit id); the totals still count them. `rules_sha256` is given by the caller (the SHA-256
|
||||||
|
// of encode_cellular_revamp_rules, which tuning revisions are adopted by) and left out when empty.
|
||||||
|
// `heat` is the energy the region's cells have used and not yet recycled (CellularLives::heat).
|
||||||
|
// `drip` is the rules-13 spent-pool drip (cellular_drip_spent) and its energy cycle (ADR-0182
|
||||||
|
// section 14), left out before rules 13.
|
||||||
|
// `counts` and `totals` cover every life and deposit, whatever the limits: the region's stock
|
||||||
|
// is the totals plus `spent`.
|
||||||
namespace evo::server {
|
namespace evo::server {
|
||||||
struct CellularAdminViewLimits {
|
struct CellularAdminViewLimits {
|
||||||
std::size_t cells{4096}, deposits{16384};
|
std::size_t cells{4096}, deposits{16384};
|
||||||
@@ -30,7 +42,8 @@ struct CellularAdminViewLimits {
|
|||||||
using CellularAdminOnline = std::function<bool(const LifeAccount&)>;
|
using CellularAdminOnline = std::function<bool(const LifeAccount&)>;
|
||||||
[[nodiscard]] std::string render_cellular_admin_view(const CellularLives& state,
|
[[nodiscard]] std::string render_cellular_admin_view(const CellularLives& state,
|
||||||
const CellularAdminOnline& online,
|
const CellularAdminOnline& online,
|
||||||
CellularAdminViewLimits limits = {});
|
CellularAdminViewLimits limits = {},
|
||||||
|
std::string_view rules_sha256 = {});
|
||||||
// Lowercase 8-4-4-4-12 text of a 16-byte account.
|
// Lowercase 8-4-4-4-12 text of a 16-byte account.
|
||||||
[[nodiscard]] std::string cellular_account_text(const LifeAccount& account);
|
[[nodiscard]] std::string cellular_account_text(const LifeAccount& account);
|
||||||
} // namespace evo::server
|
} // namespace evo::server
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ struct CellularBatchHeader {
|
|||||||
inline constexpr std::uint32_t cellular_batch_format = 3;
|
inline constexpr std::uint32_t cellular_batch_format = 3;
|
||||||
// ADR-0166: explicit opt-in for owner format 8/rules 10; the default remains 3.
|
// ADR-0166: explicit opt-in for owner format 8/rules 10; the default remains 3.
|
||||||
inline constexpr std::uint32_t cellular_batch_inheritance_format = 4;
|
inline constexpr std::uint32_t cellular_batch_inheritance_format = 4;
|
||||||
|
// ADR-0182: trace 4 plus admin commands, for rules 13 only. A batch without commands stays 4.
|
||||||
|
inline constexpr std::uint32_t cellular_batch_admin_format = 5;
|
||||||
inline constexpr std::uint32_t cellular_batch_v2_format = 2;
|
inline constexpr std::uint32_t cellular_batch_v2_format = 2;
|
||||||
inline constexpr std::uint32_t cellular_batch_legacy_format = 1;
|
inline constexpr std::uint32_t cellular_batch_legacy_format = 1;
|
||||||
struct CellularTickIntents {
|
struct CellularTickIntents {
|
||||||
@@ -38,6 +40,8 @@ struct CellularTickIntents {
|
|||||||
// Choices accepted against the preceding checkpoint and scheduled for this tick.
|
// Choices accepted against the preceding checkpoint and scheduled for this tick.
|
||||||
// The successor identity is durably reserved before the batch is replayed.
|
// The successor identity is durably reserved before the batch is replayed.
|
||||||
std::vector<CellularMutationSelection> mutations;
|
std::vector<CellularMutationSelection> mutations;
|
||||||
|
// Format 5 (ADR-0182): operator commands applied after the births, by ascending id.
|
||||||
|
std::vector<CellularAdminCommand> admin{};
|
||||||
friend bool operator==(const CellularTickIntents&, const CellularTickIntents&) = default;
|
friend bool operator==(const CellularTickIntents&, const CellularTickIntents&) = default;
|
||||||
};
|
};
|
||||||
// Transient scheduler report, not part of the replay trace. A refused birth changes
|
// Transient scheduler report, not part of the replay trace. A refused birth changes
|
||||||
@@ -81,13 +85,21 @@ inline constexpr std::size_t cellular_batch_tick_header_bytes = 16;
|
|||||||
inline constexpr std::size_t cellular_batch_intent_bytes = 24;
|
inline constexpr std::size_t cellular_batch_intent_bytes = 24;
|
||||||
inline constexpr std::size_t cellular_batch_birth_bytes = 40;
|
inline constexpr std::size_t cellular_batch_birth_bytes = 40;
|
||||||
inline constexpr std::size_t cellular_batch_mutation_bytes = 40;
|
inline constexpr std::size_t cellular_batch_mutation_bytes = 40;
|
||||||
|
// Format 5: id u64, kind u16, count u16, zero u32, target u64, energy and four matter u64.
|
||||||
|
inline constexpr std::size_t cellular_batch_admin_bytes = 64;
|
||||||
|
inline constexpr std::size_t max_cellular_tick_admin_commands = 16;
|
||||||
inline constexpr std::size_t max_cellular_batch_ticks = 64;
|
inline constexpr std::size_t max_cellular_batch_ticks = 64;
|
||||||
|
// The largest trace of a batch whose ticks hold at most `lives` lives.
|
||||||
|
[[nodiscard]] constexpr std::size_t cellular_batch_bytes_for(std::size_t lives) noexcept {
|
||||||
|
return cellular_batch_header_bytes +
|
||||||
|
max_cellular_batch_ticks *
|
||||||
|
(cellular_batch_tick_header_bytes +
|
||||||
|
lives * (cellular_batch_intent_bytes + cellular_batch_birth_bytes +
|
||||||
|
cellular_batch_mutation_bytes) +
|
||||||
|
max_cellular_tick_admin_commands * cellular_batch_admin_bytes);
|
||||||
|
}
|
||||||
inline constexpr std::size_t max_cellular_batch_bytes =
|
inline constexpr std::size_t max_cellular_batch_bytes =
|
||||||
cellular_batch_header_bytes +
|
cellular_batch_bytes_for(biology::max_cellular_tick_lives);
|
||||||
max_cellular_batch_ticks * (cellular_batch_tick_header_bytes +
|
|
||||||
biology::max_cellular_tick_lives *
|
|
||||||
(cellular_batch_intent_bytes + cellular_batch_birth_bytes +
|
|
||||||
cellular_batch_mutation_bytes));
|
|
||||||
enum class CellularBatchError : std::uint8_t { format, version, scope, state };
|
enum class CellularBatchError : std::uint8_t { format, version, scope, state };
|
||||||
inline constexpr std::size_t cellular_action_record_bytes = 48;
|
inline constexpr std::size_t cellular_action_record_bytes = 48;
|
||||||
inline constexpr std::size_t max_cellular_action_records = 1'024;
|
inline constexpr std::size_t max_cellular_action_records = 1'024;
|
||||||
@@ -118,6 +130,19 @@ struct CellularMutationOutcome {
|
|||||||
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
||||||
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||||
std::vector<CellularMutationOutcome>& mutation_outcomes);
|
std::vector<CellularMutationOutcome>& mutation_outcomes);
|
||||||
|
// ADR-0182: also reports every admin command's result in trace order; `tuning` names the
|
||||||
|
// rules an adopt_tuning command adopts (a batch holds at most one).
|
||||||
|
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
||||||
|
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||||
|
std::vector<CellularMutationOutcome>& mutation_outcomes,
|
||||||
|
std::vector<CellularAdminResult>& admin_results,
|
||||||
|
const CellularTuningResolver& tuning = {});
|
||||||
|
// ADR-0182: the rules a batch's single adopt_tuning names are its successor's (nothing else
|
||||||
|
// changes them), so publication and recovery resolve from the successor once they have
|
||||||
|
// checked the digest: this returns the successor's rules for `check(encoding, digest)`.
|
||||||
|
[[nodiscard]] CellularTuningResolver cellular_successor_tuning(
|
||||||
|
const CellularLives& successor,
|
||||||
|
std::function<bool(std::span<const std::uint8_t>, const std::array<std::uint8_t, 32>&)> check);
|
||||||
// The canonical 34-byte reserved choice (schema v29): tick, life, event and offer tick as
|
// The canonical 34-byte reserved choice (schema v29): tick, life, event and offer tick as
|
||||||
// u64 and the operator as u16, little-endian.
|
// u64 and the operator as u16, little-endian.
|
||||||
inline constexpr std::size_t cellular_mutation_input_bytes = 34;
|
inline constexpr std::size_t cellular_mutation_input_bytes = 34;
|
||||||
|
|||||||
@@ -7,10 +7,12 @@
|
|||||||
#include "evo/server/lifecycle/cellular_revamp.hpp"
|
#include "evo/server/lifecycle/cellular_revamp.hpp"
|
||||||
#include "evo/server/lifecycle/primitive_lives.hpp"
|
#include "evo/server/lifecycle/primitive_lives.hpp"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
#include <compare>
|
#include <compare>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <expected>
|
#include <expected>
|
||||||
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <span>
|
#include <span>
|
||||||
@@ -179,6 +181,53 @@ struct CellularLifeIntent {
|
|||||||
biology::CellularStepIntent intent{};
|
biology::CellularStepIntent intent{};
|
||||||
auto operator<=>(const CellularLifeIntent&) const = default;
|
auto operator<=>(const CellularLifeIntent&) const = default;
|
||||||
};
|
};
|
||||||
|
// ADR-0182 admin commands: operator inputs recorded in the trace (batch format 5) and applied
|
||||||
|
// after a tick's births, in ascending id. Imports enter the boundary ledger as a named game
|
||||||
|
// source; removed matter goes to the spent pool. A command whose target is gone or that does
|
||||||
|
// not fit is refused and changes nothing; the others still apply.
|
||||||
|
enum class CellularAdminKind : std::uint8_t { // A u16 in the trace.
|
||||||
|
remove_cell = 1, // `target` life: body and reserve go to the spent pool.
|
||||||
|
grant_reserve = 2, // `amount` imported into the `target` life's reserve.
|
||||||
|
add_bubbles = 3, // `amount` imported as `count` (1..256) bubbles sharing it.
|
||||||
|
add_pool = 4, // `amount` imported into the spent pool.
|
||||||
|
release_pool = 5, // Up to `amount` moved from the spent pool into `count` bubbles.
|
||||||
|
spawn_wildlife = 6, // `count` (1..256) random-genome roots, identities `target`.., imported.
|
||||||
|
// ADR-0182 tuning amendment: the region's rules-13 rules become tuning revision `target`,
|
||||||
|
// whose canonical rules encoding (encode_cellular_revamp_rules) has the SHA-256 held in the
|
||||||
|
// energy, carbon, nitrogen and phosphorus amounts (little-endian words; `other` zero).
|
||||||
|
adopt_tuning = 7,
|
||||||
|
// Schema 67: up to `amount` (per channel, never more than it holds) moved from the
|
||||||
|
// `target` life's reserve to the spent pool; and every wildlife life removed as by 1.
|
||||||
|
take_reserve = 8,
|
||||||
|
remove_wildlife = 9,
|
||||||
|
};
|
||||||
|
struct CellularAdminCommand {
|
||||||
|
std::uint64_t id{}; // The durable queue id.
|
||||||
|
CellularAdminKind kind{};
|
||||||
|
std::uint16_t count{};
|
||||||
|
std::uint64_t target{};
|
||||||
|
accounting::Inventory amount{};
|
||||||
|
friend bool operator==(const CellularAdminCommand&, const CellularAdminCommand&) = default;
|
||||||
|
};
|
||||||
|
// Shape only (kind, counts, amounts, identity range); whether it applies is decided at its tick.
|
||||||
|
[[nodiscard]] bool cellular_admin_command_valid(const CellularAdminCommand& command) noexcept;
|
||||||
|
// The 32-byte digest an adopt_tuning command carries, and a command carrying one.
|
||||||
|
[[nodiscard]] std::array<std::uint8_t, 32>
|
||||||
|
cellular_admin_digest(const CellularAdminCommand& command) noexcept;
|
||||||
|
[[nodiscard]] CellularAdminCommand
|
||||||
|
cellular_adopt_tuning_command(std::uint64_t id, std::uint64_t revision,
|
||||||
|
const std::array<std::uint8_t, 32>& digest) noexcept;
|
||||||
|
// The rules an adopt_tuning command names, from whoever can check its digest (the region host
|
||||||
|
// from the revision text, publication and recovery from the successor state). Nullopt: unknown.
|
||||||
|
using CellularTuningResolver = std::function<std::optional<CellularRevampRules>(
|
||||||
|
std::uint64_t revision, const std::array<std::uint8_t, 32>& digest)>;
|
||||||
|
// Canonical bytes of the rules-13 rules (as the owner snapshot stores them, without the pool).
|
||||||
|
[[nodiscard]] std::vector<std::uint8_t> encode_cellular_revamp_rules(const CellularRevampRules& r);
|
||||||
|
struct CellularAdminResult {
|
||||||
|
std::uint64_t id{};
|
||||||
|
bool applied{};
|
||||||
|
friend bool operator==(const CellularAdminResult&, const CellularAdminResult&) = default;
|
||||||
|
};
|
||||||
struct CellularMutationSelection {
|
struct CellularMutationSelection {
|
||||||
std::uint64_t life_id{}, event_index{}, offer_tick{}, successor_id{};
|
std::uint64_t life_id{}, event_index{}, offer_tick{}, successor_id{};
|
||||||
std::uint16_t operator_id{};
|
std::uint16_t operator_id{};
|
||||||
@@ -412,6 +461,12 @@ class CellularLives {
|
|||||||
[[nodiscard]] std::expected<CellularTickExecution, CellularLivesError>
|
[[nodiscard]] std::expected<CellularTickExecution, CellularLivesError>
|
||||||
advance_tick_with_mutations(std::span<const CellularLifeIntent> intents,
|
advance_tick_with_mutations(std::span<const CellularLifeIntent> intents,
|
||||||
std::span<const CellularMutationSelection> selections);
|
std::span<const CellularMutationSelection> selections);
|
||||||
|
// ADR-0182: a detached candidate after `commands` (valid, strictly ascending ids) at the
|
||||||
|
// current tick, after its births. Rules 13 only. `results` reports each command, in order.
|
||||||
|
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
||||||
|
admin_candidate(std::span<const CellularAdminCommand> commands,
|
||||||
|
std::vector<CellularAdminResult>* results = nullptr,
|
||||||
|
const CellularTuningResolver& tuning = {}) const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
friend class CellularMigration;
|
friend class CellularMigration;
|
||||||
@@ -432,6 +487,11 @@ class CellularLives {
|
|||||||
migration_replacement(std::vector<CellularOwnedLife>, const biology::LineageArchive&,
|
migration_replacement(std::vector<CellularOwnedLife>, const biology::LineageArchive&,
|
||||||
CellularBoundaryLedger) const;
|
CellularBoundaryLedger) const;
|
||||||
struct State;
|
struct State;
|
||||||
|
// ADR-0180/0182: one randomized founder root `id` placed at a seeded free spot, funded
|
||||||
|
// from the nursery, or (with `imported`) by a game-source import added to it.
|
||||||
|
[[nodiscard]] static std::optional<CellularLivesError>
|
||||||
|
seed_wildlife_root(State& next, std::uint64_t world, std::uint64_t region, std::uint64_t tick,
|
||||||
|
std::uint64_t id, accounting::Inventory* imported);
|
||||||
explicit CellularLives(std::unique_ptr<State> state);
|
explicit CellularLives(std::unique_ptr<State> state);
|
||||||
std::unique_ptr<State> state_;
|
std::unique_ptr<State> state_;
|
||||||
std::vector<CellularLifeTickFeedback> last_tick_feedback_;
|
std::vector<CellularLifeTickFeedback> last_tick_feedback_;
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ struct CellularMigrationTrace {
|
|||||||
};
|
};
|
||||||
inline constexpr std::size_t migration_trace_header_bytes = 256;
|
inline constexpr std::size_t migration_trace_header_bytes = 256;
|
||||||
inline constexpr std::size_t max_migration_trace_bytes =
|
inline constexpr std::size_t max_migration_trace_bytes =
|
||||||
migration_trace_header_bytes + 8 * biology::max_cellular_tick_lives + 8;
|
migration_trace_header_bytes + 8 * biology::max_cellular_frozen_lives + 8;
|
||||||
struct RecordedCellularMigration {
|
struct RecordedCellularMigration {
|
||||||
CellularMigrationTrace trace;
|
CellularMigrationTrace trace;
|
||||||
CellularMigrationExecution execution;
|
CellularMigrationExecution execution;
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ struct CellularTierPolicy {
|
|||||||
};
|
};
|
||||||
inline constexpr std::size_t cellular_population_header_bytes = 80;
|
inline constexpr std::size_t cellular_population_header_bytes = 80;
|
||||||
inline constexpr std::uint32_t cellular_population_inheritance_format = 3;
|
inline constexpr std::uint32_t cellular_population_inheritance_format = 3;
|
||||||
inline constexpr std::size_t max_cellular_population_bytes = cellular_population_header_bytes +
|
inline constexpr std::size_t max_cellular_population_bytes =
|
||||||
16 * biology::max_cellular_tick_lives +
|
cellular_population_header_bytes + 16 * biology::max_cellular_frozen_lives +
|
||||||
max_cellular_lives_bytes + 8;
|
max_cellular_lives_bytes + 8;
|
||||||
|
|
||||||
class CellularPopulation {
|
class CellularPopulation {
|
||||||
|
|||||||
@@ -26,8 +26,8 @@ struct CellularPopulationBatch {
|
|||||||
};
|
};
|
||||||
inline constexpr std::size_t population_batch_header_bytes = 136;
|
inline constexpr std::size_t population_batch_header_bytes = 136;
|
||||||
inline constexpr std::size_t max_population_batch_bytes =
|
inline constexpr std::size_t max_population_batch_bytes =
|
||||||
population_batch_header_bytes + max_cellular_batch_bytes +
|
population_batch_header_bytes + cellular_batch_bytes_for(biology::max_cellular_frozen_lives) +
|
||||||
max_cellular_batch_ticks * (16 + 16 * biology::max_cellular_tick_lives);
|
max_cellular_batch_ticks * (16 + 16 * biology::max_cellular_frozen_lives);
|
||||||
struct CellularPopulationExecution {
|
struct CellularPopulationExecution {
|
||||||
CellularPopulationBatch batch;
|
CellularPopulationBatch batch;
|
||||||
std::unique_ptr<CellularPopulation> state;
|
std::unique_ptr<CellularPopulation> state;
|
||||||
|
|||||||
@@ -28,6 +28,12 @@ struct CellularRevampRules {
|
|||||||
// bubble per non-empty channel of at most these amounts, at seeded random spots.
|
// bubble per non-empty channel of at most these amounts, at seeded random spots.
|
||||||
std::uint32_t drip_interval_ticks{};
|
std::uint32_t drip_interval_ticks{};
|
||||||
std::uint64_t drip_bubble_pj{}, drip_bubble_fg{};
|
std::uint64_t drip_bubble_pj{}, drip_bubble_fg{};
|
||||||
|
// ADR-0182 section 14 (0 and false keep the historical law): the share of the region's
|
||||||
|
// heat, per mille, moved to the spent pool at the end of every tick before the drip, so
|
||||||
|
// energy cycles back like matter; and a drip at the deposit limit joins an existing bubble
|
||||||
|
// (the first at or after its spot) instead of waiting.
|
||||||
|
std::uint32_t heat_recycle_per_thousand{};
|
||||||
|
bool drip_absorb{};
|
||||||
// Share of reserve matter carried as load, per mille: it slows thrust and turning and makes
|
// Share of reserve matter carried as load, per mille: it slows thrust and turning and makes
|
||||||
// thrust costlier, in proportion to the body's mass. Upkeep stays on the body.
|
// thrust costlier, in proportion to the body's mass. Upkeep stays on the body.
|
||||||
std::uint32_t reserve_load_per_thousand{};
|
std::uint32_t reserve_load_per_thousand{};
|
||||||
@@ -45,6 +51,9 @@ struct CellularRevampRules {
|
|||||||
accounting::Inventory bud_fee{};
|
accounting::Inventory bud_fee{};
|
||||||
std::uint32_t bud_fee_scale_percent{};
|
std::uint32_t bud_fee_scale_percent{};
|
||||||
std::uint32_t organism_cap{256};
|
std::uint32_t organism_cap{256};
|
||||||
|
// Wildlife buds are refused at this many lives (0: the organism cap), leaving the slots
|
||||||
|
// above it to players; spawning still answers to the organism cap. Below 32,768.
|
||||||
|
std::uint32_t wildlife_cap{};
|
||||||
// Multicellular organisms (reproduction plan section 6): the share of the extra members'
|
// Multicellular organisms (reproduction plan section 6): the share of the extra members'
|
||||||
// mass carried as load on one cell's thrust, and the emergence threshold.
|
// mass carried as load on one cell's thrust, and the emergence threshold.
|
||||||
std::uint32_t organism_load_per_thousand{500};
|
std::uint32_t organism_load_per_thousand{500};
|
||||||
@@ -114,13 +123,21 @@ cellular_mutation_cost(const biology::CellularMutationTuning& tuning) noexcept;
|
|||||||
// The spent pool's drip for the tick ending at `tick`: on every `drip_interval_ticks`-th tick,
|
// The spent pool's drip for the tick ending at `tick`: on every `drip_interval_ticks`-th tick,
|
||||||
// one bubble per non-empty channel of at most the declared size, taken from `spent`, at a
|
// one bubble per non-empty channel of at most the declared size, taken from `spent`, at a
|
||||||
// seeded random spot (nudged east past taken addresses) with the next deposit id and `source`.
|
// seeded random spot (nudged east past taken addresses) with the next deposit id and `source`.
|
||||||
// A habitat at its deposit limit keeps the rest waiting. False only on identity overflow, with
|
// A habitat at its deposit limit keeps the rest waiting, or with `drip_absorb` adds it to the
|
||||||
// `config` and `spent` then unusable.
|
// first bubble at or after that spot in address order (wrapping). False only on identity
|
||||||
|
// overflow, with `config` and `spent` then unusable.
|
||||||
[[nodiscard]] bool cellular_drip_spent(biology::CellularHabitatConfig& config,
|
[[nodiscard]] bool cellular_drip_spent(biology::CellularHabitatConfig& config,
|
||||||
accounting::Inventory& spent,
|
accounting::Inventory& spent,
|
||||||
const CellularRevampRules& rules, std::uint64_t world,
|
const CellularRevampRules& rules, std::uint64_t world,
|
||||||
std::uint64_t region, std::uint64_t tick,
|
std::uint64_t region, std::uint64_t tick,
|
||||||
std::uint64_t source);
|
std::uint64_t source);
|
||||||
|
// ADR-0182 admin bubbles: `amount` as `count` bubbles, each channel split evenly (the remainder
|
||||||
|
// in the last), at seeded random spots nudged east past taken addresses, with the next deposit
|
||||||
|
// ids and `source`. False, with `config` unchanged, when the habitat cannot take them all.
|
||||||
|
[[nodiscard]] bool cellular_scatter_bubbles(biology::CellularHabitatConfig& config,
|
||||||
|
const accounting::Inventory& amount,
|
||||||
|
std::uint16_t count, std::uint64_t seed,
|
||||||
|
std::uint64_t source);
|
||||||
// A body's handling carrying reserve matter: thrust, reverse thrust and turning scale by
|
// A body's handling carrying reserve matter: thrust, reverse thrust and turning scale by
|
||||||
// body / (body + load), full-output costs by (body + load) / body, where load is the declared
|
// body / (body + load), full-output costs by (body + load) / body, where load is the declared
|
||||||
// share of `carried` matter. Drag is unchanged. No load leaves the handling as it is.
|
// share of `carried` matter. Drag is unchanged. No load leaves the handling as it is.
|
||||||
|
|||||||
@@ -23,10 +23,13 @@ struct OpsResponse {
|
|||||||
};
|
};
|
||||||
// Receives the request path (no query handling: probes use exact paths).
|
// Receives the request path (no query handling: probes use exact paths).
|
||||||
using OpsHandler = std::function<OpsResponse(std::string_view path)>;
|
using OpsHandler = std::function<OpsResponse(std::string_view path)>;
|
||||||
// ADR-0131 API mode (the grant broker): GET or POST without a body, the path and the
|
// ADR-0131 API mode (the grant broker): GET or POST, the path and the Authorization header
|
||||||
// Authorization header value (empty when absent). Views are valid during the call only.
|
// value (empty when absent). A body (Content-Length, no chunked encoding) is accepted only
|
||||||
|
// when the server is asked for one (ADR-0182 admin tuning); otherwise it is a 400. Views are
|
||||||
|
// valid during the call only.
|
||||||
struct ApiRequest {
|
struct ApiRequest {
|
||||||
std::string_view method, path, authorization;
|
std::string_view method, path, authorization;
|
||||||
|
std::string_view body{};
|
||||||
};
|
};
|
||||||
using ApiHandler = std::function<OpsResponse(const ApiRequest&)>;
|
using ApiHandler = std::function<OpsResponse(const ApiRequest&)>;
|
||||||
enum class OpsError : std::uint8_t { address, socket };
|
enum class OpsError : std::uint8_t { address, socket };
|
||||||
@@ -39,6 +42,7 @@ class OpsServer {
|
|||||||
static constexpr std::size_t max_accepts_per_serve = 4;
|
static constexpr std::size_t max_accepts_per_serve = 4;
|
||||||
static constexpr std::size_t max_request_bytes = 4096;
|
static constexpr std::size_t max_request_bytes = 4096;
|
||||||
static constexpr std::size_t max_api_request_bytes = 8192; // Room for an access token.
|
static constexpr std::size_t max_api_request_bytes = 8192; // Room for an access token.
|
||||||
|
static constexpr std::size_t max_api_body_bytes = std::size_t{64} << 10U; // Beyond those.
|
||||||
static constexpr std::size_t max_response_bytes = 16384; // The default bound.
|
static constexpr std::size_t max_response_bytes = 16384; // The default bound.
|
||||||
// ADR-0182: the admin view and portal answer up to this many bytes when asked to.
|
// ADR-0182: the admin view and portal answer up to this many bytes when asked to.
|
||||||
static constexpr std::size_t max_configurable_response_bytes = std::size_t{4} << 20U;
|
static constexpr std::size_t max_configurable_response_bytes = std::size_t{4} << 20U;
|
||||||
@@ -61,8 +65,9 @@ class OpsServer {
|
|||||||
// expires connections without waiting. Connections beyond the bound are closed
|
// expires connections without waiting. Connections beyond the bound are closed
|
||||||
// at once; slow or oversized ones are answered or dropped without delaying others.
|
// at once; slow or oversized ones are answered or dropped without delaying others.
|
||||||
void serve(const OpsHandler& handler);
|
void serve(const OpsHandler& handler);
|
||||||
// The same bounded loop for API requests (max_api_request_bytes).
|
// The same bounded loop for API requests (max_api_request_bytes), with request bodies of
|
||||||
void serve_api(const ApiHandler& handler);
|
// at most `body_limit` (at most max_api_body_bytes) bytes; larger ones answer 413.
|
||||||
|
void serve_api(const ApiHandler& handler, std::size_t body_limit = 0);
|
||||||
[[nodiscard]] std::uint64_t refused() const noexcept {
|
[[nodiscard]] std::uint64_t refused() const noexcept {
|
||||||
return refused_;
|
return refused_;
|
||||||
}
|
}
|
||||||
@@ -80,7 +85,7 @@ class OpsServer {
|
|||||||
OpsServer(int fd, std::uint16_t port, std::size_t response_limit)
|
OpsServer(int fd, std::uint16_t port, std::size_t response_limit)
|
||||||
: fd_(fd), port_(port), response_limit_(response_limit) {}
|
: fd_(fd), port_(port), response_limit_(response_limit) {}
|
||||||
void respond(Connection& c, const OpsHandler& handler);
|
void respond(Connection& c, const OpsHandler& handler);
|
||||||
void respond_api(Connection& c, const ApiHandler& handler);
|
void respond_api(Connection& c, const ApiHandler& handler, std::size_t body_limit);
|
||||||
template <typename Answer> void serve_with(std::size_t request_limit, const Answer& answer);
|
template <typename Answer> void serve_with(std::size_t request_limit, const Answer& answer);
|
||||||
int fd_;
|
int fd_;
|
||||||
std::uint16_t port_;
|
std::uint16_t port_;
|
||||||
|
|||||||
@@ -207,6 +207,11 @@ class RegionSessions {
|
|||||||
[[nodiscard]] const network::motion::ProbeMarkers& markers() const noexcept;
|
[[nodiscard]] const network::motion::ProbeMarkers& markers() const noexcept;
|
||||||
// Closes every connection with `shutdown` (flushed by later polls).
|
// Closes every connection with `shutdown` (flushed by later polls).
|
||||||
void shutdown(std::chrono::steady_clock::time_point now);
|
void shutdown(std::chrono::steady_clock::time_point now);
|
||||||
|
// ADR-0087 session window: while closed, every Hello (grant or handoff ticket) is closed
|
||||||
|
// with `shutdown` before signature work. Open by default; closing does not close the
|
||||||
|
// connections already open (call shutdown for that).
|
||||||
|
void set_admission(bool open) noexcept;
|
||||||
|
[[nodiscard]] bool admitting() const noexcept;
|
||||||
[[nodiscard]] std::vector<RegionSessionEvent> take_events();
|
[[nodiscard]] std::vector<RegionSessionEvent> take_events();
|
||||||
[[nodiscard]] std::optional<std::uint64_t> holder(const network::AccountId& account) const;
|
[[nodiscard]] std::optional<std::uint64_t> holder(const network::AccountId& account) const;
|
||||||
[[nodiscard]] std::size_t sessions() const noexcept;
|
[[nodiscard]] std::size_t sessions() const noexcept;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <charconv>
|
#include <charconv>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <expected>
|
#include <expected>
|
||||||
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
@@ -67,4 +68,52 @@ class SessionWindow {
|
|||||||
bool closed_{};
|
bool closed_{};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ADR-0087 amendment (2026-10-27): the window as the database records it, re-read every few
|
||||||
|
// seconds. A newer activation replaces the current window (sessions continue); a closed,
|
||||||
|
// expired, over-long or absent record closes it. Each admitted window keeps its own absolute
|
||||||
|
// deadline, and a window once closed never reopens: only a newer activation opens sessions
|
||||||
|
// again. While the database cannot be read the caller does not observe, so the current
|
||||||
|
// window keeps running to its deadline.
|
||||||
|
class SessionWindowFeed {
|
||||||
|
public:
|
||||||
|
struct Record {
|
||||||
|
std::string activation_id;
|
||||||
|
std::optional<std::uint64_t> expires_at; // nullopt: the record closes the window.
|
||||||
|
};
|
||||||
|
enum class Change : std::uint8_t { none, opened, closed, refused };
|
||||||
|
|
||||||
|
// `record` is the region's newest row, or nullopt when it has none.
|
||||||
|
Change observe(const std::optional<Record>& record, std::uint64_t now_seconds) {
|
||||||
|
if (!record) {
|
||||||
|
const bool had = window_.has_value();
|
||||||
|
window_.reset();
|
||||||
|
seen_.clear();
|
||||||
|
return had ? Change::closed : Change::none;
|
||||||
|
}
|
||||||
|
if (record->activation_id == seen_)
|
||||||
|
return Change::none;
|
||||||
|
seen_ = record->activation_id;
|
||||||
|
const bool had = window_.has_value();
|
||||||
|
window_.reset();
|
||||||
|
if (!record->expires_at)
|
||||||
|
return had ? Change::closed : Change::none;
|
||||||
|
auto opened = SessionWindow::open(
|
||||||
|
record->activation_id + ":" + std::to_string(*record->expires_at), now_seconds);
|
||||||
|
if (!opened)
|
||||||
|
return Change::refused;
|
||||||
|
window_ = std::move(*opened);
|
||||||
|
return Change::opened;
|
||||||
|
}
|
||||||
|
[[nodiscard]] bool accepting(std::uint64_t now_seconds) noexcept {
|
||||||
|
return window_ && window_->accepting(now_seconds);
|
||||||
|
}
|
||||||
|
[[nodiscard]] const std::optional<SessionWindow>& window() const noexcept {
|
||||||
|
return window_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::optional<SessionWindow> window_;
|
||||||
|
std::string seen_; // The newest activation observed, admitted or not.
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace evo::server
|
} // namespace evo::server
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
-- Session windows in SQL (ADR-0087 amendment and ADR-0182, 2026-10-27). A region's dev
|
||||||
|
-- session window is the newest row of an append-only table instead of a Git-committed
|
||||||
|
-- environment value: the admin portal opens, extends and closes it, and the region reads it
|
||||||
|
-- every few seconds. A row with an expiry opens (or replaces) the window until then, at most
|
||||||
|
-- four hours after it was written; a row without one closes it. Rows are never changed.
|
||||||
|
--
|
||||||
|
-- The admin functions move to a dedicated group role: schema 61's read views are revoked
|
||||||
|
-- from the runtime group, and apply.sql grants every admin function to :admin_role on each
|
||||||
|
-- run when that role is configured. The runtime group may only read the current window.
|
||||||
|
|
||||||
|
CREATE TABLE evolution.session_windows (
|
||||||
|
world_id evolution.u64 NOT NULL,
|
||||||
|
region_id evolution.u64 NOT NULL,
|
||||||
|
sequence bigint GENERATED ALWAYS AS IDENTITY,
|
||||||
|
activation_id text NOT NULL UNIQUE CHECK (activation_id ~ '^[A-Za-z0-9._-]{1,64}$'),
|
||||||
|
expires_at timestamptz,
|
||||||
|
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
|
||||||
|
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
PRIMARY KEY (world_id, region_id, sequence),
|
||||||
|
FOREIGN KEY (world_id, region_id) REFERENCES evolution.region_leases,
|
||||||
|
CHECK (expires_at IS NULL OR
|
||||||
|
(expires_at > created_at AND expires_at <= created_at + interval '4 hours'))
|
||||||
|
);
|
||||||
|
CREATE TRIGGER session_windows_immutable BEFORE UPDATE OR DELETE ON evolution.session_windows
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
CREATE TRIGGER session_windows_no_truncate BEFORE TRUNCATE ON evolution.session_windows
|
||||||
|
FOR EACH STATEMENT EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
|
||||||
|
-- The region's current window: its newest row, or nothing when none was ever written.
|
||||||
|
CREATE FUNCTION evolution.load_session_window_v1(p_world evolution.u64, p_region evolution.u64)
|
||||||
|
RETURNS TABLE (activation_id text, expires_at timestamptz, author_subject text,
|
||||||
|
created_at timestamptz)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT w.activation_id, w.expires_at, w.author_subject, w.created_at
|
||||||
|
FROM evolution.session_windows w
|
||||||
|
WHERE w.world_id = p_world AND w.region_id = p_region
|
||||||
|
ORDER BY w.sequence DESC
|
||||||
|
LIMIT 1
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.load_session_window_v1(evolution.u64, evolution.u64) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.load_session_window_v1(evolution.u64, evolution.u64)
|
||||||
|
TO :"runtime_role";
|
||||||
|
|
||||||
|
-- Opens or extends (1..14400 seconds from now, a new activation) or closes (0 seconds) the
|
||||||
|
-- region's window, recording who and why. Returns the row written.
|
||||||
|
CREATE FUNCTION evolution.admin_set_session_window_v1(p_world evolution.u64,
|
||||||
|
p_region evolution.u64, p_seconds integer, p_subject text, p_reason text)
|
||||||
|
RETURNS TABLE (activation_id text, expires_at timestamptz)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
#variable_conflict use_column
|
||||||
|
DECLARE
|
||||||
|
now_at timestamptz := clock_timestamp();
|
||||||
|
id text := 'adm-' || to_char(now_at AT TIME ZONE 'UTC', 'YYYYMMDD"T"HH24MISS') || '-'
|
||||||
|
|| substr(replace(gen_random_uuid()::text, '-', ''), 1, 8);
|
||||||
|
BEGIN
|
||||||
|
IF p_seconds IS NULL OR p_seconds < 0 OR p_seconds > 14400 THEN
|
||||||
|
RAISE EXCEPTION 'session window duration out of range' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
|
||||||
|
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
|
||||||
|
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
RETURN QUERY
|
||||||
|
WITH written AS (
|
||||||
|
INSERT INTO evolution.session_windows AS w(world_id, region_id, activation_id, expires_at,
|
||||||
|
author_subject, reason, created_at)
|
||||||
|
VALUES (p_world, p_region, id,
|
||||||
|
CASE WHEN p_seconds = 0 THEN NULL ELSE now_at + make_interval(secs => p_seconds) END,
|
||||||
|
p_subject, coalesce(p_reason, ''), now_at)
|
||||||
|
RETURNING w.activation_id, w.expires_at)
|
||||||
|
SELECT written.activation_id, written.expires_at FROM written;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_set_session_window_v1(evolution.u64, evolution.u64,
|
||||||
|
integer, text, text) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- The region's last 50 window changes, newest first.
|
||||||
|
CREATE FUNCTION evolution.admin_session_windows_v1(p_world evolution.u64, p_region evolution.u64)
|
||||||
|
RETURNS TABLE (sequence bigint, activation_id text, expires_at timestamptz,
|
||||||
|
author_subject text, reason text, created_at timestamptz)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT w.sequence, w.activation_id, w.expires_at, w.author_subject, w.reason, w.created_at
|
||||||
|
FROM evolution.session_windows w
|
||||||
|
WHERE w.world_id = p_world AND w.region_id = p_region
|
||||||
|
ORDER BY w.sequence DESC
|
||||||
|
LIMIT 50
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_session_windows_v1(evolution.u64, evolution.u64)
|
||||||
|
FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Schema 61's read views belong to the admin role from now on.
|
||||||
|
REVOKE EXECUTE ON FUNCTION evolution.admin_accounts_v1(evolution.u64) FROM :"runtime_role";
|
||||||
|
REVOKE EXECUTE ON FUNCTION evolution.admin_account_lives_v1(evolution.u64, uuid)
|
||||||
|
FROM :"runtime_role";
|
||||||
|
REVOKE EXECUTE ON FUNCTION evolution.admin_regions_v1(evolution.u64) FROM :"runtime_role";
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(62,:'migration_sha_62');
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
-- Admin commands (ADR-0182, 2026-10-27). The admin portal queues operator commands for a
|
||||||
|
-- region: remove a cell, grant a reserve, add bubbles, add to or release the spent pool, and
|
||||||
|
-- spawn wildlife. The region applies each once, after a tick's births, and records it in the
|
||||||
|
-- trace (format 5: trace 4 plus 64-byte command records counted in the tick header's last
|
||||||
|
-- word), so replay and recovery reproduce it. Publication binds every recorded command to
|
||||||
|
-- its queue row exactly once. A bundle-15 trace without commands stays trace 4; the existing
|
||||||
|
-- parsers read a trace 5 through its trace-4 normal form, so nothing else changes.
|
||||||
|
|
||||||
|
-- u64 values as little-endian bytes.
|
||||||
|
CREATE FUNCTION evolution.le_bytes(v numeric, n integer)
|
||||||
|
RETURNS bytea LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE out bytea := ''::bytea; x numeric := v;
|
||||||
|
BEGIN
|
||||||
|
FOR i IN 1 .. n LOOP
|
||||||
|
out := out || set_byte('\x00'::bytea, 0, (x % 256)::integer);
|
||||||
|
x := floor(x / 256);
|
||||||
|
END LOOP;
|
||||||
|
RETURN out;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.le_bytes(numeric, integer) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- The trace-4 normal form of a trace 5: version 4, command counts zero, records dropped.
|
||||||
|
CREATE FUNCTION evolution.cellular_trace_without_admin(t bytea)
|
||||||
|
RETURNS bytea LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
ticks integer;
|
||||||
|
off integer := 112;
|
||||||
|
out bytea;
|
||||||
|
records integer;
|
||||||
|
admin integer;
|
||||||
|
BEGIN
|
||||||
|
IF t IS NULL OR octet_length(t) < 112 OR evolution.manifest_uint(t, 8, 4) <> 5 THEN
|
||||||
|
RETURN t;
|
||||||
|
END IF;
|
||||||
|
ticks := evolution.manifest_uint(t, 104, 4)::integer;
|
||||||
|
out := overlay(substring(t FROM 1 FOR 112) PLACING '\x04000000'::bytea FROM 9 FOR 4);
|
||||||
|
FOR i IN 1 .. ticks LOOP
|
||||||
|
IF octet_length(t) < off + 16 THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
records := evolution.manifest_uint(t, off, 4)::integer * 24
|
||||||
|
+ evolution.manifest_uint(t, off + 4, 4)::integer * 40
|
||||||
|
+ evolution.manifest_uint(t, off + 8, 4)::integer * 40;
|
||||||
|
admin := evolution.manifest_uint(t, off + 12, 4)::integer;
|
||||||
|
IF admin > 16 OR octet_length(t) < off + 16 + records + admin * 64 THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
out := out || substring(t FROM off + 1 FOR 12) || '\x00000000'::bytea
|
||||||
|
|| substring(t FROM off + 17 FOR records);
|
||||||
|
off := off + 16 + records + admin * 64;
|
||||||
|
END LOOP;
|
||||||
|
IF off <> octet_length(t) THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
RETURN out;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.cellular_trace_without_admin(bytea) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- A trace 5's command records with the tick each applies at, in trace order.
|
||||||
|
CREATE FUNCTION evolution.cellular_trace_admin(t bytea, m bytea)
|
||||||
|
RETURNS TABLE (tick evolution.u64, command_id bigint, kind integer, cell_count integer,
|
||||||
|
target evolution.u64, energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64,
|
||||||
|
phosphorus evolution.u64, other evolution.u64)
|
||||||
|
LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(m);
|
||||||
|
ticks integer;
|
||||||
|
off integer := 112;
|
||||||
|
records integer;
|
||||||
|
admin integer;
|
||||||
|
previous numeric;
|
||||||
|
BEGIN
|
||||||
|
IF t IS NULL OR octet_length(t) < 112 OR evolution.manifest_uint(t, 8, 4) <> 5 THEN
|
||||||
|
RETURN;
|
||||||
|
END IF;
|
||||||
|
ticks := evolution.manifest_uint(t, 104, 4)::integer;
|
||||||
|
FOR tick_index IN 0 .. ticks - 1 LOOP
|
||||||
|
records := evolution.manifest_uint(t, off, 4)::integer * 24
|
||||||
|
+ evolution.manifest_uint(t, off + 4, 4)::integer * 40
|
||||||
|
+ evolution.manifest_uint(t, off + 8, 4)::integer * 40;
|
||||||
|
admin := evolution.manifest_uint(t, off + 12, 4)::integer;
|
||||||
|
off := off + 16 + records;
|
||||||
|
previous := 0;
|
||||||
|
FOR i IN 1 .. admin LOOP
|
||||||
|
tick := c.begin_tick + tick_index + 1;
|
||||||
|
command_id := evolution.manifest_uint(t, off, 8)::bigint;
|
||||||
|
kind := evolution.manifest_uint(t, off + 8, 2)::integer;
|
||||||
|
cell_count := evolution.manifest_uint(t, off + 10, 2)::integer;
|
||||||
|
target := evolution.manifest_uint(t, off + 16, 8);
|
||||||
|
energy := evolution.manifest_uint(t, off + 24, 8);
|
||||||
|
carbon := evolution.manifest_uint(t, off + 32, 8);
|
||||||
|
nitrogen := evolution.manifest_uint(t, off + 40, 8);
|
||||||
|
phosphorus := evolution.manifest_uint(t, off + 48, 8);
|
||||||
|
other := evolution.manifest_uint(t, off + 56, 8);
|
||||||
|
IF command_id <= previous OR substring(t FROM off + 13 FOR 4) <> '\x00000000'::bytea THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
previous := command_id;
|
||||||
|
off := off + 64;
|
||||||
|
RETURN NEXT;
|
||||||
|
END LOOP;
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.cellular_trace_admin(bytea, bytea) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- The trace parsers read a bundle-15 trace 5 through its normal form, after binding the real
|
||||||
|
-- trace to the manifest (as schema 55 did for retained plans).
|
||||||
|
CREATE FUNCTION evolution.cellular_trace_normal(INOUT t bytea, INOUT m bytea)
|
||||||
|
LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(m);
|
||||||
|
b15 constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000';
|
||||||
|
BEGIN
|
||||||
|
IF t IS NULL OR octet_length(t) < 12 OR evolution.manifest_uint(t, 8, 4) <> 5 THEN
|
||||||
|
RETURN;
|
||||||
|
END IF;
|
||||||
|
IF c.versions <> b15 OR octet_length(t) <> c.trace_bytes OR sha256(t) <> c.trace_sha256 THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin trace binding' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
t := evolution.cellular_trace_without_admin(t);
|
||||||
|
m := overlay(m PLACING evolution.le_bytes(octet_length(t), 8) FROM 281 FOR 8);
|
||||||
|
m := overlay(m PLACING sha256(t) FROM 289 FOR 32);
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.cellular_trace_normal(bytea, bytea) FROM PUBLIC;
|
||||||
|
|
||||||
|
ALTER FUNCTION evolution.cellular_births(bytea,bytea) RENAME TO cellular_births_v62;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.cellular_births_v62(bytea,bytea) FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.cellular_births(t bytea, m bytea)
|
||||||
|
RETURNS TABLE(account_id uuid, request_id evolution.u64, generation evolution.u64,
|
||||||
|
identity evolution.u64, born evolution.u64)
|
||||||
|
LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE n record := evolution.cellular_trace_normal(t, m);
|
||||||
|
BEGIN
|
||||||
|
RETURN QUERY SELECT * FROM evolution.cellular_births_v62(n.t, n.m);
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.cellular_births(bytea,bytea) FROM PUBLIC;
|
||||||
|
|
||||||
|
ALTER FUNCTION evolution.cellular_mutation_selections(bytea,bytea)
|
||||||
|
RENAME TO cellular_mutation_selections_v62;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.cellular_mutation_selections_v62(bytea,bytea)
|
||||||
|
FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.cellular_mutation_selections(p_trace bytea, p_manifest bytea)
|
||||||
|
RETURNS TABLE (tick evolution.u64, life_id evolution.u64, event_index evolution.u64,
|
||||||
|
offer_tick evolution.u64, successor_identity evolution.u64, operator_id integer)
|
||||||
|
LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE n record := evolution.cellular_trace_normal(p_trace, p_manifest);
|
||||||
|
BEGIN
|
||||||
|
RETURN QUERY SELECT * FROM evolution.cellular_mutation_selections_v62(n.t, n.m);
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.cellular_mutation_selections(bytea,bytea) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- The queue. A row is the operator's exact command; its application is recorded separately.
|
||||||
|
CREATE TABLE evolution.admin_commands (
|
||||||
|
command_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
world_id evolution.u64 NOT NULL,
|
||||||
|
region_id evolution.u64 NOT NULL,
|
||||||
|
kind smallint NOT NULL CHECK (kind BETWEEN 1 AND 6),
|
||||||
|
cell_count integer NOT NULL CHECK (cell_count BETWEEN 0 AND 256),
|
||||||
|
target evolution.u64 NOT NULL,
|
||||||
|
energy evolution.u64 NOT NULL,
|
||||||
|
carbon evolution.u64 NOT NULL,
|
||||||
|
nitrogen evolution.u64 NOT NULL,
|
||||||
|
phosphorus evolution.u64 NOT NULL,
|
||||||
|
other evolution.u64 NOT NULL,
|
||||||
|
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
|
||||||
|
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
FOREIGN KEY (world_id, region_id) REFERENCES evolution.region_leases
|
||||||
|
);
|
||||||
|
CREATE TRIGGER admin_commands_immutable BEFORE UPDATE OR DELETE ON evolution.admin_commands
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
CREATE TRIGGER admin_commands_no_truncate BEFORE TRUNCATE ON evolution.admin_commands
|
||||||
|
FOR EACH STATEMENT EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
CREATE TABLE evolution.admin_command_applications (
|
||||||
|
command_id bigint PRIMARY KEY REFERENCES evolution.admin_commands,
|
||||||
|
commit_id uuid NOT NULL,
|
||||||
|
commit_sequence evolution.u64 NOT NULL,
|
||||||
|
tick evolution.u64 NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TRIGGER admin_command_applications_immutable BEFORE UPDATE OR DELETE
|
||||||
|
ON evolution.admin_command_applications
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
|
||||||
|
-- Queues a command (the same shapes the owner accepts). Spawning takes its identities from the
|
||||||
|
-- world's life allocator, so they never meet a player's.
|
||||||
|
CREATE FUNCTION evolution.admin_enqueue_command_v1(p_world evolution.u64, p_region evolution.u64,
|
||||||
|
p_kind integer, p_count integer, p_target evolution.u64, p_energy evolution.u64,
|
||||||
|
p_carbon evolution.u64, p_nitrogen evolution.u64, p_phosphorus evolution.u64,
|
||||||
|
p_other evolution.u64, p_subject text, p_reason text)
|
||||||
|
RETURNS TABLE (command_id bigint, target evolution.u64)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
#variable_conflict use_column
|
||||||
|
DECLARE
|
||||||
|
has_amount boolean := p_energy + p_carbon + p_nitrogen + p_phosphorus + p_other > 0;
|
||||||
|
first numeric := p_target;
|
||||||
|
BEGIN
|
||||||
|
IF NOT ((p_kind IN (1, 2) AND p_target > 0 AND p_count = 0 AND has_amount = (p_kind = 2))
|
||||||
|
OR (p_kind IN (3, 5) AND p_target = 0 AND p_count BETWEEN 1 AND 256 AND has_amount)
|
||||||
|
OR (p_kind = 4 AND p_target = 0 AND p_count = 0 AND has_amount)
|
||||||
|
OR (p_kind = 6 AND p_count BETWEEN 1 AND 64 AND NOT has_amount)) THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin command' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
|
||||||
|
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
|
||||||
|
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF p_kind = 6 THEN
|
||||||
|
SELECT a.next_identity INTO first FROM evolution.life_allocators a
|
||||||
|
WHERE a.world_id = p_world FOR UPDATE;
|
||||||
|
IF first IS NULL OR first + p_count > 9223372036854775808 THEN
|
||||||
|
RAISE EXCEPTION 'no identities for wildlife' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
UPDATE evolution.life_allocators SET next_identity = first + p_count
|
||||||
|
WHERE world_id = p_world;
|
||||||
|
END IF;
|
||||||
|
RETURN QUERY
|
||||||
|
WITH queued AS (
|
||||||
|
INSERT INTO evolution.admin_commands AS q(world_id, region_id, kind, cell_count, target,
|
||||||
|
energy, carbon, nitrogen, phosphorus, other, author_subject, reason)
|
||||||
|
VALUES (p_world, p_region, p_kind, p_count, first, p_energy, p_carbon, p_nitrogen,
|
||||||
|
p_phosphorus, p_other, p_subject, coalesce(p_reason, ''))
|
||||||
|
RETURNING q.command_id, q.target)
|
||||||
|
SELECT queued.command_id, queued.target FROM queued;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_enqueue_command_v1(evolution.u64, evolution.u64, integer,
|
||||||
|
integer, evolution.u64, evolution.u64, evolution.u64, evolution.u64, evolution.u64,
|
||||||
|
evolution.u64, text, text) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- The region's commands not yet published, oldest first.
|
||||||
|
CREATE FUNCTION evolution.load_pending_admin_commands_v1(p_world evolution.u64,
|
||||||
|
p_region evolution.u64)
|
||||||
|
RETURNS TABLE (command_id bigint, kind integer, cell_count integer, target evolution.u64,
|
||||||
|
energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64,
|
||||||
|
other evolution.u64)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT q.command_id, q.kind, q.cell_count, q.target, q.energy, q.carbon, q.nitrogen,
|
||||||
|
q.phosphorus, q.other
|
||||||
|
FROM evolution.admin_commands q
|
||||||
|
WHERE q.world_id = p_world AND q.region_id = p_region
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM evolution.admin_command_applications a
|
||||||
|
WHERE a.command_id = q.command_id)
|
||||||
|
ORDER BY q.command_id
|
||||||
|
LIMIT 64
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
|
||||||
|
FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
|
||||||
|
TO :"runtime_role";
|
||||||
|
|
||||||
|
-- The region's last 100 commands, newest first, with the tick each applied at.
|
||||||
|
CREATE FUNCTION evolution.admin_commands_v1(p_world evolution.u64, p_region evolution.u64)
|
||||||
|
RETURNS TABLE (command_id bigint, kind integer, cell_count integer, target evolution.u64,
|
||||||
|
energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64,
|
||||||
|
other evolution.u64, author_subject text, reason text, created_at timestamptz,
|
||||||
|
applied_tick evolution.u64)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT q.command_id, q.kind, q.cell_count, q.target, q.energy, q.carbon, q.nitrogen,
|
||||||
|
q.phosphorus, q.other, q.author_subject, q.reason, q.created_at, a.tick
|
||||||
|
FROM evolution.admin_commands q
|
||||||
|
LEFT JOIN evolution.admin_command_applications a ON a.command_id = q.command_id
|
||||||
|
WHERE q.world_id = p_world AND q.region_id = p_region
|
||||||
|
ORDER BY q.command_id DESC
|
||||||
|
LIMIT 100
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_commands_v1(evolution.u64, evolution.u64) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Every command recorded in a published trace is exactly its queue row and applies once.
|
||||||
|
CREATE FUNCTION evolution.bind_cellular_admin_commands(p_manifest bytea, p_trace bytea)
|
||||||
|
RETURNS void LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest);
|
||||||
|
r record;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT * FROM evolution.cellular_trace_admin(p_trace, p_manifest) LOOP
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM evolution.admin_commands q
|
||||||
|
WHERE q.command_id = r.command_id AND q.world_id = c.world_id
|
||||||
|
AND q.region_id = c.region_id AND q.kind = r.kind AND q.cell_count = r.cell_count
|
||||||
|
AND q.target = r.target AND q.energy = r.energy AND q.carbon = r.carbon
|
||||||
|
AND q.nitrogen = r.nitrogen AND q.phosphorus = r.phosphorus AND q.other = r.other) THEN
|
||||||
|
RAISE EXCEPTION 'admin command differs from its queue' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF EXISTS (SELECT 1 FROM evolution.admin_command_applications a
|
||||||
|
WHERE a.command_id = r.command_id AND (a.commit_id <> c.commit_id OR a.tick <> r.tick)) THEN
|
||||||
|
RAISE EXCEPTION 'admin command already applied' USING ERRCODE = 'EVL07';
|
||||||
|
END IF;
|
||||||
|
INSERT INTO evolution.admin_command_applications(command_id, commit_id, commit_sequence, tick)
|
||||||
|
VALUES (r.command_id, c.commit_id, c.commit_sequence, r.tick)
|
||||||
|
ON CONFLICT (command_id) DO NOTHING;
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.bind_cellular_admin_commands(bytea, bytea) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Schema 59's publishers, binding admin commands in the same transaction.
|
||||||
|
ALTER FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea)
|
||||||
|
RENAME TO publish_cellular_checkpoint_v62;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.publish_cellular_checkpoint_v62(bytea,bytea,bytea,bytea)
|
||||||
|
FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.publish_cellular_checkpoint(p_manifest bytea, p_decisions bytea,
|
||||||
|
p_actions bytea, p_trace bytea)
|
||||||
|
RETURNS TABLE(region_frame evolution.u64, head_sequence evolution.u64, head_commit uuid,
|
||||||
|
head_digest text, head_tick evolution.u64)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE h record;
|
||||||
|
BEGIN
|
||||||
|
SELECT * INTO h FROM evolution.publish_cellular_checkpoint_v62(p_manifest, p_decisions,
|
||||||
|
p_actions, p_trace);
|
||||||
|
IF NOT FOUND THEN
|
||||||
|
RAISE EXCEPTION 'publication returned no head' USING ERRCODE = 'XX000';
|
||||||
|
END IF;
|
||||||
|
PERFORM evolution.bind_cellular_admin_commands(p_manifest, p_trace);
|
||||||
|
RETURN QUERY SELECT h.region_frame, h.head_sequence, h.head_commit, h.head_digest, h.head_tick;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea)
|
||||||
|
TO :"runtime_role";
|
||||||
|
|
||||||
|
ALTER FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,bytea,bytea)
|
||||||
|
RENAME TO publish_cellular_mutation_checkpoint_v62;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.publish_cellular_mutation_checkpoint_v62(bytea,bytea,bytea,bytea,
|
||||||
|
bytea,bytea) FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.publish_cellular_mutation_checkpoint(p_manifest bytea,
|
||||||
|
p_decisions bytea, p_actions bytea, p_trace bytea, p_mutations bytea, p_results bytea)
|
||||||
|
RETURNS TABLE(region_frame evolution.u64, head_sequence evolution.u64, head_commit uuid,
|
||||||
|
head_digest text, head_tick evolution.u64)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE h record;
|
||||||
|
BEGIN
|
||||||
|
SELECT * INTO h FROM evolution.publish_cellular_mutation_checkpoint_v62(p_manifest,
|
||||||
|
p_decisions, p_actions, p_trace, p_mutations, p_results);
|
||||||
|
IF NOT FOUND THEN
|
||||||
|
RAISE EXCEPTION 'publication returned no head' USING ERRCODE = 'XX000';
|
||||||
|
END IF;
|
||||||
|
PERFORM evolution.bind_cellular_admin_commands(p_manifest, p_trace);
|
||||||
|
RETURN QUERY SELECT h.region_frame, h.head_sequence, h.head_commit, h.head_digest, h.head_tick;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,
|
||||||
|
bytea,bytea) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,
|
||||||
|
bytea,bytea) TO :"runtime_role";
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(63,:'migration_sha_63');
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
-- Account administration (ADR-0182 section 6, 2026-10-27): bans, an admin logout and time
|
||||||
|
-- played. A ban is an append-only row; the newest row per account decides. A banned account
|
||||||
|
-- gets no grant (SQLSTATE EVL20, which the broker reports as account_banned), and banning
|
||||||
|
-- also revokes its grants, so a live session closes at its next control renewal. Session
|
||||||
|
-- intervals are recorded by the session-control functions the regions already call: a claim
|
||||||
|
-- opens one, a renewal moves its last-seen time, a release closes it. A session that is
|
||||||
|
-- never released ends at its last renewal.
|
||||||
|
|
||||||
|
CREATE TABLE evolution.account_bans (
|
||||||
|
sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
account_id uuid NOT NULL,
|
||||||
|
banned boolean NOT NULL,
|
||||||
|
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
|
||||||
|
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE INDEX account_bans_by_account ON evolution.account_bans(account_id, sequence);
|
||||||
|
CREATE TRIGGER account_bans_immutable BEFORE UPDATE OR DELETE ON evolution.account_bans
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
|
||||||
|
CREATE TABLE evolution.session_intervals (
|
||||||
|
world_id evolution.u64 NOT NULL,
|
||||||
|
account_id uuid NOT NULL,
|
||||||
|
generation evolution.u64 NOT NULL,
|
||||||
|
region_id evolution.u64 NOT NULL,
|
||||||
|
started_at timestamptz NOT NULL,
|
||||||
|
last_seen timestamptz NOT NULL,
|
||||||
|
ended_at timestamptz,
|
||||||
|
PRIMARY KEY (world_id, account_id, generation)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE FUNCTION evolution.account_banned(p_account uuid)
|
||||||
|
RETURNS boolean LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT coalesce((SELECT b.banned FROM evolution.account_bans b
|
||||||
|
WHERE b.account_id = p_account ORDER BY b.sequence DESC LIMIT 1), false)
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.account_banned(uuid) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Raises the account's accepted serial past every grant issued and expires its control, as
|
||||||
|
-- revoke_account_grants does for a Keycloak identity.
|
||||||
|
CREATE FUNCTION evolution.revoke_account_by_id(p_world evolution.u64, p_account uuid)
|
||||||
|
RETURNS boolean LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE r evolution.account_identities%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
SELECT * INTO r FROM evolution.account_identities x WHERE x.account_id = p_account FOR UPDATE;
|
||||||
|
IF NOT FOUND THEN
|
||||||
|
UPDATE evolution.account_controls a
|
||||||
|
SET expires_at = CASE WHEN a.region_id IS NULL THEN NULL
|
||||||
|
ELSE least(a.expires_at, clock_timestamp()) END
|
||||||
|
WHERE a.world_id = p_world AND a.account_id = p_account;
|
||||||
|
RETURN FOUND;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO evolution.account_controls AS a (world_id, account_id, serial, generation)
|
||||||
|
VALUES (p_world, r.account_id, greatest(r.last_serial, 1), 1)
|
||||||
|
ON CONFLICT (world_id, account_id) DO UPDATE
|
||||||
|
SET serial = greatest(a.serial, EXCLUDED.serial),
|
||||||
|
expires_at = CASE WHEN a.region_id IS NULL THEN NULL
|
||||||
|
ELSE least(a.expires_at, clock_timestamp()) END;
|
||||||
|
RETURN true;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.revoke_account_by_id(evolution.u64, uuid) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Admin: ban or lift a ban (recorded with who and why); a ban also logs the account out.
|
||||||
|
CREATE FUNCTION evolution.admin_set_account_ban_v1(p_world evolution.u64, p_account uuid,
|
||||||
|
p_banned boolean, p_subject text, p_reason text)
|
||||||
|
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
BEGIN
|
||||||
|
IF p_world IS NULL OR p_world = 0 OR p_account IS NULL OR p_banned IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'invalid ban' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
INSERT INTO evolution.account_bans(account_id, banned, author_subject, reason)
|
||||||
|
VALUES (p_account, p_banned, p_subject, coalesce(p_reason, ''));
|
||||||
|
IF p_banned THEN
|
||||||
|
PERFORM evolution.revoke_account_by_id(p_world, p_account);
|
||||||
|
END IF;
|
||||||
|
RETURN p_banned;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_set_account_ban_v1(evolution.u64, uuid, boolean, text, text)
|
||||||
|
FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Admin: end the account's sessions now (its next login needs a new grant).
|
||||||
|
CREATE FUNCTION evolution.admin_logout_account_v1(p_world evolution.u64, p_account uuid)
|
||||||
|
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
BEGIN
|
||||||
|
IF p_world IS NULL OR p_world = 0 OR p_account IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'invalid account' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
RETURN evolution.revoke_account_by_id(p_world, p_account);
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_logout_account_v1(evolution.u64, uuid) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Admin: each account's ban state, time played and last session activity in the world.
|
||||||
|
CREATE FUNCTION evolution.admin_account_status_v1(p_world evolution.u64)
|
||||||
|
RETURNS TABLE (account_id uuid, banned boolean, played_seconds bigint, last_seen timestamptz,
|
||||||
|
sessions bigint)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
WITH accounts AS (
|
||||||
|
SELECT i.account_id FROM evolution.account_identities i
|
||||||
|
UNION SELECT s.account_id FROM evolution.session_intervals s WHERE s.world_id = p_world
|
||||||
|
UNION SELECT b.account_id FROM evolution.account_bans b
|
||||||
|
)
|
||||||
|
SELECT a.account_id, evolution.account_banned(a.account_id),
|
||||||
|
coalesce((SELECT floor(sum(extract(epoch FROM coalesce(s.ended_at, s.last_seen)
|
||||||
|
- s.started_at)))::bigint
|
||||||
|
FROM evolution.session_intervals s
|
||||||
|
WHERE s.world_id = p_world AND s.account_id = a.account_id), 0),
|
||||||
|
(SELECT max(coalesce(s.ended_at, s.last_seen)) FROM evolution.session_intervals s
|
||||||
|
WHERE s.world_id = p_world AND s.account_id = a.account_id),
|
||||||
|
(SELECT count(*) FROM evolution.session_intervals s
|
||||||
|
WHERE s.world_id = p_world AND s.account_id = a.account_id)
|
||||||
|
FROM accounts a
|
||||||
|
LIMIT 10000
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_account_status_v1(evolution.u64) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Admin: one account's ban history, newest first.
|
||||||
|
CREATE FUNCTION evolution.admin_account_bans_v1(p_account uuid)
|
||||||
|
RETURNS TABLE (banned boolean, author_subject text, reason text, created_at timestamptz)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT b.banned, b.author_subject, b.reason, b.created_at FROM evolution.account_bans b
|
||||||
|
WHERE b.account_id = p_account ORDER BY b.sequence DESC LIMIT 50
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_account_bans_v1(uuid) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- A banned account gets no grant.
|
||||||
|
ALTER FUNCTION evolution.issue_account_grant(evolution.u64, text, text)
|
||||||
|
RENAME TO issue_account_grant_v63;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.issue_account_grant_v63(evolution.u64, text, text)
|
||||||
|
FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.issue_account_grant(p_world evolution.u64, p_issuer text,
|
||||||
|
p_subject text)
|
||||||
|
RETURNS TABLE(grant_account uuid, grant_serial evolution.u64, home_region evolution.u64)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE known uuid;
|
||||||
|
BEGIN
|
||||||
|
SELECT x.account_id INTO known FROM evolution.account_identities x
|
||||||
|
WHERE x.issuer = p_issuer AND x.subject = p_subject;
|
||||||
|
IF known IS NOT NULL AND evolution.account_banned(known) THEN
|
||||||
|
RAISE EXCEPTION 'account banned' USING ERRCODE = 'EVL20';
|
||||||
|
END IF;
|
||||||
|
RETURN QUERY SELECT * FROM evolution.issue_account_grant_v63(p_world, p_issuer, p_subject);
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.issue_account_grant(evolution.u64, text, text) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.issue_account_grant(evolution.u64, text, text)
|
||||||
|
TO :"runtime_role";
|
||||||
|
|
||||||
|
-- Session intervals from the control functions (signatures unchanged).
|
||||||
|
ALTER FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, evolution.u64,
|
||||||
|
uuid, evolution.u64, evolution.u64, integer) RENAME TO claim_account_control_v63;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.claim_account_control_v63(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.claim_account_control(p_world evolution.u64, p_region evolution.u64,
|
||||||
|
p_holder uuid, p_epoch evolution.u64, p_account uuid, p_serial evolution.u64,
|
||||||
|
p_session evolution.u64, p_duration_ms integer)
|
||||||
|
RETURNS TABLE (control_generation evolution.u64, wait_ms integer, granted_ms integer)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE r record;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT * FROM evolution.claim_account_control_v63(p_world, p_region, p_holder,
|
||||||
|
p_epoch, p_account, p_serial, p_session, p_duration_ms) LOOP
|
||||||
|
IF r.granted_ms > 0 THEN
|
||||||
|
INSERT INTO evolution.session_intervals(world_id, account_id, generation, region_id,
|
||||||
|
started_at, last_seen)
|
||||||
|
VALUES (p_world, p_account, r.control_generation, p_region, clock_timestamp(),
|
||||||
|
clock_timestamp())
|
||||||
|
ON CONFLICT (world_id, account_id, generation) DO NOTHING;
|
||||||
|
END IF;
|
||||||
|
control_generation := r.control_generation;
|
||||||
|
wait_ms := r.wait_ms;
|
||||||
|
granted_ms := r.granted_ms;
|
||||||
|
RETURN NEXT;
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64, evolution.u64, integer) TO :"runtime_role";
|
||||||
|
|
||||||
|
ALTER FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid, evolution.u64,
|
||||||
|
uuid, evolution.u64, integer) RENAME TO renew_account_control_v63;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.renew_account_control_v63(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64, integer) FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.renew_account_control(p_world evolution.u64, p_region evolution.u64,
|
||||||
|
p_holder uuid, p_epoch evolution.u64, p_account uuid, p_generation evolution.u64,
|
||||||
|
p_duration_ms integer)
|
||||||
|
RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE granted integer;
|
||||||
|
BEGIN
|
||||||
|
granted := evolution.renew_account_control_v63(p_world, p_region, p_holder, p_epoch, p_account,
|
||||||
|
p_generation, p_duration_ms);
|
||||||
|
UPDATE evolution.session_intervals s SET last_seen = clock_timestamp()
|
||||||
|
WHERE s.world_id = p_world AND s.account_id = p_account AND s.generation = p_generation
|
||||||
|
AND s.ended_at IS NULL;
|
||||||
|
RETURN granted;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64, integer) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64, integer) TO :"runtime_role";
|
||||||
|
|
||||||
|
ALTER FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64) RENAME TO release_account_control_v63;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.release_account_control_v63(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64) FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.release_account_control(p_world evolution.u64, p_region evolution.u64,
|
||||||
|
p_holder uuid, p_epoch evolution.u64, p_account uuid, p_generation evolution.u64)
|
||||||
|
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE released boolean;
|
||||||
|
BEGIN
|
||||||
|
released := evolution.release_account_control_v63(p_world, p_region, p_holder, p_epoch,
|
||||||
|
p_account, p_generation);
|
||||||
|
UPDATE evolution.session_intervals s SET last_seen = clock_timestamp(),
|
||||||
|
ended_at = clock_timestamp()
|
||||||
|
WHERE s.world_id = p_world AND s.account_id = p_account AND s.generation = p_generation
|
||||||
|
AND s.ended_at IS NULL;
|
||||||
|
RETURN released;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid,
|
||||||
|
evolution.u64, uuid, evolution.u64) TO :"runtime_role";
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(64,:'migration_sha_64');
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
-- Resource schedules (ADR-0182 section 4, 2026-10-27): the game source as recurring admin
|
||||||
|
-- commands. A schedule repeats an add_bubbles, release_pool or spawn_wildlife command every
|
||||||
|
-- `interval_seconds` while it is enabled. When the region reads its pending commands, each
|
||||||
|
-- enabled schedule whose last command was applied (or that never ran) and whose interval has
|
||||||
|
-- passed queues its next command, exactly as an operator would; it is then recorded in the
|
||||||
|
-- trace and bound once like any command. At most one command per schedule waits, so an idle
|
||||||
|
-- region (no living cells, no ticks) builds no backlog. Schedule versions are append-only;
|
||||||
|
-- the newest row of a schedule decides.
|
||||||
|
|
||||||
|
ALTER TABLE evolution.admin_commands ADD COLUMN schedule_id bigint;
|
||||||
|
|
||||||
|
CREATE TABLE evolution.admin_schedules (
|
||||||
|
sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
schedule_id bigint NOT NULL,
|
||||||
|
world_id evolution.u64 NOT NULL,
|
||||||
|
region_id evolution.u64 NOT NULL,
|
||||||
|
kind smallint NOT NULL CHECK (kind IN (3, 5, 6)),
|
||||||
|
cell_count integer NOT NULL CHECK (cell_count BETWEEN 1 AND 256),
|
||||||
|
energy evolution.u64 NOT NULL,
|
||||||
|
carbon evolution.u64 NOT NULL,
|
||||||
|
nitrogen evolution.u64 NOT NULL,
|
||||||
|
phosphorus evolution.u64 NOT NULL,
|
||||||
|
other evolution.u64 NOT NULL,
|
||||||
|
interval_seconds integer NOT NULL CHECK (interval_seconds BETWEEN 1 AND 86400),
|
||||||
|
enabled boolean NOT NULL,
|
||||||
|
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
|
||||||
|
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
FOREIGN KEY (world_id, region_id) REFERENCES evolution.region_leases,
|
||||||
|
CHECK ((kind = 6 AND cell_count <= 64 AND energy + carbon + nitrogen + phosphorus + other = 0)
|
||||||
|
OR (kind IN (3, 5) AND energy + carbon + nitrogen + phosphorus + other > 0))
|
||||||
|
);
|
||||||
|
CREATE INDEX admin_schedules_by_schedule ON evolution.admin_schedules(schedule_id, sequence);
|
||||||
|
CREATE SEQUENCE evolution.admin_schedule_ids;
|
||||||
|
CREATE TRIGGER admin_schedules_immutable BEFORE UPDATE OR DELETE ON evolution.admin_schedules
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
|
||||||
|
-- Admin: creates (p_schedule 0) or replaces a schedule's settings; disabling stops it.
|
||||||
|
CREATE FUNCTION evolution.admin_set_schedule_v1(p_world evolution.u64, p_region evolution.u64,
|
||||||
|
p_schedule bigint, p_kind integer, p_count integer, p_energy evolution.u64,
|
||||||
|
p_carbon evolution.u64, p_nitrogen evolution.u64, p_phosphorus evolution.u64,
|
||||||
|
p_other evolution.u64, p_interval integer, p_enabled boolean, p_subject text, p_reason text)
|
||||||
|
RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE id bigint := p_schedule;
|
||||||
|
BEGIN
|
||||||
|
IF id IS NULL OR id = 0 THEN
|
||||||
|
id := nextval('evolution.admin_schedule_ids');
|
||||||
|
ELSIF NOT EXISTS (SELECT 1 FROM evolution.admin_schedules s WHERE s.schedule_id = id
|
||||||
|
AND s.world_id = p_world AND s.region_id = p_region) THEN
|
||||||
|
RAISE EXCEPTION 'unknown schedule' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
BEGIN
|
||||||
|
INSERT INTO evolution.admin_schedules(schedule_id, world_id, region_id, kind, cell_count,
|
||||||
|
energy, carbon, nitrogen, phosphorus, other, interval_seconds, enabled, author_subject,
|
||||||
|
reason)
|
||||||
|
VALUES (id, p_world, p_region, p_kind, p_count, p_energy, p_carbon, p_nitrogen,
|
||||||
|
p_phosphorus, p_other, p_interval, p_enabled, p_subject, coalesce(p_reason, ''));
|
||||||
|
EXCEPTION WHEN check_violation OR foreign_key_violation OR not_null_violation THEN
|
||||||
|
RAISE EXCEPTION 'invalid schedule' USING ERRCODE = '22023';
|
||||||
|
END;
|
||||||
|
RETURN id;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_set_schedule_v1(evolution.u64, evolution.u64, bigint,
|
||||||
|
integer, integer, evolution.u64, evolution.u64, evolution.u64, evolution.u64, evolution.u64,
|
||||||
|
integer, boolean, text, text) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Admin: a region's schedules as they now stand, with their last queued command.
|
||||||
|
CREATE FUNCTION evolution.admin_schedules_v1(p_world evolution.u64, p_region evolution.u64)
|
||||||
|
RETURNS TABLE (schedule_id bigint, kind integer, cell_count integer, energy evolution.u64,
|
||||||
|
carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64, other evolution.u64,
|
||||||
|
interval_seconds integer, enabled boolean, author_subject text, reason text,
|
||||||
|
changed_at timestamptz, last_queued timestamptz, runs bigint)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT s.schedule_id, s.kind, s.cell_count, s.energy, s.carbon, s.nitrogen, s.phosphorus,
|
||||||
|
s.other, s.interval_seconds, s.enabled, s.author_subject, s.reason, s.created_at,
|
||||||
|
(SELECT max(q.created_at) FROM evolution.admin_commands q
|
||||||
|
WHERE q.schedule_id = s.schedule_id),
|
||||||
|
(SELECT count(*) FROM evolution.admin_commands q WHERE q.schedule_id = s.schedule_id)
|
||||||
|
FROM evolution.admin_schedules s
|
||||||
|
WHERE s.world_id = p_world AND s.region_id = p_region
|
||||||
|
AND s.sequence = (SELECT max(x.sequence) FROM evolution.admin_schedules x
|
||||||
|
WHERE x.schedule_id = s.schedule_id)
|
||||||
|
ORDER BY s.schedule_id
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_schedules_v1(evolution.u64, evolution.u64) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Queues every due schedule's next command (spawning takes identities from the allocator).
|
||||||
|
CREATE FUNCTION evolution.queue_due_schedules(p_world evolution.u64, p_region evolution.u64)
|
||||||
|
RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
s record;
|
||||||
|
first numeric;
|
||||||
|
BEGIN
|
||||||
|
FOR s IN SELECT * FROM evolution.admin_schedules x
|
||||||
|
WHERE x.world_id = p_world AND x.region_id = p_region
|
||||||
|
AND x.sequence = (SELECT max(y.sequence) FROM evolution.admin_schedules y
|
||||||
|
WHERE y.schedule_id = x.schedule_id)
|
||||||
|
AND x.enabled
|
||||||
|
ORDER BY x.schedule_id LOOP
|
||||||
|
CONTINUE WHEN EXISTS (SELECT 1 FROM evolution.admin_commands q
|
||||||
|
WHERE q.schedule_id = s.schedule_id
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM evolution.admin_command_applications a
|
||||||
|
WHERE a.command_id = q.command_id));
|
||||||
|
CONTINUE WHEN coalesce((SELECT max(q.created_at) FROM evolution.admin_commands q
|
||||||
|
WHERE q.schedule_id = s.schedule_id), '-infinity'::timestamptz)
|
||||||
|
+ make_interval(secs => s.interval_seconds) > clock_timestamp();
|
||||||
|
first := 0;
|
||||||
|
IF s.kind = 6 THEN
|
||||||
|
SELECT a.next_identity INTO first FROM evolution.life_allocators a
|
||||||
|
WHERE a.world_id = p_world FOR UPDATE;
|
||||||
|
CONTINUE WHEN first IS NULL OR first + s.cell_count > 9223372036854775808;
|
||||||
|
UPDATE evolution.life_allocators SET next_identity = first + s.cell_count
|
||||||
|
WHERE world_id = p_world;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO evolution.admin_commands(world_id, region_id, kind, cell_count, target, energy,
|
||||||
|
carbon, nitrogen, phosphorus, other, author_subject, reason, schedule_id)
|
||||||
|
VALUES (p_world, p_region, s.kind, s.cell_count, first, s.energy, s.carbon, s.nitrogen,
|
||||||
|
s.phosphorus, s.other, 'schedule ' || s.schedule_id, s.reason, s.schedule_id);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.queue_due_schedules(evolution.u64, evolution.u64) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- The region's pending commands, after queuing what its schedules owe (same signature).
|
||||||
|
ALTER FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
|
||||||
|
RENAME TO load_pending_admin_commands_v64;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.load_pending_admin_commands_v64(evolution.u64, evolution.u64)
|
||||||
|
FROM PUBLIC, :"runtime_role";
|
||||||
|
CREATE FUNCTION evolution.load_pending_admin_commands_v1(p_world evolution.u64,
|
||||||
|
p_region evolution.u64)
|
||||||
|
RETURNS TABLE (command_id bigint, kind integer, cell_count integer, target evolution.u64,
|
||||||
|
energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64,
|
||||||
|
other evolution.u64)
|
||||||
|
LANGUAGE plpgsql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
BEGIN
|
||||||
|
PERFORM evolution.queue_due_schedules(p_world, p_region);
|
||||||
|
RETURN QUERY SELECT * FROM evolution.load_pending_admin_commands_v64(p_world, p_region);
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
|
||||||
|
FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
|
||||||
|
TO :"runtime_role";
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(65,:'migration_sha_65');
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
-- Tuning revisions (ADR-0182 sections 1-2, 2026-10-27). The rules-13 tuning of a world is a
|
||||||
|
-- sequence of append-only revisions: the canonical tuning text and the SHA-256 of the rules it
|
||||||
|
-- produces (encode_cellular_revamp_rules). Storing a revision queues an adopt_tuning admin
|
||||||
|
-- command (kind 7) for each named region; the region fetches the text, rebuilds the rules,
|
||||||
|
-- checks the digest and adopts them at a tick recorded in its trace, so replay and recovery
|
||||||
|
-- reproduce the change exactly. Commands of kind 7 come only from this function.
|
||||||
|
|
||||||
|
ALTER TABLE evolution.admin_commands DROP CONSTRAINT admin_commands_kind_check;
|
||||||
|
ALTER TABLE evolution.admin_commands ADD CONSTRAINT admin_commands_kind_check
|
||||||
|
CHECK (kind BETWEEN 1 AND 7);
|
||||||
|
|
||||||
|
CREATE TABLE evolution.tuning_revisions (
|
||||||
|
revision bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
world_id evolution.u64 NOT NULL,
|
||||||
|
text text NOT NULL CHECK (octet_length(text) BETWEEN 1 AND 262144),
|
||||||
|
rules_sha256 bytea NOT NULL CHECK (octet_length(rules_sha256) = 32),
|
||||||
|
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
|
||||||
|
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE TRIGGER tuning_revisions_immutable BEFORE UPDATE OR DELETE ON evolution.tuning_revisions
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
|
||||||
|
-- Admin: stores a revision (validated by the admin API, which also computed the rules digest;
|
||||||
|
-- the text is kept as written, comments included) and queues its adoption in each of
|
||||||
|
-- `p_regions`.
|
||||||
|
CREATE FUNCTION evolution.admin_set_tuning_v1(p_world evolution.u64, p_text text,
|
||||||
|
p_rules_sha256 bytea, p_regions bigint[], p_subject text, p_reason text)
|
||||||
|
RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
made bigint;
|
||||||
|
region bigint;
|
||||||
|
BEGIN
|
||||||
|
IF p_world IS NULL OR p_world = 0 OR p_regions IS NULL OR cardinality(p_regions) = 0
|
||||||
|
OR cardinality(p_regions) > 64 OR p_rules_sha256 IS NULL
|
||||||
|
OR octet_length(p_rules_sha256) <> 32 THEN
|
||||||
|
RAISE EXCEPTION 'invalid tuning revision' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
BEGIN
|
||||||
|
INSERT INTO evolution.tuning_revisions(world_id, text, rules_sha256, author_subject, reason)
|
||||||
|
VALUES (p_world, p_text, p_rules_sha256, p_subject, coalesce(p_reason, ''))
|
||||||
|
RETURNING revision INTO made;
|
||||||
|
EXCEPTION WHEN check_violation OR not_null_violation THEN
|
||||||
|
RAISE EXCEPTION 'invalid tuning revision' USING ERRCODE = '22023';
|
||||||
|
END;
|
||||||
|
FOREACH region IN ARRAY p_regions LOOP
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
|
||||||
|
WHERE l.world_id = p_world AND l.region_id = region) THEN
|
||||||
|
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
INSERT INTO evolution.admin_commands(world_id, region_id, kind, cell_count, target, energy,
|
||||||
|
carbon, nitrogen, phosphorus, other, author_subject, reason)
|
||||||
|
VALUES (p_world, region, 7, 0, made, evolution.manifest_uint(p_rules_sha256, 0, 8),
|
||||||
|
evolution.manifest_uint(p_rules_sha256, 8, 8),
|
||||||
|
evolution.manifest_uint(p_rules_sha256, 16, 8),
|
||||||
|
evolution.manifest_uint(p_rules_sha256, 24, 8), 0, p_subject, coalesce(p_reason, ''));
|
||||||
|
END LOOP;
|
||||||
|
RETURN made;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_set_tuning_v1(evolution.u64, text, bytea, bigint[], text,
|
||||||
|
text) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- The region: a revision's text and rules digest.
|
||||||
|
CREATE FUNCTION evolution.load_tuning_revision_v1(p_world evolution.u64, p_revision bigint)
|
||||||
|
RETURNS TABLE (text text, rules_sha256 bytea)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT t.text, t.rules_sha256 FROM evolution.tuning_revisions t
|
||||||
|
WHERE t.world_id = p_world AND t.revision = p_revision
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.load_tuning_revision_v1(evolution.u64, bigint) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.load_tuning_revision_v1(evolution.u64, bigint)
|
||||||
|
TO :"runtime_role";
|
||||||
|
|
||||||
|
-- Admin: the world's revisions, newest first, with how many regions have adopted each.
|
||||||
|
CREATE FUNCTION evolution.admin_tuning_revisions_v1(p_world evolution.u64)
|
||||||
|
RETURNS TABLE (revision bigint, rules_sha256 text, author_subject text, reason text,
|
||||||
|
created_at timestamptz, regions bigint, adopted bigint, last_tick evolution.u64)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT t.revision, encode(t.rules_sha256, 'hex'), t.author_subject, t.reason, t.created_at,
|
||||||
|
(SELECT count(*) FROM evolution.admin_commands q
|
||||||
|
WHERE q.kind = 7 AND q.world_id = p_world AND q.target = t.revision),
|
||||||
|
(SELECT count(*) FROM evolution.admin_commands q
|
||||||
|
JOIN evolution.admin_command_applications a ON a.command_id = q.command_id
|
||||||
|
WHERE q.kind = 7 AND q.world_id = p_world AND q.target = t.revision),
|
||||||
|
(SELECT max(a.tick) FROM evolution.admin_commands q
|
||||||
|
JOIN evolution.admin_command_applications a ON a.command_id = q.command_id
|
||||||
|
WHERE q.kind = 7 AND q.world_id = p_world AND q.target = t.revision)
|
||||||
|
FROM evolution.tuning_revisions t
|
||||||
|
WHERE t.world_id = p_world
|
||||||
|
ORDER BY t.revision DESC
|
||||||
|
LIMIT 100
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_tuning_revisions_v1(evolution.u64) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- Admin: a revision's text (0: the newest).
|
||||||
|
CREATE FUNCTION evolution.admin_tuning_text_v1(p_world evolution.u64, p_revision bigint)
|
||||||
|
RETURNS TABLE (revision bigint, text text)
|
||||||
|
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
SELECT t.revision, t.text FROM evolution.tuning_revisions t
|
||||||
|
WHERE t.world_id = p_world AND (p_revision = 0 OR t.revision = p_revision)
|
||||||
|
ORDER BY t.revision DESC
|
||||||
|
LIMIT 1
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_tuning_text_v1(evolution.u64, bigint) FROM PUBLIC;
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(66,:'migration_sha_66');
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
-- Admin take and cull (ADR-0182 section 16, 2026-10-28). Two more admin command kinds for
|
||||||
|
-- testing a live region: take_reserve (8) moves up to the given amounts from one life's
|
||||||
|
-- reserve to the spent pool, the inverse of grant_reserve; remove_wildlife (9) removes every
|
||||||
|
-- life without an account at once, as remove_cell does one.
|
||||||
|
|
||||||
|
ALTER TABLE evolution.admin_commands DROP CONSTRAINT admin_commands_kind_check;
|
||||||
|
ALTER TABLE evolution.admin_commands ADD CONSTRAINT admin_commands_kind_check
|
||||||
|
CHECK (kind BETWEEN 1 AND 9);
|
||||||
|
|
||||||
|
-- Queues a command (the same shapes the owner accepts). Spawning takes its identities from the
|
||||||
|
-- world's life allocator, so they never meet a player's.
|
||||||
|
CREATE OR REPLACE FUNCTION evolution.admin_enqueue_command_v1(p_world evolution.u64,
|
||||||
|
p_region evolution.u64, p_kind integer, p_count integer, p_target evolution.u64,
|
||||||
|
p_energy evolution.u64, p_carbon evolution.u64, p_nitrogen evolution.u64,
|
||||||
|
p_phosphorus evolution.u64, p_other evolution.u64, p_subject text, p_reason text)
|
||||||
|
RETURNS TABLE (command_id bigint, target evolution.u64)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
#variable_conflict use_column
|
||||||
|
DECLARE
|
||||||
|
has_amount boolean := p_energy + p_carbon + p_nitrogen + p_phosphorus + p_other > 0;
|
||||||
|
first numeric := p_target;
|
||||||
|
BEGIN
|
||||||
|
IF NOT ((p_kind IN (1, 2, 8) AND p_target > 0 AND p_count = 0
|
||||||
|
AND has_amount = (p_kind IN (2, 8)))
|
||||||
|
OR (p_kind IN (3, 5) AND p_target = 0 AND p_count BETWEEN 1 AND 256 AND has_amount)
|
||||||
|
OR (p_kind = 4 AND p_target = 0 AND p_count = 0 AND has_amount)
|
||||||
|
OR (p_kind = 6 AND p_count BETWEEN 1 AND 64 AND NOT has_amount)
|
||||||
|
OR (p_kind = 9 AND p_target = 0 AND p_count = 0 AND NOT has_amount)) THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin command' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
|
||||||
|
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
|
||||||
|
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF p_kind = 6 THEN
|
||||||
|
SELECT a.next_identity INTO first FROM evolution.life_allocators a
|
||||||
|
WHERE a.world_id = p_world FOR UPDATE;
|
||||||
|
IF first IS NULL OR first + p_count > 9223372036854775808 THEN
|
||||||
|
RAISE EXCEPTION 'no identities for wildlife' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
UPDATE evolution.life_allocators SET next_identity = first + p_count
|
||||||
|
WHERE world_id = p_world;
|
||||||
|
END IF;
|
||||||
|
RETURN QUERY
|
||||||
|
WITH queued AS (
|
||||||
|
INSERT INTO evolution.admin_commands AS q(world_id, region_id, kind, cell_count, target,
|
||||||
|
energy, carbon, nitrogen, phosphorus, other, author_subject, reason)
|
||||||
|
VALUES (p_world, p_region, p_kind, p_count, first, p_energy, p_carbon, p_nitrogen,
|
||||||
|
p_phosphorus, p_other, p_subject, coalesce(p_reason, ''))
|
||||||
|
RETURNING q.command_id, q.target)
|
||||||
|
SELECT queued.command_id, queued.target FROM queued;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(67,:'migration_sha_67');
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
-- Larger region ticks (ADR-0182 section 17, 2026-10-28). A region tick may hold up to 4,096
|
||||||
|
-- lives, a bound for testing (regions run far fewer). The cellular trace checker under the
|
||||||
|
-- current publishers (schema 43's, renamed cellular_births_v45 by schema 46) accepts up to
|
||||||
|
-- 4,096 intents, births and mutation choices per tick; nothing else in it changes. Cohort
|
||||||
|
-- populations and migration traces keep their 256 bounds. Spawning takes up to 256 wildlife
|
||||||
|
-- per command.
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION evolution.cellular_births_v45(p_trace bytea, p_manifest bytea)
|
||||||
|
RETURNS TABLE(account_id uuid, request_id evolution.u64, generation evolution.u64,
|
||||||
|
identity evolution.u64, born evolution.u64)
|
||||||
|
LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest);
|
||||||
|
revision boolean;
|
||||||
|
ticks numeric;
|
||||||
|
tick_index integer;
|
||||||
|
trace_format numeric;
|
||||||
|
tick_header_size integer;
|
||||||
|
intent_count numeric;
|
||||||
|
birth_count numeric;
|
||||||
|
mutation_count numeric;
|
||||||
|
off integer := 112;
|
||||||
|
account bytea;
|
||||||
|
previous_account bytea;
|
||||||
|
previous_request numeric;
|
||||||
|
BEGIN
|
||||||
|
revision := c.versions IN (
|
||||||
|
'\x020000000300000001000000010000000100000002000000010000000200000001000000'::bytea,
|
||||||
|
'\x030000000400000001000000010000000100000002000000010000000200000001000000'::bytea,
|
||||||
|
'\x040000000500000001000000010000000100000002000000010000000200000001000000'::bytea,
|
||||||
|
'\x050000000600000001000000010000000100000002000000010000000200000001000000'::bytea,
|
||||||
|
'\x060000000600000001000000010000000100000003000000020000000200000001000000'::bytea,
|
||||||
|
'\x070000000600000001000000010000000100000004000000030000000200000001000000'::bytea,
|
||||||
|
'\x080000000600000002000000010000000100000004000000030000000200000001000000'::bytea);
|
||||||
|
trace_format := evolution.manifest_uint(p_trace, 8, 4);
|
||||||
|
tick_header_size := CASE trace_format WHEN 2 THEN 8 WHEN 3 THEN 16 ELSE 0 END;
|
||||||
|
IF c.profile <> 4 OR c.commit_sequence = 0 OR p_trace IS NULL
|
||||||
|
OR octet_length(p_trace) <> c.trace_bytes OR sha256(p_trace) <> c.trace_sha256
|
||||||
|
OR substring(p_trace FROM 1 FOR 8) <> '\x45564c4342543031'
|
||||||
|
OR tick_header_size = 0
|
||||||
|
OR (revision AND trace_format <> 3)
|
||||||
|
OR (NOT revision AND trace_format <> 2)
|
||||||
|
OR evolution.manifest_uint(p_trace, 12, 4) <> 4
|
||||||
|
OR evolution.manifest_uint(p_trace, 16, 8) <> c.world_id
|
||||||
|
OR evolution.manifest_uint(p_trace, 24, 8) <> c.region_id
|
||||||
|
OR evolution.manifest_uint(p_trace, 32, 8) <> c.frame_id
|
||||||
|
OR encode(substring(p_trace FROM 41 FOR 16), 'hex')::uuid <> c.predecessor_commit
|
||||||
|
OR substring(p_trace FROM 57 FOR 32) <> c.predecessor_digest
|
||||||
|
OR evolution.manifest_uint(p_trace, 88, 8) <> c.begin_tick
|
||||||
|
OR evolution.manifest_uint(p_trace, 96, 8) <> c.end_tick THEN
|
||||||
|
RAISE EXCEPTION 'invalid cellular birth trace binding' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
ticks := c.end_tick - c.begin_tick;
|
||||||
|
IF ticks < 1 OR ticks > 64 OR evolution.manifest_uint(p_trace, 104, 4) <> ticks
|
||||||
|
OR evolution.manifest_uint(p_trace, 108, 4) <> 0 THEN
|
||||||
|
RAISE EXCEPTION 'invalid cellular birth trace range' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
FOR tick_index IN 0 .. ticks::integer - 1 LOOP
|
||||||
|
IF off + tick_header_size > octet_length(p_trace) THEN
|
||||||
|
RAISE EXCEPTION 'truncated cellular tick header' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
intent_count := evolution.manifest_uint(p_trace, off, 4);
|
||||||
|
birth_count := evolution.manifest_uint(p_trace, off + 4, 4);
|
||||||
|
mutation_count := 0;
|
||||||
|
IF trace_format = 3 THEN
|
||||||
|
mutation_count := evolution.manifest_uint(p_trace, off + 8, 4);
|
||||||
|
IF evolution.manifest_uint(p_trace, off + 12, 4) <> 0 THEN
|
||||||
|
RAISE EXCEPTION 'invalid cellular tick reserved word' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
END IF;
|
||||||
|
IF intent_count > 4096 OR birth_count > 4096 OR mutation_count > 4096
|
||||||
|
OR off + tick_header_size + intent_count * 24 + birth_count * 40
|
||||||
|
+ mutation_count * 40 > octet_length(p_trace) THEN
|
||||||
|
RAISE EXCEPTION 'invalid cellular tick counts' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
off := off + tick_header_size + intent_count::integer * 24;
|
||||||
|
previous_account := ''::bytea;
|
||||||
|
previous_request := -1;
|
||||||
|
FOR birth_index IN 0 .. birth_count::integer - 1 LOOP
|
||||||
|
account := substring(p_trace FROM off + 1 FOR 16);
|
||||||
|
account_id := encode(account, 'hex')::uuid;
|
||||||
|
request_id := evolution.manifest_uint(p_trace, off + 16, 8);
|
||||||
|
generation := evolution.manifest_uint(p_trace, off + 24, 8);
|
||||||
|
identity := evolution.manifest_uint(p_trace, off + 32, 8);
|
||||||
|
born := c.begin_tick + tick_index + 1;
|
||||||
|
IF account_id = '00000000-0000-0000-0000-000000000000' OR request_id = 0
|
||||||
|
OR generation = 0 OR identity = 0
|
||||||
|
OR (account, request_id) <= (previous_account, previous_request) THEN
|
||||||
|
RAISE EXCEPTION 'invalid cellular birth record' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
previous_account := account;
|
||||||
|
previous_request := request_id;
|
||||||
|
off := off + 40;
|
||||||
|
RETURN NEXT;
|
||||||
|
END LOOP;
|
||||||
|
off := off + mutation_count::integer * 40;
|
||||||
|
END LOOP;
|
||||||
|
IF off <> octet_length(p_trace) THEN
|
||||||
|
RAISE EXCEPTION 'trailing cellular trace bytes' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION evolution.admin_enqueue_command_v1(p_world evolution.u64,
|
||||||
|
p_region evolution.u64, p_kind integer, p_count integer, p_target evolution.u64,
|
||||||
|
p_energy evolution.u64, p_carbon evolution.u64, p_nitrogen evolution.u64,
|
||||||
|
p_phosphorus evolution.u64, p_other evolution.u64, p_subject text, p_reason text)
|
||||||
|
RETURNS TABLE (command_id bigint, target evolution.u64)
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
#variable_conflict use_column
|
||||||
|
DECLARE
|
||||||
|
has_amount boolean := p_energy + p_carbon + p_nitrogen + p_phosphorus + p_other > 0;
|
||||||
|
first numeric := p_target;
|
||||||
|
BEGIN
|
||||||
|
IF NOT ((p_kind IN (1, 2, 8) AND p_target > 0 AND p_count = 0
|
||||||
|
AND has_amount = (p_kind IN (2, 8)))
|
||||||
|
OR (p_kind IN (3, 5) AND p_target = 0 AND p_count BETWEEN 1 AND 256 AND has_amount)
|
||||||
|
OR (p_kind = 4 AND p_target = 0 AND p_count = 0 AND has_amount)
|
||||||
|
OR (p_kind = 6 AND p_count BETWEEN 1 AND 256 AND NOT has_amount)
|
||||||
|
OR (p_kind = 9 AND p_target = 0 AND p_count = 0 AND NOT has_amount)) THEN
|
||||||
|
RAISE EXCEPTION 'invalid admin command' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
|
||||||
|
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
|
||||||
|
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
IF p_kind = 6 THEN
|
||||||
|
SELECT a.next_identity INTO first FROM evolution.life_allocators a
|
||||||
|
WHERE a.world_id = p_world FOR UPDATE;
|
||||||
|
IF first IS NULL OR first + p_count > 9223372036854775808 THEN
|
||||||
|
RAISE EXCEPTION 'no identities for wildlife' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
UPDATE evolution.life_allocators SET next_identity = first + p_count
|
||||||
|
WHERE world_id = p_world;
|
||||||
|
END IF;
|
||||||
|
RETURN QUERY
|
||||||
|
WITH queued AS (
|
||||||
|
INSERT INTO evolution.admin_commands AS q(world_id, region_id, kind, cell_count, target,
|
||||||
|
energy, carbon, nitrogen, phosphorus, other, author_subject, reason)
|
||||||
|
VALUES (p_world, p_region, p_kind, p_count, first, p_energy, p_carbon, p_nitrogen,
|
||||||
|
p_phosphorus, p_other, p_subject, coalesce(p_reason, ''))
|
||||||
|
RETURNING q.command_id, q.target)
|
||||||
|
SELECT queued.command_id, queued.target FROM queued;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(68,:'migration_sha_68');
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
-- Admin: end a stranded life (ADR-0182 section 18, 2026-10-29). A published life whose
|
||||||
|
-- reservation was never ended refuses every new birth for the account ("Existing cell is
|
||||||
|
-- already bound to this account"). The admin API first checks that no cell in the life's
|
||||||
|
-- region holds the account; this function then ends the reservation at the region's latest
|
||||||
|
-- commit, exactly as end_cellular_lives does, and records who did it and why. Unpublished
|
||||||
|
-- reservations are left to the region, which still holds them as queued births. The region's
|
||||||
|
-- checkpoints and history are unchanged.
|
||||||
|
|
||||||
|
CREATE TABLE evolution.admin_life_endings (
|
||||||
|
sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
world_id evolution.u64 NOT NULL,
|
||||||
|
account_id uuid NOT NULL,
|
||||||
|
request_id evolution.u64 NOT NULL,
|
||||||
|
ended_commit uuid NOT NULL,
|
||||||
|
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
|
||||||
|
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE TRIGGER admin_life_endings_immutable BEFORE UPDATE OR DELETE ON evolution.admin_life_endings
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
|
||||||
|
|
||||||
|
-- Returns true when this call ended the life, false when it was not open (already ended,
|
||||||
|
-- refused or cancelled). Raises EVL21 for an unknown or unpublished request.
|
||||||
|
CREATE FUNCTION evolution.admin_end_account_life_v1(p_world evolution.u64, p_account uuid,
|
||||||
|
p_request evolution.u64, p_subject text, p_reason text)
|
||||||
|
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE r evolution.life_reservations%ROWTYPE; latest uuid;
|
||||||
|
BEGIN
|
||||||
|
IF p_world IS NULL OR p_world = 0 OR p_account IS NULL OR p_request IS NULL OR p_request = 0 THEN
|
||||||
|
RAISE EXCEPTION 'invalid life ending' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
SELECT * INTO r FROM evolution.life_reservations x
|
||||||
|
WHERE x.world_id = p_world AND x.account_id = p_account AND x.request_id = p_request
|
||||||
|
FOR UPDATE;
|
||||||
|
IF NOT FOUND OR NOT EXISTS (SELECT 1 FROM evolution.primitive_life_bindings b
|
||||||
|
WHERE b.world_id = p_world AND b.account_id = p_account AND b.request_id = p_request) THEN
|
||||||
|
RAISE EXCEPTION 'no published life for this request' USING ERRCODE = 'EVL21';
|
||||||
|
END IF;
|
||||||
|
IF r.rejection <> 0 OR r.ended_commit IS NOT NULL THEN
|
||||||
|
RETURN false;
|
||||||
|
END IF;
|
||||||
|
SELECT c.commit_id INTO latest FROM evolution.region_commits c
|
||||||
|
WHERE c.world_id = p_world AND c.region_id = r.region_id
|
||||||
|
ORDER BY c.commit_sequence DESC LIMIT 1;
|
||||||
|
IF latest IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'region has no commit' USING ERRCODE = 'EVL21';
|
||||||
|
END IF;
|
||||||
|
UPDATE evolution.life_reservations x SET ended_commit = latest
|
||||||
|
WHERE x.world_id = p_world AND x.account_id = p_account AND x.request_id = p_request;
|
||||||
|
INSERT INTO evolution.admin_life_endings(world_id, account_id, request_id, ended_commit,
|
||||||
|
author_subject, reason)
|
||||||
|
VALUES (p_world, p_account, p_request, latest, p_subject, coalesce(p_reason, ''));
|
||||||
|
RETURN true;
|
||||||
|
END $$;
|
||||||
|
REVOKE ALL ON FUNCTION evolution.admin_end_account_life_v1(evolution.u64, uuid, evolution.u64,
|
||||||
|
text, text) FROM PUBLIC;
|
||||||
|
|
||||||
|
-- A region refuses a birth whose account still holds a cell in its state (life_exists) and
|
||||||
|
-- records that refusal as existing_life (4). Schema 15 accepted only reasons 1..3, so the
|
||||||
|
-- refusal was never recorded: the reservation stayed open and unpublished, and refused every
|
||||||
|
-- later birth for the account. Schema 17 already let the column hold 4.
|
||||||
|
CREATE OR REPLACE FUNCTION evolution.reject_primitive_life(p_world evolution.u64,
|
||||||
|
p_region evolution.u64, p_holder uuid, p_epoch evolution.u64, p_account uuid,
|
||||||
|
p_generation evolution.u64, p_request evolution.u64, p_reason smallint)
|
||||||
|
RETURNS smallint LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||||
|
DECLARE r evolution.life_reservations%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
IF p_request IS NULL OR p_request = 0 OR p_reason IS NULL OR p_reason NOT BETWEEN 1 AND 4 THEN
|
||||||
|
RAISE EXCEPTION 'invalid life rejection' USING ERRCODE = '22023';
|
||||||
|
END IF;
|
||||||
|
PERFORM evolution.check_life_control(p_world, p_region, p_holder, p_epoch, p_account, p_generation);
|
||||||
|
SELECT * INTO r FROM evolution.life_reservations x
|
||||||
|
WHERE x.world_id = p_world AND x.account_id = p_account AND x.request_id = p_request FOR UPDATE;
|
||||||
|
IF NOT FOUND OR r.region_id <> p_region THEN
|
||||||
|
RAISE EXCEPTION 'life reservation not owned' USING ERRCODE = 'EVL04';
|
||||||
|
END IF;
|
||||||
|
IF r.rejection <> 0 THEN RETURN r.rejection; END IF;
|
||||||
|
UPDATE evolution.life_reservations SET rejection = p_reason
|
||||||
|
WHERE world_id = p_world AND account_id = p_account AND request_id = p_request;
|
||||||
|
RETURN p_reason;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(69,:'migration_sha_69');
|
||||||
+182
-6
@@ -137,6 +137,14 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution')
|
|||||||
SELECT :'history_v58' || ',59:' || :'migration_sha_59' AS history_v59 \gset
|
SELECT :'history_v58' || ',59:' || :'migration_sha_59' AS history_v59 \gset
|
||||||
SELECT :'history_v59' || ',60:' || :'migration_sha_60' AS history_v60 \gset
|
SELECT :'history_v59' || ',60:' || :'migration_sha_60' AS history_v60 \gset
|
||||||
SELECT :'history_v60' || ',61:' || :'migration_sha_61' AS history_v61 \gset
|
SELECT :'history_v60' || ',61:' || :'migration_sha_61' AS history_v61 \gset
|
||||||
|
SELECT :'history_v61' || ',62:' || :'migration_sha_62' AS history_v62 \gset
|
||||||
|
SELECT :'history_v62' || ',63:' || :'migration_sha_63' AS history_v63 \gset
|
||||||
|
SELECT :'history_v63' || ',64:' || :'migration_sha_64' AS history_v64 \gset
|
||||||
|
SELECT :'history_v64' || ',65:' || :'migration_sha_65' AS history_v65 \gset
|
||||||
|
SELECT :'history_v65' || ',66:' || :'migration_sha_66' AS history_v66 \gset
|
||||||
|
SELECT :'history_v66' || ',67:' || :'migration_sha_67' AS history_v67 \gset
|
||||||
|
SELECT :'history_v67' || ',68:' || :'migration_sha_68' AS history_v68 \gset
|
||||||
|
SELECT :'history_v68' || ',69:' || :'migration_sha_69' AS history_v69 \gset
|
||||||
SELECT :'history' = :'history_v22' AS at_v22,
|
SELECT :'history' = :'history_v22' AS at_v22,
|
||||||
:'history' = :'history_v23' AS at_v23,
|
:'history' = :'history_v23' AS at_v23,
|
||||||
:'history' = :'history_v24' AS at_v24,
|
:'history' = :'history_v24' AS at_v24,
|
||||||
@@ -176,8 +184,24 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution')
|
|||||||
:'history' = :'history_v58' AS at_v58,
|
:'history' = :'history_v58' AS at_v58,
|
||||||
:'history' = :'history_v59' AS at_v59,
|
:'history' = :'history_v59' AS at_v59,
|
||||||
:'history' = :'history_v60' AS at_v60,
|
:'history' = :'history_v60' AS at_v60,
|
||||||
:'history' = :'history_v61' AS at_v61 \gset
|
:'history' = :'history_v61' AS at_v61,
|
||||||
\if :at_v61
|
:'history' = :'history_v62' AS at_v62,
|
||||||
|
:'history' = :'history_v63' AS at_v63,
|
||||||
|
:'history' = :'history_v64' AS at_v64,
|
||||||
|
:'history' = :'history_v65' AS at_v65,
|
||||||
|
:'history' = :'history_v66' AS at_v66,
|
||||||
|
:'history' = :'history_v67' AS at_v67,
|
||||||
|
:'history' = :'history_v68' AS at_v68,
|
||||||
|
:'history' = :'history_v69' AS at_v69 \gset
|
||||||
|
\if :at_v69
|
||||||
|
\elif :at_v68
|
||||||
|
\elif :at_v67
|
||||||
|
\elif :at_v66
|
||||||
|
\elif :at_v65
|
||||||
|
\elif :at_v64
|
||||||
|
\elif :at_v63
|
||||||
|
\elif :at_v62
|
||||||
|
\elif :at_v61
|
||||||
\elif :at_v60
|
\elif :at_v60
|
||||||
\elif :at_v59
|
\elif :at_v59
|
||||||
\elif :at_v58
|
\elif :at_v58
|
||||||
@@ -593,7 +617,15 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24,
|
|||||||
coalesce(max(version), 0) = 58 AS at_v58,
|
coalesce(max(version), 0) = 58 AS at_v58,
|
||||||
coalesce(max(version), 0) = 59 AS at_v59,
|
coalesce(max(version), 0) = 59 AS at_v59,
|
||||||
coalesce(max(version), 0) = 60 AS at_v60,
|
coalesce(max(version), 0) = 60 AS at_v60,
|
||||||
coalesce(max(version), 0) = 61 AS at_v61
|
coalesce(max(version), 0) = 61 AS at_v61,
|
||||||
|
coalesce(max(version), 0) = 62 AS at_v62,
|
||||||
|
coalesce(max(version), 0) = 63 AS at_v63,
|
||||||
|
coalesce(max(version), 0) = 64 AS at_v64,
|
||||||
|
coalesce(max(version), 0) = 65 AS at_v65,
|
||||||
|
coalesce(max(version), 0) = 66 AS at_v66,
|
||||||
|
coalesce(max(version), 0) = 67 AS at_v67,
|
||||||
|
coalesce(max(version), 0) = 68 AS at_v68,
|
||||||
|
coalesce(max(version), 0) = 69 AS at_v69
|
||||||
FROM evolution.schema_migrations \gset
|
FROM evolution.schema_migrations \gset
|
||||||
\if :at_v24
|
\if :at_v24
|
||||||
\ir 0025_cellular_v2_bundle.sql
|
\ir 0025_cellular_v2_bundle.sql
|
||||||
@@ -823,6 +855,14 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24,
|
|||||||
\elif :at_v59
|
\elif :at_v59
|
||||||
\elif :at_v60
|
\elif :at_v60
|
||||||
\elif :at_v61
|
\elif :at_v61
|
||||||
|
\elif :at_v62
|
||||||
|
\elif :at_v63
|
||||||
|
\elif :at_v64
|
||||||
|
\elif :at_v65
|
||||||
|
\elif :at_v66
|
||||||
|
\elif :at_v67
|
||||||
|
\elif :at_v68
|
||||||
|
\elif :at_v69
|
||||||
\else
|
\else
|
||||||
\echo 'Unknown or changed migration history after v43'
|
\echo 'Unknown or changed migration history after v43'
|
||||||
DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$;
|
DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$;
|
||||||
@@ -899,6 +939,38 @@ SELECT coalesce(max(version), 0) = 60 AS needs_v61 FROM evolution.schema_migrati
|
|||||||
\if :needs_v61
|
\if :needs_v61
|
||||||
\ir 0061_admin_read_views.sql
|
\ir 0061_admin_read_views.sql
|
||||||
\endif
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 61 AS needs_v62 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v62
|
||||||
|
\ir 0062_session_windows.sql
|
||||||
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 62 AS needs_v63 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v63
|
||||||
|
\ir 0063_admin_commands.sql
|
||||||
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 63 AS needs_v64 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v64
|
||||||
|
\ir 0064_account_admin.sql
|
||||||
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 64 AS needs_v65 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v65
|
||||||
|
\ir 0065_admin_schedules.sql
|
||||||
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 65 AS needs_v66 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v66
|
||||||
|
\ir 0066_tuning_revisions.sql
|
||||||
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 66 AS needs_v67 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v67
|
||||||
|
\ir 0067_admin_take_and_cull.sql
|
||||||
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 67 AS needs_v68 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v68
|
||||||
|
\ir 0068_larger_region_ticks.sql
|
||||||
|
\endif
|
||||||
|
SELECT coalesce(max(version), 0) = 68 AS needs_v69 FROM evolution.schema_migrations \gset
|
||||||
|
\if :needs_v69
|
||||||
|
\ir 0069_admin_end_life.sql
|
||||||
|
\endif
|
||||||
-- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes
|
-- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes
|
||||||
-- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC
|
-- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC
|
||||||
-- grants or SET-able memberships would bypass the fenced functions. Checks the
|
-- grants or SET-able memberships would bypass the fenced functions. Checks the
|
||||||
@@ -972,9 +1044,9 @@ BEGIN
|
|||||||
('evolution.load_cellular_mutation_publications(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid),
|
('evolution.load_cellular_mutation_publications(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid),
|
||||||
('evolution.end_cellular_lives(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,bytea)'::regprocedure::oid),
|
('evolution.end_cellular_lives(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,bytea)'::regprocedure::oid),
|
||||||
('evolution.issue_account_grant(evolution.u64,text,text)'::regprocedure::oid),
|
('evolution.issue_account_grant(evolution.u64,text,text)'::regprocedure::oid),
|
||||||
('evolution.admin_accounts_v1(evolution.u64)'::regprocedure::oid),
|
('evolution.load_session_window_v1(evolution.u64,evolution.u64)'::regprocedure::oid),
|
||||||
('evolution.admin_account_lives_v1(evolution.u64,uuid)'::regprocedure::oid),
|
('evolution.load_pending_admin_commands_v1(evolution.u64,evolution.u64)'::regprocedure::oid),
|
||||||
('evolution.admin_regions_v1(evolution.u64)'::regprocedure::oid),
|
('evolution.load_tuning_revision_v1(evolution.u64,bigint)'::regprocedure::oid),
|
||||||
('evolution.revoke_account_grants(evolution.u64,text,text)'::regprocedure::oid),
|
('evolution.revoke_account_grants(evolution.u64,text,text)'::regprocedure::oid),
|
||||||
('evolution.load_cellular_publication_actions(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid),
|
('evolution.load_cellular_publication_actions(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid),
|
||||||
('evolution.load_cellular_publication_births(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid),
|
('evolution.load_cellular_publication_births(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid),
|
||||||
@@ -1029,4 +1101,108 @@ BEGIN
|
|||||||
RAISE EXCEPTION 'runtime role audit failed: %', bad;
|
RAISE EXCEPTION 'runtime role audit failed: %', bad;
|
||||||
END IF;
|
END IF;
|
||||||
END $$;
|
END $$;
|
||||||
|
-- ADR-0182: the admin API's group role, when configured (EVO_PG_ADMIN_ROLE). Every run
|
||||||
|
-- grants it exactly the admin functions and audits it like the runtime group; it shares no
|
||||||
|
-- membership with the runtime group.
|
||||||
|
\if :{?admin_role}
|
||||||
|
GRANT USAGE ON SCHEMA evolution TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_accounts_v1(evolution.u64) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_account_lives_v1(evolution.u64, uuid) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_regions_v1(evolution.u64) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.load_session_window_v1(evolution.u64, evolution.u64)
|
||||||
|
TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_session_windows_v1(evolution.u64, evolution.u64)
|
||||||
|
TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_set_session_window_v1(evolution.u64, evolution.u64,
|
||||||
|
integer, text, text) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_enqueue_command_v1(evolution.u64, evolution.u64, integer,
|
||||||
|
integer, evolution.u64, evolution.u64, evolution.u64, evolution.u64, evolution.u64,
|
||||||
|
evolution.u64, text, text) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_commands_v1(evolution.u64, evolution.u64)
|
||||||
|
TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_set_account_ban_v1(evolution.u64, uuid, boolean, text,
|
||||||
|
text) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_logout_account_v1(evolution.u64, uuid) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_end_account_life_v1(evolution.u64, uuid, evolution.u64,
|
||||||
|
text, text) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_account_status_v1(evolution.u64) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_account_bans_v1(uuid) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_set_schedule_v1(evolution.u64, evolution.u64, bigint,
|
||||||
|
integer, integer, evolution.u64, evolution.u64, evolution.u64, evolution.u64, evolution.u64,
|
||||||
|
integer, boolean, text, text) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_schedules_v1(evolution.u64, evolution.u64)
|
||||||
|
TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_set_tuning_v1(evolution.u64, text, bytea, bigint[], text,
|
||||||
|
text) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_tuning_revisions_v1(evolution.u64) TO :"admin_role";
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.admin_tuning_text_v1(evolution.u64, bigint) TO :"admin_role";
|
||||||
|
SELECT pg_catalog.set_config('evolution.admin_role', :'admin_role', true);
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
admin oid := (SELECT r.oid FROM pg_catalog.pg_roles r
|
||||||
|
WHERE r.rolname = pg_catalog.current_setting('evolution.admin_role'));
|
||||||
|
runtime oid := (SELECT r.oid FROM pg_catalog.pg_roles r
|
||||||
|
WHERE r.rolname = pg_catalog.current_setting('evolution.runtime_role'));
|
||||||
|
bad text;
|
||||||
|
BEGIN
|
||||||
|
IF admin IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'admin role does not exist';
|
||||||
|
END IF;
|
||||||
|
WITH RECURSIVE closure(oid) AS (
|
||||||
|
SELECT admin
|
||||||
|
UNION
|
||||||
|
SELECT m.member FROM pg_catalog.pg_auth_members m JOIN closure c ON m.roleid = c.oid
|
||||||
|
), fenced(oid) AS (VALUES
|
||||||
|
('evolution.admin_accounts_v1(evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.admin_account_lives_v1(evolution.u64,uuid)'::regprocedure::oid),
|
||||||
|
('evolution.admin_regions_v1(evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.load_session_window_v1(evolution.u64,evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.admin_session_windows_v1(evolution.u64,evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.admin_set_session_window_v1(evolution.u64,evolution.u64,integer,text,text)'::regprocedure::oid),
|
||||||
|
('evolution.admin_enqueue_command_v1(evolution.u64,evolution.u64,integer,integer,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,text,text)'::regprocedure::oid),
|
||||||
|
('evolution.admin_commands_v1(evolution.u64,evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.admin_set_account_ban_v1(evolution.u64,uuid,boolean,text,text)'::regprocedure::oid),
|
||||||
|
('evolution.admin_logout_account_v1(evolution.u64,uuid)'::regprocedure::oid),
|
||||||
|
('evolution.admin_end_account_life_v1(evolution.u64,uuid,evolution.u64,text,text)'::regprocedure::oid),
|
||||||
|
('evolution.admin_account_status_v1(evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.admin_account_bans_v1(uuid)'::regprocedure::oid),
|
||||||
|
('evolution.admin_set_schedule_v1(evolution.u64,evolution.u64,bigint,integer,integer,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,integer,boolean,text,text)'::regprocedure::oid),
|
||||||
|
('evolution.admin_schedules_v1(evolution.u64,evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.admin_set_tuning_v1(evolution.u64,text,bytea,bigint[],text,text)'::regprocedure::oid),
|
||||||
|
('evolution.admin_tuning_revisions_v1(evolution.u64)'::regprocedure::oid),
|
||||||
|
('evolution.admin_tuning_text_v1(evolution.u64,bigint)'::regprocedure::oid)
|
||||||
|
), violations(reason) AS (
|
||||||
|
SELECT 'admin role is the runtime role' WHERE admin = runtime
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'privileged attribute or owner identity' FROM pg_catalog.pg_roles r
|
||||||
|
JOIN closure c ON c.oid = r.oid
|
||||||
|
WHERE r.rolsuper OR r.rolcreaterole OR r.rolcreatedb OR r.rolreplication
|
||||||
|
OR r.rolbypassrls OR r.rolname = current_user
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'membership outside the admin group' FROM pg_catalog.pg_auth_members m
|
||||||
|
JOIN closure c ON c.oid = m.member
|
||||||
|
WHERE m.roleid NOT IN (SELECT oid FROM closure)
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'table privilege in evolution schema' FROM closure c
|
||||||
|
CROSS JOIN pg_catalog.pg_class t
|
||||||
|
WHERE t.relnamespace = 'evolution'::regnamespace AND t.relkind IN ('r', 'p', 'v', 'm', 'S')
|
||||||
|
AND pg_catalog.has_table_privilege(c.oid, t.oid,
|
||||||
|
'SELECT,INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER,MAINTAIN')
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'CREATE on schema or database' FROM closure c
|
||||||
|
WHERE pg_catalog.has_schema_privilege(c.oid, 'evolution', 'CREATE')
|
||||||
|
OR pg_catalog.has_database_privilege(c.oid, pg_catalog.current_database(), 'CREATE')
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'EXECUTE outside the admin function set' FROM closure c
|
||||||
|
CROSS JOIN pg_catalog.pg_proc p
|
||||||
|
WHERE p.pronamespace = 'evolution'::regnamespace
|
||||||
|
AND p.oid NOT IN (SELECT oid FROM fenced)
|
||||||
|
AND pg_catalog.has_function_privilege(c.oid, p.oid, 'EXECUTE')
|
||||||
|
)
|
||||||
|
SELECT pg_catalog.string_agg(DISTINCT v.reason, '; ') INTO bad FROM violations v;
|
||||||
|
IF bad IS NOT NULL THEN
|
||||||
|
RAISE EXCEPTION 'admin role audit failed: %', bad;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
\endif
|
||||||
COMMIT;
|
COMMIT;
|
||||||
|
|||||||
@@ -48,6 +48,9 @@ constexpr std::array fields{
|
|||||||
Field{"spent.drip_interval_ticks", &CellularRevampTuning::spent_drip_interval_ticks, 0, 72'000},
|
Field{"spent.drip_interval_ticks", &CellularRevampTuning::spent_drip_interval_ticks, 0, 72'000},
|
||||||
Field{"spent.drip_bubble_pj", &CellularRevampTuning::spent_drip_bubble_pj, 0, amount_limit},
|
Field{"spent.drip_bubble_pj", &CellularRevampTuning::spent_drip_bubble_pj, 0, amount_limit},
|
||||||
Field{"spent.drip_bubble_fg", &CellularRevampTuning::spent_drip_bubble_fg, 0, amount_limit},
|
Field{"spent.drip_bubble_fg", &CellularRevampTuning::spent_drip_bubble_fg, 0, amount_limit},
|
||||||
|
Field{"spent.heat_recycle_per_mille", &CellularRevampTuning::spent_heat_recycle_per_mille, 0,
|
||||||
|
1'000},
|
||||||
|
Field{"spent.drip_absorb", &CellularRevampTuning::spent_drip_absorb, 0, 1},
|
||||||
Field{"mutation.options", &CellularRevampTuning::mutation_options, 1, 10},
|
Field{"mutation.options", &CellularRevampTuning::mutation_options, 1, 10},
|
||||||
Field{"mutation.floor_ppm", &CellularRevampTuning::mutation_floor_ppm, 0, 1'000'000},
|
Field{"mutation.floor_ppm", &CellularRevampTuning::mutation_floor_ppm, 0, 1'000'000},
|
||||||
Field{"mutation.cap_ppm", &CellularRevampTuning::mutation_cap_ppm, 1, 1'000'000},
|
Field{"mutation.cap_ppm", &CellularRevampTuning::mutation_cap_ppm, 1, 1'000'000},
|
||||||
@@ -83,7 +86,8 @@ constexpr std::array fields{
|
|||||||
amount_limit},
|
amount_limit},
|
||||||
Field{"reproduction.bud_fee_scale_percent",
|
Field{"reproduction.bud_fee_scale_percent",
|
||||||
&CellularRevampTuning::reproduction_bud_fee_scale_percent, 0, 100},
|
&CellularRevampTuning::reproduction_bud_fee_scale_percent, 0, 100},
|
||||||
Field{"reproduction.organism_cap", &CellularRevampTuning::reproduction_organism_cap, 1, 256},
|
Field{"reproduction.organism_cap", &CellularRevampTuning::reproduction_organism_cap, 1, 4'096},
|
||||||
|
Field{"reproduction.wildlife_cap", &CellularRevampTuning::reproduction_wildlife_cap, 0, 4'096},
|
||||||
Field{"organism.load_per_mille", &CellularRevampTuning::organism_load_per_mille, 0, 10'000},
|
Field{"organism.load_per_mille", &CellularRevampTuning::organism_load_per_mille, 0, 10'000},
|
||||||
Field{"organism.emerge_members", &CellularRevampTuning::organism_emerge_members, 2, 10'000},
|
Field{"organism.emerge_members", &CellularRevampTuning::organism_emerge_members, 2, 10'000},
|
||||||
Field{"organism.emerge_mass_fg", &CellularRevampTuning::organism_emerge_mass_fg, 0,
|
Field{"organism.emerge_mass_fg", &CellularRevampTuning::organism_emerge_mass_fg, 0,
|
||||||
@@ -257,6 +261,9 @@ parse_cellular_revamp_tuning(std::string_view text) {
|
|||||||
if (!seen.at(index) && fields.at(index).key != "playtest.starting_wildlife_cells" &&
|
if (!seen.at(index) && fields.at(index).key != "playtest.starting_wildlife_cells" &&
|
||||||
fields.at(index).key != "feeding.collection_percent" &&
|
fields.at(index).key != "feeding.collection_percent" &&
|
||||||
fields.at(index).key != "feeding.split_evenly" &&
|
fields.at(index).key != "feeding.split_evenly" &&
|
||||||
|
fields.at(index).key != "spent.heat_recycle_per_mille" &&
|
||||||
|
fields.at(index).key != "spent.drip_absorb" &&
|
||||||
|
fields.at(index).key != "reproduction.wildlife_cap" &&
|
||||||
fields.at(index).key != "reproduction.safety_version" &&
|
fields.at(index).key != "reproduction.safety_version" &&
|
||||||
fields.at(index).key != "body.growth_reserve_seconds" &&
|
fields.at(index).key != "body.growth_reserve_seconds" &&
|
||||||
fields.at(index).key != "reproduction.split_launch_um_per_s")
|
fields.at(index).key != "reproduction.split_launch_um_per_s")
|
||||||
@@ -265,6 +272,9 @@ parse_cellular_revamp_tuning(std::string_view text) {
|
|||||||
if (tuning.version != cellular_revamp_tuning_version)
|
if (tuning.version != cellular_revamp_tuning_version)
|
||||||
return std::unexpected{
|
return std::unexpected{
|
||||||
error(CellularTuningErrorKind::unsupported_version, 0, "tuning.version")};
|
error(CellularTuningErrorKind::unsupported_version, 0, "tuning.version")};
|
||||||
|
if (tuning.reproduction_wildlife_cap > tuning.reproduction_organism_cap)
|
||||||
|
return std::unexpected{
|
||||||
|
error(CellularTuningErrorKind::inconsistent, 0, "reproduction.wildlife_cap")};
|
||||||
if (tuning.playtest_starting_wildlife_cells >= tuning.reproduction_organism_cap)
|
if (tuning.playtest_starting_wildlife_cells >= tuning.reproduction_organism_cap)
|
||||||
return std::unexpected{
|
return std::unexpected{
|
||||||
error(CellularTuningErrorKind::inconsistent, 0, "playtest.starting_wildlife_cells")};
|
error(CellularTuningErrorKind::inconsistent, 0, "playtest.starting_wildlife_cells")};
|
||||||
|
|||||||
@@ -15,6 +15,16 @@
|
|||||||
|
|
||||||
namespace evo::persistence {
|
namespace evo::persistence {
|
||||||
namespace {
|
namespace {
|
||||||
|
// ADR-0182: a batch's tuning adoption resolves to its successor's rules after their SHA-256
|
||||||
|
// matches the command's digest.
|
||||||
|
server::CellularTuningResolver successor_tuning(const server::CellularLives& successor) {
|
||||||
|
return server::cellular_successor_tuning(
|
||||||
|
successor,
|
||||||
|
[](std::span<const std::uint8_t> bytes, const std::array<std::uint8_t, 32>& digest) {
|
||||||
|
const auto computed = sha256(bytes);
|
||||||
|
return computed && std::ranges::equal(*computed, digest);
|
||||||
|
});
|
||||||
|
}
|
||||||
using std::chrono::milliseconds;
|
using std::chrono::milliseconds;
|
||||||
|
|
||||||
std::uint64_t input_tick(const server::CellularActionRecord& action) {
|
std::uint64_t input_tick(const server::CellularActionRecord& action) {
|
||||||
@@ -149,7 +159,7 @@ bool prepared_is_canonical(const CellularPreparedCommit& prepared,
|
|||||||
const auto encoded_trace = server::encode_cellular_batch(trace);
|
const auto encoded_trace = server::encode_cellular_batch(trace);
|
||||||
const auto digest = sha256(prepared.trace);
|
const auto digest = sha256(prepared.trace);
|
||||||
const bool trace_version_matches =
|
const bool trace_version_matches =
|
||||||
trace.format_version == cellular_checkpoint_trace_format(manifest.cellular_versions);
|
cellular_checkpoint_trace_admits(manifest.cellular_versions, trace.format_version);
|
||||||
return manifest.profile == CheckpointProfile::cellular_lives_v1 && trace_version_matches &&
|
return manifest.profile == CheckpointProfile::cellular_lives_v1 && trace_version_matches &&
|
||||||
manifest.key == prepared.key && manifest.commit == prepared.commit &&
|
manifest.key == prepared.key && manifest.commit == prepared.commit &&
|
||||||
manifest.sequence > 0 && manifest.batch.trace_bytes == prepared.trace.size() && digest &&
|
manifest.sequence > 0 && manifest.batch.trace_bytes == prepared.trace.size() && digest &&
|
||||||
@@ -561,7 +571,9 @@ publish_cellular_batch(Postgres& db, const FilesystemObjectStore& objects, const
|
|||||||
const auto previous = decode_manifest(predecessor.manifest);
|
const auto previous = decode_manifest(predecessor.manifest);
|
||||||
const auto predecessor_digest = sha256(predecessor.manifest);
|
const auto predecessor_digest = sha256(predecessor.manifest);
|
||||||
auto committed_batch = batch;
|
auto committed_batch = batch;
|
||||||
if (previous)
|
if (previous && !(committed_batch.format_version == server::cellular_batch_admin_format &&
|
||||||
|
cellular_checkpoint_trace_admits(previous->cellular_versions,
|
||||||
|
committed_batch.format_version)))
|
||||||
committed_batch.format_version =
|
committed_batch.format_version =
|
||||||
cellular_checkpoint_trace_format(previous->cellular_versions);
|
cellular_checkpoint_trace_format(previous->cellular_versions);
|
||||||
const auto trace = server::encode_cellular_batch(committed_batch);
|
const auto trace = server::encode_cellular_batch(committed_batch);
|
||||||
@@ -599,7 +611,9 @@ publish_cellular_batch(Postgres& db, const FilesystemObjectStore& objects, const
|
|||||||
if (!base)
|
if (!base)
|
||||||
return std::unexpected{failure(PublicationError::predecessor)};
|
return std::unexpected{failure(PublicationError::predecessor)};
|
||||||
std::vector<server::CellularMutationOutcome> outcomes;
|
std::vector<server::CellularMutationOutcome> outcomes;
|
||||||
auto replay = server::replay_cellular_batch(**base, committed_batch, outcomes);
|
std::vector<server::CellularAdminResult> admin_results;
|
||||||
|
auto replay = server::replay_cellular_batch(**base, committed_batch, outcomes, admin_results,
|
||||||
|
successor_tuning(candidate));
|
||||||
const auto payload = candidate.snapshot();
|
const auto payload = candidate.snapshot();
|
||||||
if (!replay || (*replay)->snapshot() != payload ||
|
if (!replay || (*replay)->snapshot() != payload ||
|
||||||
!server::match_cellular_actions_to_trace(**base, committed_batch, actions) ||
|
!server::match_cellular_actions_to_trace(**base, committed_batch, actions) ||
|
||||||
@@ -834,7 +848,7 @@ recover_cellular_loaded(Postgres& db, const FilesystemObjectStore& objects, Regi
|
|||||||
auto trace = server::decode_cellular_batch(*trace_bytes);
|
auto trace = server::decode_cellular_batch(*trace_bytes);
|
||||||
if (!trace)
|
if (!trace)
|
||||||
return fail_with(RecoveryError::tail);
|
return fail_with(RecoveryError::tail);
|
||||||
if (trace->format_version != cellular_checkpoint_trace_format(manifest->cellular_versions))
|
if (!cellular_checkpoint_trace_admits(manifest->cellular_versions, trace->format_version))
|
||||||
return fail_with(RecoveryError::tail);
|
return fail_with(RecoveryError::tail);
|
||||||
if (trace->header.world != key.world || trace->header.region != key.region ||
|
if (trace->header.world != key.world || trace->header.region != key.region ||
|
||||||
trace->header.frame != manifest->frame ||
|
trace->header.frame != manifest->frame ||
|
||||||
@@ -884,7 +898,19 @@ recover_cellular_loaded(Postgres& db, const FilesystemObjectStore& objects, Regi
|
|||||||
!server::match_cellular_actions_to_trace(**base, *trace, *batch_actions))
|
!server::match_cellular_actions_to_trace(**base, *trace, *batch_actions))
|
||||||
return fail_with(RecoveryError::history);
|
return fail_with(RecoveryError::history);
|
||||||
std::vector<server::CellularMutationOutcome> outcomes;
|
std::vector<server::CellularMutationOutcome> outcomes;
|
||||||
auto replay = server::replay_cellular_batch(**base, *trace, outcomes);
|
std::vector<server::CellularAdminResult> admin_results;
|
||||||
|
// ADR-0182: an adoption resolves from the stored successor (trace 5 only).
|
||||||
|
server::CellularTuningResolver tuning;
|
||||||
|
std::unique_ptr<server::CellularLives> successor;
|
||||||
|
if (trace->format_version == server::cellular_batch_admin_format) {
|
||||||
|
auto restored = restore_cellular_payload(*payload, *manifest);
|
||||||
|
if (!restored)
|
||||||
|
return fail_with(RecoveryError::tail);
|
||||||
|
successor = std::move(*restored);
|
||||||
|
tuning = successor_tuning(*successor);
|
||||||
|
}
|
||||||
|
auto replay =
|
||||||
|
server::replay_cellular_batch(**base, *trace, outcomes, admin_results, tuning);
|
||||||
if (!replay || (*replay)->snapshot() != *payload)
|
if (!replay || (*replay)->snapshot() != *payload)
|
||||||
return fail_with(RecoveryError::tail);
|
return fail_with(RecoveryError::tail);
|
||||||
|
|
||||||
|
|||||||
@@ -155,12 +155,12 @@ bool structural(const CheckpointManifest& m) noexcept {
|
|||||||
const auto cellular_v2_max =
|
const auto cellular_v2_max =
|
||||||
server::cellular_batch_header_bytes +
|
server::cellular_batch_header_bytes +
|
||||||
ticks * (server::cellular_batch_v2_tick_header_bytes +
|
ticks * (server::cellular_batch_v2_tick_header_bytes +
|
||||||
biology::max_cellular_tick_lives *
|
biology::max_cellular_frozen_lives *
|
||||||
(server::cellular_batch_intent_bytes + server::cellular_batch_birth_bytes));
|
(server::cellular_batch_intent_bytes + server::cellular_batch_birth_bytes));
|
||||||
const auto cellular_legacy_max =
|
const auto cellular_legacy_max =
|
||||||
server::cellular_batch_header_bytes +
|
server::cellular_batch_header_bytes +
|
||||||
ticks * (server::cellular_batch_v1_tick_header_bytes +
|
ticks * (server::cellular_batch_v1_tick_header_bytes +
|
||||||
biology::max_cellular_tick_lives * server::cellular_batch_intent_bytes);
|
biology::max_cellular_frozen_lives * server::cellular_batch_intent_bytes);
|
||||||
const bool cellular_current_trace =
|
const bool cellular_current_trace =
|
||||||
b.trace_bytes >= cellular_current_min && b.trace_bytes <= cellular_max &&
|
b.trace_bytes >= cellular_current_min && b.trace_bytes <= cellular_max &&
|
||||||
(b.trace_bytes - cellular_current_min) % sizeof(std::uint64_t) == 0;
|
(b.trace_bytes - cellular_current_min) % sizeof(std::uint64_t) == 0;
|
||||||
|
|||||||
@@ -987,8 +987,9 @@ std::expected<LifeRefusal, LifeReservationFailure>
|
|||||||
reject_primitive_life(Postgres& db, RegionKey key, const LeaseGrant& lease, const Uuid& account,
|
reject_primitive_life(Postgres& db, RegionKey key, const LeaseGrant& lease, const Uuid& account,
|
||||||
std::uint64_t generation, std::uint64_t request_id, LifeRefusal reason,
|
std::uint64_t generation, std::uint64_t request_id, LifeRefusal reason,
|
||||||
milliseconds timeout) {
|
milliseconds timeout) {
|
||||||
|
// Schema 69: existing_life (4) too, a region refusing a birth whose account holds a cell.
|
||||||
const auto value = static_cast<std::uint8_t>(reason);
|
const auto value = static_cast<std::uint8_t>(reason);
|
||||||
if (value < 1 || value > 3)
|
if (value < 1 || value > 4)
|
||||||
return std::unexpected{LifeReservationFailure{LifeReservationError::invalid, {}}};
|
return std::unexpected{LifeReservationFailure{LifeReservationError::invalid, {}}};
|
||||||
const auto base = control_parameters(key, lease, account, generation);
|
const auto base = control_parameters(key, lease, account, generation);
|
||||||
const std::array<std::string, 8> p{base[0],
|
const std::array<std::string, 8> p{base[0],
|
||||||
@@ -1449,6 +1450,8 @@ AccountIdentityError identity_failure(const PgFailure& f) {
|
|||||||
return AccountIdentityError::unknown;
|
return AccountIdentityError::unknown;
|
||||||
if (f.kind == PgError::config || f.kind == PgError::bounds || state == "22023")
|
if (f.kind == PgError::config || f.kind == PgError::bounds || state == "22023")
|
||||||
return AccountIdentityError::invalid;
|
return AccountIdentityError::invalid;
|
||||||
|
if (state == "EVL20")
|
||||||
|
return AccountIdentityError::banned;
|
||||||
return AccountIdentityError::store;
|
return AccountIdentityError::store;
|
||||||
}
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|||||||
@@ -256,8 +256,8 @@ class JsonParser {
|
|||||||
std::size_t at_{};
|
std::size_t at_{};
|
||||||
};
|
};
|
||||||
|
|
||||||
std::optional<JsonValue> JsonValue::parse(std::string_view text) {
|
std::optional<JsonValue> JsonValue::parse(std::string_view text, std::size_t limit) {
|
||||||
if (text.size() > max_json_bytes)
|
if (text.size() > limit)
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
return JsonParser{text}.document();
|
return JsonParser{text}.document();
|
||||||
}
|
}
|
||||||
|
|||||||
+1029
-18
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,257 @@
|
|||||||
|
#include "evo/server/admin/https_client.hpp"
|
||||||
|
|
||||||
|
#include <openssl/err.h>
|
||||||
|
#include <openssl/ssl.h>
|
||||||
|
#include <openssl/x509v3.h>
|
||||||
|
|
||||||
|
#include <cerrno>
|
||||||
|
#include <charconv>
|
||||||
|
#include <memory>
|
||||||
|
#include <netdb.h>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace evo::server::admin {
|
||||||
|
namespace {
|
||||||
|
using Clock = std::chrono::steady_clock;
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
bool wait(int fd, short events, Clock::time_point deadline) {
|
||||||
|
for (;;) {
|
||||||
|
const auto left =
|
||||||
|
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int connect_to(const std::string& host, std::uint16_t port, Clock::time_point deadline) {
|
||||||
|
addrinfo hints{};
|
||||||
|
hints.ai_family = AF_UNSPEC;
|
||||||
|
hints.ai_socktype = SOCK_STREAM;
|
||||||
|
addrinfo* found = nullptr;
|
||||||
|
const auto service = std::to_string(port);
|
||||||
|
if (::getaddrinfo(host.c_str(), service.c_str(), &hints, &found) != 0 || found == nullptr)
|
||||||
|
return -1;
|
||||||
|
const std::unique_ptr<addrinfo, decltype(&::freeaddrinfo)> results{found, ::freeaddrinfo};
|
||||||
|
for (const addrinfo* candidate = found; candidate != nullptr; candidate = candidate->ai_next) {
|
||||||
|
const int fd =
|
||||||
|
::socket(candidate->ai_family, candidate->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC,
|
||||||
|
candidate->ai_protocol);
|
||||||
|
if (fd < 0)
|
||||||
|
continue;
|
||||||
|
Socket socket{fd};
|
||||||
|
if (::connect(fd, candidate->ai_addr, candidate->ai_addrlen) != 0) {
|
||||||
|
int failure = 0;
|
||||||
|
socklen_t length = sizeof failure;
|
||||||
|
if (errno != EINPROGRESS || !wait(fd, POLLOUT, deadline) ||
|
||||||
|
::getsockopt(fd, SOL_SOCKET, SO_ERROR, &failure, &length) != 0 || failure != 0)
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
socket.fd = -1; // Handed to the caller.
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Waits for the TLS operation that just returned `result` to become possible again.
|
||||||
|
bool retry(SSL* ssl, int result, Clock::time_point deadline) {
|
||||||
|
const int fd = SSL_get_fd(ssl);
|
||||||
|
switch (SSL_get_error(ssl, result)) {
|
||||||
|
case SSL_ERROR_WANT_READ:
|
||||||
|
return wait(fd, POLLIN, deadline);
|
||||||
|
case SSL_ERROR_WANT_WRITE:
|
||||||
|
return wait(fd, POLLOUT, deadline);
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string lower(std::string_view text) {
|
||||||
|
std::string out(text);
|
||||||
|
for (auto& ch : out)
|
||||||
|
ch = static_cast<char>(ch >= 'A' && ch <= 'Z' ? ch - 'A' + 'a' : ch);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::optional<HttpsResponse> parse_http_response(std::string_view raw, std::size_t limit) {
|
||||||
|
const auto head_end = raw.find("\r\n\r\n");
|
||||||
|
if (head_end == std::string_view::npos || !raw.starts_with("HTTP/1."))
|
||||||
|
return std::nullopt;
|
||||||
|
const auto line_end = raw.find("\r\n");
|
||||||
|
const auto space = raw.find(' ');
|
||||||
|
if (space == std::string_view::npos || space + 4 > line_end)
|
||||||
|
return std::nullopt;
|
||||||
|
HttpsResponse response;
|
||||||
|
const auto code = raw.substr(space + 1, 3);
|
||||||
|
if (std::from_chars(code.data(), code.data() + code.size(), response.status).ec !=
|
||||||
|
std::errc{} ||
|
||||||
|
response.status < 100 || response.status > 599)
|
||||||
|
return std::nullopt;
|
||||||
|
std::optional<std::size_t> length;
|
||||||
|
bool chunked = false;
|
||||||
|
for (auto at = line_end + 2; at < head_end;) {
|
||||||
|
const auto end = raw.find("\r\n", at);
|
||||||
|
const auto header = raw.substr(at, end - at);
|
||||||
|
at = end + 2;
|
||||||
|
const auto colon = header.find(':');
|
||||||
|
if (colon == std::string_view::npos)
|
||||||
|
continue;
|
||||||
|
const auto name = lower(header.substr(0, colon));
|
||||||
|
auto value = header.substr(colon + 1);
|
||||||
|
while (!value.empty() && value.front() == ' ')
|
||||||
|
value.remove_prefix(1);
|
||||||
|
if (name == "content-length") {
|
||||||
|
std::size_t bytes{};
|
||||||
|
if (std::from_chars(value.data(), value.data() + value.size(), bytes).ec != std::errc{})
|
||||||
|
return std::nullopt;
|
||||||
|
length = bytes;
|
||||||
|
} else if (name == "transfer-encoding") {
|
||||||
|
chunked = lower(value).find("chunked") != std::string::npos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto body = raw.substr(head_end + 4);
|
||||||
|
if (chunked) {
|
||||||
|
std::string out;
|
||||||
|
for (;;) {
|
||||||
|
const auto end = body.find("\r\n");
|
||||||
|
if (end == std::string_view::npos)
|
||||||
|
return std::nullopt;
|
||||||
|
std::size_t size{};
|
||||||
|
const auto digits = body.substr(0, std::min(end, body.find(';')));
|
||||||
|
if (std::from_chars(digits.data(), digits.data() + digits.size(), size, 16).ec !=
|
||||||
|
std::errc{})
|
||||||
|
return std::nullopt;
|
||||||
|
body.remove_prefix(end + 2);
|
||||||
|
if (size == 0)
|
||||||
|
break;
|
||||||
|
if (body.size() < size + 2 || body.substr(size, 2) != "\r\n" ||
|
||||||
|
out.size() + size > limit)
|
||||||
|
return std::nullopt;
|
||||||
|
out.append(body.substr(0, size));
|
||||||
|
body.remove_prefix(size + 2);
|
||||||
|
}
|
||||||
|
response.body = std::move(out);
|
||||||
|
} else {
|
||||||
|
if (length && *length > body.size())
|
||||||
|
return std::nullopt;
|
||||||
|
response.body = std::string(length ? body.substr(0, *length) : body);
|
||||||
|
}
|
||||||
|
if (response.body.size() > limit)
|
||||||
|
return std::nullopt;
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<HttpsBase> parse_https_base(std::string_view url) {
|
||||||
|
if (url.starts_with("https://"))
|
||||||
|
url.remove_prefix(8);
|
||||||
|
else if (url.find("://") != std::string_view::npos)
|
||||||
|
return std::nullopt;
|
||||||
|
const auto slash = url.find('/');
|
||||||
|
auto authority = url.substr(0, slash);
|
||||||
|
auto prefix = slash == std::string_view::npos ? std::string_view{} : url.substr(slash);
|
||||||
|
while (!prefix.empty() && prefix.back() == '/')
|
||||||
|
prefix.remove_suffix(1);
|
||||||
|
HttpsBase base;
|
||||||
|
const auto colon = authority.rfind(':');
|
||||||
|
if (colon != std::string_view::npos) {
|
||||||
|
const auto port = authority.substr(colon + 1);
|
||||||
|
if (std::from_chars(port.data(), port.data() + port.size(), base.port).ec != std::errc{} ||
|
||||||
|
base.port == 0)
|
||||||
|
return std::nullopt;
|
||||||
|
authority = authority.substr(0, colon);
|
||||||
|
}
|
||||||
|
if (authority.empty())
|
||||||
|
return std::nullopt;
|
||||||
|
base.host = std::string(authority);
|
||||||
|
base.prefix = std::string(prefix);
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<HttpsResponse> https_request(const HttpsRequest& request) {
|
||||||
|
const auto deadline = Clock::now() + request.timeout;
|
||||||
|
const int fd = connect_to(request.host, request.port, deadline);
|
||||||
|
if (fd < 0)
|
||||||
|
return std::nullopt;
|
||||||
|
const Socket socket{fd};
|
||||||
|
const std::unique_ptr<SSL_CTX, decltype(&SSL_CTX_free)> context{
|
||||||
|
SSL_CTX_new(TLS_client_method()), SSL_CTX_free};
|
||||||
|
if (!context || SSL_CTX_set_min_proto_version(context.get(), TLS1_2_VERSION) != 1)
|
||||||
|
return std::nullopt;
|
||||||
|
if (request.verify) {
|
||||||
|
if (SSL_CTX_set_default_verify_paths(context.get()) != 1)
|
||||||
|
return std::nullopt;
|
||||||
|
SSL_CTX_set_verify(context.get(), SSL_VERIFY_PEER, nullptr);
|
||||||
|
} else {
|
||||||
|
SSL_CTX_set_verify(context.get(), SSL_VERIFY_NONE, nullptr);
|
||||||
|
}
|
||||||
|
const std::unique_ptr<SSL, decltype(&SSL_free)> ssl{SSL_new(context.get()), SSL_free};
|
||||||
|
if (!ssl || SSL_set_fd(ssl.get(), fd) != 1 ||
|
||||||
|
SSL_set_tlsext_host_name(ssl.get(), request.host.c_str()) != 1 ||
|
||||||
|
(request.verify && SSL_set1_host(ssl.get(), request.host.c_str()) != 1))
|
||||||
|
return std::nullopt;
|
||||||
|
for (;;) {
|
||||||
|
const int done = SSL_connect(ssl.get());
|
||||||
|
if (done == 1)
|
||||||
|
break;
|
||||||
|
if (!retry(ssl.get(), done, deadline))
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
std::string message =
|
||||||
|
request.method + " " + request.target + " HTTP/1.1\r\nHost: " + request.host +
|
||||||
|
"\r\nConnection: close\r\nContent-Length: " + std::to_string(request.body.size()) + "\r\n";
|
||||||
|
for (const auto& [name, value] : request.headers)
|
||||||
|
message.append(name).append(": ").append(value).append("\r\n");
|
||||||
|
message += "\r\n" + request.body;
|
||||||
|
for (std::size_t sent = 0; sent < message.size();) {
|
||||||
|
std::size_t wrote = 0;
|
||||||
|
const int done =
|
||||||
|
SSL_write_ex(ssl.get(), message.data() + sent, message.size() - sent, &wrote);
|
||||||
|
if (done == 1)
|
||||||
|
sent += wrote;
|
||||||
|
else if (!retry(ssl.get(), done, deadline))
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
constexpr std::size_t header_room = 64U << 10U;
|
||||||
|
std::string raw;
|
||||||
|
for (;;) {
|
||||||
|
char chunk[16384];
|
||||||
|
std::size_t got = 0;
|
||||||
|
const int done = SSL_read_ex(ssl.get(), chunk, sizeof chunk, &got);
|
||||||
|
if (done == 1) {
|
||||||
|
raw.append(chunk, got);
|
||||||
|
if (raw.size() > request.limit + header_room)
|
||||||
|
return std::nullopt;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const int error = SSL_get_error(ssl.get(), done);
|
||||||
|
if (error == SSL_ERROR_ZERO_RETURN ||
|
||||||
|
(error == SSL_ERROR_SYSCALL && ERR_peek_error() == 0) ||
|
||||||
|
(error == SSL_ERROR_SSL &&
|
||||||
|
ERR_GET_REASON(ERR_peek_error()) == SSL_R_UNEXPECTED_EOF_WHILE_READING))
|
||||||
|
break; // The server closed the connection: the answer is complete.
|
||||||
|
if (!retry(ssl.get(), done, deadline))
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
ERR_clear_error();
|
||||||
|
return parse_http_response(raw, request.limit);
|
||||||
|
}
|
||||||
|
} // namespace evo::server::admin
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
#include "evo/server/admin/region_switch.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <charconv>
|
||||||
|
#include <optional>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace evo::server::admin {
|
||||||
|
namespace {
|
||||||
|
bool any_value(std::string_view /*value*/) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool hex32(std::string_view value) {
|
||||||
|
return value.size() == 32 && std::ranges::all_of(value, [](char c) {
|
||||||
|
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Every value following `prefix`, up to (not including) the first character in `stops`, that
|
||||||
|
// `wanted` accepts (a comment can mention a flag without a value).
|
||||||
|
std::vector<std::pair<std::size_t, std::string_view>>
|
||||||
|
values_after(std::string_view text, std::string_view prefix, std::string_view stops,
|
||||||
|
bool (*wanted)(std::string_view) = any_value) {
|
||||||
|
std::vector<std::pair<std::size_t, std::string_view>> found;
|
||||||
|
for (auto at = text.find(prefix); at != std::string_view::npos;
|
||||||
|
at = text.find(prefix, at + 1)) {
|
||||||
|
const auto first = at + prefix.size();
|
||||||
|
const auto end = std::min(text.find_first_of(stops, first), text.size());
|
||||||
|
if (wanted(text.substr(first, end - first)))
|
||||||
|
found.emplace_back(first, text.substr(first, end - first));
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
std::optional<std::uint64_t> number(std::string_view text) {
|
||||||
|
std::uint64_t value{};
|
||||||
|
if (text.empty() ||
|
||||||
|
std::from_chars(text.data(), text.data() + text.size(), value).ec != std::errc{})
|
||||||
|
return std::nullopt;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
// The one value after `prefix` (all of `count` occurrences equal), or nullopt.
|
||||||
|
std::optional<std::string_view> single(std::string_view text, std::string_view prefix,
|
||||||
|
std::string_view stops, std::size_t count = 1,
|
||||||
|
bool (*wanted)(std::string_view) = any_value) {
|
||||||
|
const auto found = values_after(text, prefix, stops, wanted);
|
||||||
|
if (found.size() != count ||
|
||||||
|
!std::ranges::all_of(found, [&](const auto& v) { return v.second == found[0].second; }))
|
||||||
|
return std::nullopt;
|
||||||
|
return found[0].second;
|
||||||
|
}
|
||||||
|
// `text` with every value after `prefix` replaced by `value` (back to front, so positions hold).
|
||||||
|
std::string replace_after(std::string text, std::string_view prefix, std::string_view stops,
|
||||||
|
std::string_view value, bool (*wanted)(std::string_view) = any_value) {
|
||||||
|
auto found = values_after(text, prefix, stops, wanted);
|
||||||
|
std::ranges::reverse(found);
|
||||||
|
for (const auto& [at, old] : found)
|
||||||
|
text.replace(at, old.size(), value);
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr std::string_view world_key = "{name: REGION_WORLD, value: \"";
|
||||||
|
constexpr std::string_view region_key = "{name: REGION_ID, value: \"";
|
||||||
|
constexpr std::string_view routes_key = "{name: REGION_LIFE_ROUTES, value: \"";
|
||||||
|
constexpr std::string_view commit_key = "--commit ";
|
||||||
|
constexpr std::string_view wildlife_key = "--playtest-wildlife-first-id ";
|
||||||
|
constexpr std::string_view header_key = "# Region host for evolution-dev: world ";
|
||||||
|
constexpr std::string_view broker_region_key = "{name: BROKER_DEFAULT_REGION, value: \"";
|
||||||
|
constexpr std::string_view broker_routes_key = "{name: BROKER_ROUTES, value: \"";
|
||||||
|
constexpr std::string_view portal_regions_key = "{name: ADMIN_REGIONS, value: \"";
|
||||||
|
constexpr std::string_view opening_key = " - {name: REGION_OPENING, value: ";
|
||||||
|
constexpr std::string_view note_prefix = " # Admin portal (ADR-0182 section 15): ";
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::expected<RegionLayout, std::string> read_region_layout(const RegionSwitchFiles& files) {
|
||||||
|
const auto& [values, kustomization, broker, portal] = files;
|
||||||
|
RegionLayout layout;
|
||||||
|
// The Deployment and the provision Job each name the world and region.
|
||||||
|
const auto world = single(values, world_key, "\"", 2);
|
||||||
|
const auto region = single(values, region_key, "\"", 2);
|
||||||
|
const auto world_id = world ? number(*world) : std::nullopt;
|
||||||
|
const auto region_id = region ? number(*region) : std::nullopt;
|
||||||
|
if (!world_id)
|
||||||
|
return std::unexpected{"REGION_WORLD"};
|
||||||
|
if (!region_id)
|
||||||
|
return std::unexpected{"REGION_ID"};
|
||||||
|
layout.world = *world_id;
|
||||||
|
layout.region = *region_id;
|
||||||
|
// Canonical numbers only, so every other file can be matched by the same text.
|
||||||
|
const auto id = std::to_string(layout.region);
|
||||||
|
if (*region != id || *world != std::to_string(layout.world))
|
||||||
|
return std::unexpected{"REGION_ID"};
|
||||||
|
const auto routes = single(values, routes_key, "=");
|
||||||
|
if (!routes || *routes != id)
|
||||||
|
return std::unexpected{"REGION_LIFE_ROUTES"};
|
||||||
|
const auto commit = single(values, commit_key, " \n", 1, hex32);
|
||||||
|
if (!commit)
|
||||||
|
return std::unexpected{"--commit"};
|
||||||
|
layout.commit = std::string(*commit);
|
||||||
|
const auto wildlife = single(values, wildlife_key, " \n");
|
||||||
|
const auto wildlife_first = wildlife ? number(*wildlife) : std::nullopt;
|
||||||
|
if (!wildlife_first)
|
||||||
|
return std::unexpected{"--playtest-wildlife-first-id"};
|
||||||
|
layout.wildlife_first = *wildlife_first;
|
||||||
|
if (values.find(opening_key) == std::string::npos ||
|
||||||
|
values.find(opening_key) != values.rfind(opening_key))
|
||||||
|
return std::unexpected{"REGION_OPENING"};
|
||||||
|
const auto header = single(kustomization, header_key, "\n");
|
||||||
|
if (!header || !header->starts_with(std::to_string(layout.world) + ", region " + id + ","))
|
||||||
|
return std::unexpected{"kustomization header"};
|
||||||
|
const auto broker_region = single(broker, broker_region_key, "\"");
|
||||||
|
if (!broker_region || *broker_region != id)
|
||||||
|
return std::unexpected{"BROKER_DEFAULT_REGION"};
|
||||||
|
const auto broker_routes = single(broker, broker_routes_key, "=");
|
||||||
|
if (!broker_routes || *broker_routes != id)
|
||||||
|
return std::unexpected{"BROKER_ROUTES"};
|
||||||
|
const auto portal_regions = single(portal, portal_regions_key, "=");
|
||||||
|
if (!portal_regions || *portal_regions != id)
|
||||||
|
return std::unexpected{"ADMIN_REGIONS"};
|
||||||
|
return layout;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::expected<RegionSwitchFiles, std::string>
|
||||||
|
switch_region(const RegionSwitchFiles& files, const RegionLayout& to, std::string_view note) {
|
||||||
|
const auto from = read_region_layout(files);
|
||||||
|
if (!from)
|
||||||
|
return std::unexpected{from.error()};
|
||||||
|
if (to.world != from->world || to.region == 0 || to.region == from->region ||
|
||||||
|
to.wildlife_first == 0 || !hex32(to.commit))
|
||||||
|
return std::unexpected{"target"};
|
||||||
|
if (note.find_first_of("\r\n") != std::string_view::npos)
|
||||||
|
return std::unexpected{"note"};
|
||||||
|
auto [values, kustomization, broker, portal] = files;
|
||||||
|
const auto region = std::to_string(to.region);
|
||||||
|
values = replace_after(std::move(values), region_key, "\"", region);
|
||||||
|
values = replace_after(std::move(values), routes_key, "=", region);
|
||||||
|
values = replace_after(std::move(values), commit_key, " \n", to.commit, hex32);
|
||||||
|
values =
|
||||||
|
replace_after(std::move(values), wildlife_key, " \n", std::to_string(to.wildlife_first));
|
||||||
|
// One note above the opening, replacing the previous portal note.
|
||||||
|
const auto line = std::string(note_prefix) + std::string(note) + "\n";
|
||||||
|
if (const auto old = values.find(note_prefix); old != std::string::npos)
|
||||||
|
values.erase(old, values.find('\n', old) - old + 1);
|
||||||
|
values.insert(values.find(opening_key), line);
|
||||||
|
const auto header_at = kustomization.find(header_key) + header_key.size();
|
||||||
|
const auto old_region = ", region " + std::to_string(from->region) + ",";
|
||||||
|
kustomization.replace(kustomization.find(old_region, header_at), old_region.size(),
|
||||||
|
", region " + region + ",");
|
||||||
|
broker = replace_after(std::move(broker), broker_region_key, "\"", region);
|
||||||
|
broker = replace_after(std::move(broker), broker_routes_key, "=", region);
|
||||||
|
portal = replace_after(std::move(portal), portal_regions_key, "=", region);
|
||||||
|
RegionSwitchFiles result{std::move(values), std::move(kustomization), std::move(broker),
|
||||||
|
std::move(portal)};
|
||||||
|
const auto check = read_region_layout(result);
|
||||||
|
if (!check || *check != to)
|
||||||
|
return std::unexpected{"result"};
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
} // namespace evo::server::admin
|
||||||
@@ -97,6 +97,8 @@ OpsResponse GrantBroker::issue(const AccessTokenClaims& claims, std::uint64_t no
|
|||||||
const auto issued = persistence::issue_account_grant(*db, config_.world, claims.issuer,
|
const auto issued = persistence::issue_account_grant(*db, config_.world, claims.issuer,
|
||||||
claims.subject, config_.db_timeout);
|
claims.subject, config_.db_timeout);
|
||||||
if (!issued) {
|
if (!issued) {
|
||||||
|
if (issued.error() == persistence::AccountIdentityError::banned)
|
||||||
|
return error(403, "account_banned");
|
||||||
if (issued.error() != persistence::AccountIdentityError::invalid)
|
if (issued.error() != persistence::AccountIdentityError::invalid)
|
||||||
db_.reset();
|
db_.reset();
|
||||||
return error(503, "unavailable");
|
return error(503, "unavailable");
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
#include "evo/server/cellular_region_host.hpp"
|
#include "evo/server/cellular_region_host.hpp"
|
||||||
|
|
||||||
|
#include "evo/biology/cellular_revamp_tuning.hpp"
|
||||||
#include "evo/biology/founder.hpp"
|
#include "evo/biology/founder.hpp"
|
||||||
#include "evo/persistence/sha256.hpp"
|
#include "evo/persistence/sha256.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <charconv>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
@@ -448,6 +450,9 @@ void CellularRegionHost::resolve() {
|
|||||||
finalized_actions_.push_back({action, committed_->head.sequence});
|
finalized_actions_.push_back({action, committed_->head.sequence});
|
||||||
finalize_births(pending_->births);
|
finalize_births(pending_->births);
|
||||||
finalize_mutations(pending_->mutation_actions, pending_->prepared.results);
|
finalize_mutations(pending_->mutation_actions, pending_->prepared.results);
|
||||||
|
// The store knows which admin commands this commit bound: read the queue again.
|
||||||
|
queued_admin_.clear();
|
||||||
|
next_admin_reload_ = {};
|
||||||
pending_.reset();
|
pending_.reset();
|
||||||
++status_.commits;
|
++status_.commits;
|
||||||
status_.committed_sequence = committed_->head.sequence;
|
status_.committed_sequence = committed_->head.sequence;
|
||||||
@@ -738,6 +743,8 @@ const HostStatus& CellularRegionHost::step() {
|
|||||||
reconcile_interval();
|
reconcile_interval();
|
||||||
if (!pending_ && state_ && mutations_uncertain_ && status_.phase == HostPhase::running)
|
if (!pending_ && state_ && mutations_uncertain_ && status_.phase == HostPhase::running)
|
||||||
reload_mutations();
|
reload_mutations();
|
||||||
|
if (!pending_ && state_ && status_.phase == HostPhase::running)
|
||||||
|
reload_admin_commands();
|
||||||
if (!pending_ && state_ && status_.phase == HostPhase::running)
|
if (!pending_ && state_ && status_.phase == HostPhase::running)
|
||||||
flush_endings();
|
flush_endings();
|
||||||
refresh();
|
refresh();
|
||||||
@@ -928,6 +935,110 @@ CellularRegionHost::select_mutation(const persistence::Uuid& account, std::uint6
|
|||||||
return {admitted, tick, {}};
|
return {admitted, tick, {}};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<CellularAdminCommand> CellularRegionHost::unbound_admin_commands() const {
|
||||||
|
std::vector<CellularAdminCommand> unbound;
|
||||||
|
for (const auto& queued : queued_admin_) {
|
||||||
|
if (unbound.size() >= max_cellular_tick_admin_commands)
|
||||||
|
break;
|
||||||
|
const bool flying =
|
||||||
|
in_flight_ && std::ranges::any_of(in_flight_->batch.ticks, [&](const auto& tick) {
|
||||||
|
return std::ranges::find(tick.admin, queued.id, &CellularAdminCommand::id) !=
|
||||||
|
tick.admin.end();
|
||||||
|
});
|
||||||
|
if (!flying)
|
||||||
|
unbound.push_back(queued);
|
||||||
|
}
|
||||||
|
return unbound;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADR-0182: the region's unpublished admin commands, every 2 s (rules 13 only).
|
||||||
|
void CellularRegionHost::reload_admin_commands() {
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
if (now < next_admin_reload_ || !committed_ ||
|
||||||
|
state_->rules_version() < cellular_lives_revamp_rules || !database())
|
||||||
|
return;
|
||||||
|
next_admin_reload_ = now + std::chrono::seconds{2};
|
||||||
|
const std::array<std::string, 2> parameters{std::to_string(config_.key.world),
|
||||||
|
std::to_string(config_.key.region)};
|
||||||
|
const auto rows = db_->query(
|
||||||
|
"SELECT command_id, kind, cell_count, target, energy, carbon, nitrogen, phosphorus, other "
|
||||||
|
"FROM evolution.load_pending_admin_commands_v1($1::evolution.u64, $2::evolution.u64)",
|
||||||
|
parameters, config_.lease.commit_timeout);
|
||||||
|
if (!rows) {
|
||||||
|
db_.reset();
|
||||||
|
++status_.store_failures;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::vector<CellularAdminCommand> loaded;
|
||||||
|
for (const auto& row : *rows) {
|
||||||
|
std::array<std::uint64_t, 9> v{};
|
||||||
|
bool ok = row.size() == v.size();
|
||||||
|
for (std::size_t i = 0; ok && i < v.size(); ++i) {
|
||||||
|
const auto& text = row[i];
|
||||||
|
ok = text.has_value() &&
|
||||||
|
std::from_chars(text->data(), text->data() + text->size(), v[i]).ec == std::errc{};
|
||||||
|
}
|
||||||
|
if (!ok || v[1] > 0xFF || v[2] > 0xFFFF)
|
||||||
|
continue;
|
||||||
|
CellularAdminCommand command{v[0],
|
||||||
|
static_cast<CellularAdminKind>(v[1]),
|
||||||
|
static_cast<std::uint16_t>(v[2]),
|
||||||
|
v[3],
|
||||||
|
{{v[4]}, {}}};
|
||||||
|
for (std::size_t c = 0; c < command.amount.matter.size(); ++c)
|
||||||
|
command.amount.matter[c].value = v[5 + c];
|
||||||
|
if (!cellular_admin_command_valid(command))
|
||||||
|
continue;
|
||||||
|
// A tuning adoption waits until its revision's text rebuilds exactly these rules.
|
||||||
|
if (command.kind == CellularAdminKind::adopt_tuning &&
|
||||||
|
!verified_tuning_.contains(command.target)) {
|
||||||
|
const std::array<std::string, 2> lookup{std::to_string(config_.key.world),
|
||||||
|
std::to_string(command.target)};
|
||||||
|
const auto text =
|
||||||
|
db_->query("SELECT text FROM evolution.load_tuning_revision_v1($1::evolution.u64, "
|
||||||
|
"$2::bigint)",
|
||||||
|
lookup, config_.lease.commit_timeout);
|
||||||
|
if (!text) {
|
||||||
|
db_.reset();
|
||||||
|
++status_.store_failures;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const auto cell = text->size() == 1 && (*text)[0].size() == 1
|
||||||
|
? (*text)[0][0]
|
||||||
|
: std::optional<std::string>{};
|
||||||
|
const auto parsed = cell ? biology::parse_cellular_revamp_tuning(*cell)
|
||||||
|
: std::unexpected{biology::CellularTuningError{
|
||||||
|
biology::CellularTuningErrorKind::syntax, 0, {}}};
|
||||||
|
if (!parsed) {
|
||||||
|
std::printf("cellular tuning revision=%llu unusable\n",
|
||||||
|
static_cast<unsigned long long>(command.target));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto rules = cellular_revamp_rules(*parsed);
|
||||||
|
const auto digest = persistence::sha256(encode_cellular_revamp_rules(rules));
|
||||||
|
if (!digest || !std::ranges::equal(*digest, cellular_admin_digest(command))) {
|
||||||
|
std::printf("cellular tuning revision=%llu digest mismatch\n",
|
||||||
|
static_cast<unsigned long long>(command.target));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
verified_tuning_.emplace(command.target, rules);
|
||||||
|
}
|
||||||
|
loaded.push_back(command);
|
||||||
|
}
|
||||||
|
queued_admin_ = std::move(loaded);
|
||||||
|
}
|
||||||
|
|
||||||
|
CellularTuningResolver CellularRegionHost::tuning_resolver() const {
|
||||||
|
return [this](std::uint64_t revision,
|
||||||
|
const std::array<std::uint8_t, 32>&) -> std::optional<CellularRevampRules> {
|
||||||
|
// Verified against the command's digest when the command was loaded.
|
||||||
|
const auto found = verified_tuning_.find(revision);
|
||||||
|
if (found == verified_tuning_.end())
|
||||||
|
return std::nullopt;
|
||||||
|
return found->second;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
std::vector<persistence::CellularMutationReservation>
|
std::vector<persistence::CellularMutationReservation>
|
||||||
CellularRegionHost::unbound_mutations() const {
|
CellularRegionHost::unbound_mutations() const {
|
||||||
std::vector<persistence::CellularMutationReservation> unbound;
|
std::vector<persistence::CellularMutationReservation> unbound;
|
||||||
@@ -954,7 +1065,10 @@ CellularRegionHost::publish(const CellularBatch& batch,
|
|||||||
CellularPublishFailure{CellularHostError::invalid_batch, {}, {}, {}});
|
CellularPublishFailure{CellularHostError::invalid_batch, {}, {}, {}});
|
||||||
return publish_population(batch);
|
return publish_population(batch);
|
||||||
}
|
}
|
||||||
auto candidate = replay_cellular_batch(*state_, batch);
|
std::vector<CellularMutationOutcome> outcomes;
|
||||||
|
std::vector<CellularAdminResult> admin_results;
|
||||||
|
auto candidate =
|
||||||
|
replay_cellular_batch(*state_, batch, outcomes, admin_results, tuning_resolver());
|
||||||
if (!candidate)
|
if (!candidate)
|
||||||
return std::unexpected{
|
return std::unexpected{
|
||||||
CellularPublishFailure{CellularHostError::invalid_batch, {}, {}, {}}};
|
CellularPublishFailure{CellularHostError::invalid_batch, {}, {}, {}}};
|
||||||
@@ -1091,6 +1205,10 @@ CellularRegionHost::finish_publication(
|
|||||||
for (const auto result : published->mutation_results)
|
for (const auto result : published->mutation_results)
|
||||||
results.push_back(static_cast<std::uint8_t>(result));
|
results.push_back(static_cast<std::uint8_t>(result));
|
||||||
finalize_mutations(mutation_actions, results);
|
finalize_mutations(mutation_actions, results);
|
||||||
|
for (const auto& tick : batch.ticks)
|
||||||
|
for (const auto& command : tick.admin)
|
||||||
|
std::erase_if(queued_admin_,
|
||||||
|
[&](const auto& queued) { return queued.id == command.id; });
|
||||||
++status_.commits;
|
++status_.commits;
|
||||||
status_.committed_sequence = committed_->head.sequence;
|
status_.committed_sequence = committed_->head.sequence;
|
||||||
status_.committed_tick = committed_->head.end_tick;
|
status_.committed_tick = committed_->head.end_tick;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#include "evo/server/lifecycle/cellular_admin_view.hpp"
|
#include "evo/server/lifecycle/cellular_admin_view.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@@ -17,6 +18,25 @@ void append_inventory(std::string& out, const accounting::Inventory& inventory)
|
|||||||
append(out, channel.value);
|
append(out, channel.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Energy then the four matter channels, summed without the inventory's overflow checks: a
|
||||||
|
// region's stock is far below 2^64 in every channel.
|
||||||
|
using Totals = std::array<std::uint64_t, 5>;
|
||||||
|
void add(Totals& totals, const accounting::Inventory& inventory) {
|
||||||
|
totals[0] += inventory.energy.value;
|
||||||
|
for (std::size_t i = 0; i < inventory.matter.size(); ++i)
|
||||||
|
totals[i + 1] += inventory.matter[i].value;
|
||||||
|
}
|
||||||
|
void append_totals(std::string& out, std::string_view name, const Totals& totals) {
|
||||||
|
out += "\"";
|
||||||
|
out += name;
|
||||||
|
out += "\":[";
|
||||||
|
for (std::size_t i = 0; i < totals.size(); ++i) {
|
||||||
|
if (i != 0)
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, totals[i]);
|
||||||
|
}
|
||||||
|
out.push_back(']');
|
||||||
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
std::string cellular_account_text(const LifeAccount& account) {
|
std::string cellular_account_text(const LifeAccount& account) {
|
||||||
@@ -34,7 +54,8 @@ std::string cellular_account_text(const LifeAccount& account) {
|
|||||||
|
|
||||||
std::string render_cellular_admin_view(const CellularLives& state,
|
std::string render_cellular_admin_view(const CellularLives& state,
|
||||||
const CellularAdminOnline& online,
|
const CellularAdminOnline& online,
|
||||||
CellularAdminViewLimits limits) {
|
CellularAdminViewLimits limits,
|
||||||
|
std::string_view rules_sha256) {
|
||||||
const auto lives = state.lives();
|
const auto lives = state.lives();
|
||||||
const auto patches = state.habitat().patches();
|
const auto patches = state.habitat().patches();
|
||||||
std::string out;
|
std::string out;
|
||||||
@@ -48,17 +69,87 @@ std::string render_cellular_admin_view(const CellularLives& state,
|
|||||||
append(out, state.tick());
|
append(out, state.tick());
|
||||||
out += ",\"rules\":";
|
out += ",\"rules\":";
|
||||||
append(out, state.rules_version());
|
append(out, state.rules_version());
|
||||||
|
if (!rules_sha256.empty()) {
|
||||||
|
out += ",\"rules_sha256\":\"";
|
||||||
|
out += rules_sha256;
|
||||||
|
out.push_back('"');
|
||||||
|
}
|
||||||
out += ",\"area\":[";
|
out += ",\"area\":[";
|
||||||
append(out, state.area().width_um);
|
append(out, state.area().width_um);
|
||||||
out.push_back(',');
|
out.push_back(',');
|
||||||
append(out, state.area().height_um);
|
append(out, state.area().height_um);
|
||||||
out += "],\"spent\":[";
|
out += "],\"spent\":[";
|
||||||
append_inventory(out, state.spent());
|
append_inventory(out, state.spent());
|
||||||
out += "],\"cells_total\":";
|
out += "],\"heat\":";
|
||||||
|
append(out, state.heat().energy.value);
|
||||||
|
// The lineage archive never forgets: births and genomes recorded against its limits, at
|
||||||
|
// which the region stops ticking.
|
||||||
|
out += ",\"archive\":[";
|
||||||
|
append(out, state.archive().recorded());
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, biology::max_archived_organisms);
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, state.archive().archived());
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, biology::max_archived_genomes);
|
||||||
|
out.push_back(']');
|
||||||
|
if (state.rules_version() >= cellular_lives_revamp_rules) {
|
||||||
|
const auto& rules = state.revamp_rules();
|
||||||
|
out += ",\"drip\":[";
|
||||||
|
append(out, rules.drip_interval_ticks);
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, rules.drip_bubble_pj);
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, rules.drip_bubble_fg);
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, rules.heat_recycle_per_thousand);
|
||||||
|
out += rules.drip_absorb ? ",1]" : ",0]";
|
||||||
|
// The organism cap and the wildlife cap (0: the organism cap).
|
||||||
|
out += ",\"caps\":[";
|
||||||
|
append(out, rules.organism_cap);
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, rules.wildlife_cap);
|
||||||
|
out.push_back(']');
|
||||||
|
}
|
||||||
|
out += ",\"cells_total\":";
|
||||||
append(out, lives.size());
|
append(out, lives.size());
|
||||||
out += ",\"deposits_total\":";
|
out += ",\"deposits_total\":";
|
||||||
append(out, patches.size());
|
append(out, patches.size());
|
||||||
|
|
||||||
|
// Counts and stock over every life and deposit, beyond the listing limits.
|
||||||
|
std::array<std::uint64_t, 5> counts{}; // Players, wildlife, patches, pools, bubbles.
|
||||||
|
Totals reserve{}, body{};
|
||||||
|
std::array<Totals, 3> deposits_by_kind{};
|
||||||
|
for (const auto& life : lives) {
|
||||||
|
++counts[life.account == LifeAccount{} ? 1 : 0];
|
||||||
|
add(reserve, life.reserve);
|
||||||
|
add(body, life.body);
|
||||||
|
}
|
||||||
|
for (const auto& patch : patches) {
|
||||||
|
const auto kind = static_cast<std::size_t>(patch.kind);
|
||||||
|
if (kind < deposits_by_kind.size()) {
|
||||||
|
++counts[2 + kind];
|
||||||
|
add(deposits_by_kind[kind], patch.stock);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out += ",\"counts\":[";
|
||||||
|
for (std::size_t i = 0; i < counts.size(); ++i) {
|
||||||
|
if (i != 0)
|
||||||
|
out.push_back(',');
|
||||||
|
append(out, counts[i]);
|
||||||
|
}
|
||||||
|
out += "],\"totals\":{";
|
||||||
|
append_totals(out, "reserve", reserve);
|
||||||
|
out.push_back(',');
|
||||||
|
append_totals(out, "body", body);
|
||||||
|
out.push_back(',');
|
||||||
|
append_totals(out, "patches", deposits_by_kind[0]);
|
||||||
|
out.push_back(',');
|
||||||
|
append_totals(out, "pools", deposits_by_kind[1]);
|
||||||
|
out.push_back(',');
|
||||||
|
append_totals(out, "bubbles", deposits_by_kind[2]);
|
||||||
|
out.push_back('}');
|
||||||
|
|
||||||
// Lives are kept in ascending life id; a prefix is the lowest ids.
|
// Lives are kept in ascending life id; a prefix is the lowest ids.
|
||||||
out += ",\"cells\":[";
|
out += ",\"cells\":[";
|
||||||
const auto cells = std::min(lives.size(), limits.cells);
|
const auto cells = std::min(lives.size(), limits.cells);
|
||||||
@@ -98,7 +189,9 @@ std::string render_cellular_admin_view(const CellularLives& state,
|
|||||||
append_inventory(out, life.reserve);
|
append_inventory(out, life.reserve);
|
||||||
out.push_back(',');
|
out.push_back(',');
|
||||||
append(out, body_mass);
|
append(out, body_mass);
|
||||||
out.push_back(']');
|
out += ",\"";
|
||||||
|
append(out, cellular_lineage_root(state, life.identity.life));
|
||||||
|
out += "\"]";
|
||||||
}
|
}
|
||||||
|
|
||||||
// Patches are kept by address; the view lists them by ascending id.
|
// Patches are kept by address; the view lists them by ascending id.
|
||||||
|
|||||||
@@ -34,20 +34,29 @@ bool valid_header(const CellularBatchHeader& h, std::size_t ticks) {
|
|||||||
}
|
}
|
||||||
bool known_format(std::uint32_t format) {
|
bool known_format(std::uint32_t format) {
|
||||||
return format == cellular_batch_legacy_format || format == cellular_batch_v2_format ||
|
return format == cellular_batch_legacy_format || format == cellular_batch_v2_format ||
|
||||||
format == cellular_batch_format || format == cellular_batch_inheritance_format;
|
format == cellular_batch_format || format == cellular_batch_inheritance_format ||
|
||||||
|
format == cellular_batch_admin_format;
|
||||||
}
|
}
|
||||||
bool owner_version_matches(const CellularLives& owner, const CellularBatch& batch) {
|
bool owner_version_matches(const CellularLives& owner, const CellularBatch& batch) {
|
||||||
if (!known_format(batch.format_version))
|
if (!known_format(batch.format_version))
|
||||||
return false;
|
return false;
|
||||||
|
if (batch.format_version == cellular_batch_admin_format)
|
||||||
|
return owner.format_version() == cellular_lives_revamp_format &&
|
||||||
|
owner.rules_version() >= cellular_lives_revamp_rules;
|
||||||
if (batch.format_version == cellular_batch_inheritance_format)
|
if (batch.format_version == cellular_batch_inheritance_format)
|
||||||
return owner.format_version() >= cellular_lives_inheritance_format &&
|
return owner.format_version() >= cellular_lives_inheritance_format &&
|
||||||
cellular_retained_plans(owner.rules_version());
|
cellular_retained_plans(owner.rules_version());
|
||||||
return owner.format_version() < cellular_lives_inheritance_format;
|
return owner.format_version() < cellular_lives_inheritance_format;
|
||||||
}
|
}
|
||||||
bool payload_version_matches(const CellularBatch& batch) {
|
bool payload_version_matches(const CellularBatch& batch) {
|
||||||
|
// ADR-0182: trace 5 only with a command; a batch without one is trace 4.
|
||||||
|
if (batch.format_version == cellular_batch_admin_format &&
|
||||||
|
std::ranges::none_of(batch.ticks, [](const auto& tick) { return !tick.admin.empty(); }))
|
||||||
|
return false;
|
||||||
return std::ranges::all_of(batch.ticks, [&](const auto& tick) {
|
return std::ranges::all_of(batch.ticks, [&](const auto& tick) {
|
||||||
return (batch.format_version >= cellular_batch_v2_format || tick.births.empty()) &&
|
return (batch.format_version >= cellular_batch_v2_format || tick.births.empty()) &&
|
||||||
(batch.format_version >= cellular_batch_format || tick.mutations.empty());
|
(batch.format_version >= cellular_batch_format || tick.mutations.empty()) &&
|
||||||
|
(batch.format_version == cellular_batch_admin_format || tick.admin.empty());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
bool valid_intent(const CellularLifeIntent& life) {
|
bool valid_intent(const CellularLifeIntent& life) {
|
||||||
@@ -62,6 +71,7 @@ bool valid_intent(const CellularLifeIntent& life) {
|
|||||||
!(step.emerge && (step.frozen || step.bud || step.engulf || step.intake_target));
|
!(step.emerge && (step.frozen || step.bud || step.engulf || step.intake_target));
|
||||||
}
|
}
|
||||||
bool valid_ticks(std::span<const CellularTickIntents> ticks) {
|
bool valid_ticks(std::span<const CellularTickIntents> ticks) {
|
||||||
|
std::size_t adoptions = 0;
|
||||||
std::set<std::uint64_t> identities;
|
std::set<std::uint64_t> identities;
|
||||||
std::set<LifeAccount> accounts;
|
std::set<LifeAccount> accounts;
|
||||||
for (const auto& tick : ticks) {
|
for (const auto& tick : ticks) {
|
||||||
@@ -84,6 +94,16 @@ bool valid_ticks(std::span<const CellularTickIntents> ticks) {
|
|||||||
if (!identities.insert(birth.identity).second || !accounts.insert(birth.account).second)
|
if (!identities.insert(birth.identity).second || !accounts.insert(birth.account).second)
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (tick.admin.size() > max_cellular_tick_admin_commands)
|
||||||
|
return false;
|
||||||
|
for (std::size_t i = 0; i < tick.admin.size(); ++i) {
|
||||||
|
if (!cellular_admin_command_valid(tick.admin[i]) ||
|
||||||
|
(i > 0 && tick.admin[i - 1].id >= tick.admin[i].id))
|
||||||
|
return false;
|
||||||
|
// ADR-0182: one tuning adoption per batch, so its successor names its rules.
|
||||||
|
if (tick.admin[i].kind == CellularAdminKind::adopt_tuning && ++adoptions > 1)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
for (std::size_t i = 0; i < tick.mutations.size(); ++i) {
|
for (std::size_t i = 0; i < tick.mutations.size(); ++i) {
|
||||||
const auto& mutation = tick.mutations[i];
|
const auto& mutation = tick.mutations[i];
|
||||||
if (mutation.life_id == 0 || mutation.event_index == 0 || mutation.offer_tick == 0 ||
|
if (mutation.life_id == 0 || mutation.event_index == 0 || mutation.offer_tick == 0 ||
|
||||||
@@ -198,7 +218,8 @@ encode_cellular_batch(const CellularBatch& batch) {
|
|||||||
: 0) +
|
: 0) +
|
||||||
(batch.format_version >= cellular_batch_format
|
(batch.format_version >= cellular_batch_format
|
||||||
? tick.mutations.size() * cellular_batch_mutation_bytes
|
? tick.mutations.size() * cellular_batch_mutation_bytes
|
||||||
: 0);
|
: 0) +
|
||||||
|
tick.admin.size() * cellular_batch_admin_bytes;
|
||||||
if (records > max_cellular_batch_bytes - size - tick_header_bytes)
|
if (records > max_cellular_batch_bytes - size - tick_header_bytes)
|
||||||
return std::unexpected{CellularBatchError::format};
|
return std::unexpected{CellularBatchError::format};
|
||||||
size += tick_header_bytes + records;
|
size += tick_header_bytes + records;
|
||||||
@@ -224,7 +245,7 @@ encode_cellular_batch(const CellularBatch& batch) {
|
|||||||
put(out, tick.births.size(), 4);
|
put(out, tick.births.size(), 4);
|
||||||
if (batch.format_version >= cellular_batch_format) {
|
if (batch.format_version >= cellular_batch_format) {
|
||||||
put(out, tick.mutations.size(), 4);
|
put(out, tick.mutations.size(), 4);
|
||||||
put(out, 0, 4);
|
put(out, tick.admin.size(), 4); // Zero before format 5.
|
||||||
}
|
}
|
||||||
for (const auto& life : tick.lives)
|
for (const auto& life : tick.lives)
|
||||||
put_intent(out, life);
|
put_intent(out, life);
|
||||||
@@ -247,6 +268,16 @@ encode_cellular_batch(const CellularBatch& batch) {
|
|||||||
put(out, mutation.become ? 1 : 0, 1); // Byte 34 (rules 13).
|
put(out, mutation.become ? 1 : 0, 1); // Byte 34 (rules 13).
|
||||||
put(out, 0, 5);
|
put(out, 0, 5);
|
||||||
}
|
}
|
||||||
|
for (const auto& command : tick.admin) {
|
||||||
|
put(out, command.id, 8);
|
||||||
|
put(out, static_cast<std::uint16_t>(command.kind), 2);
|
||||||
|
put(out, command.count, 2);
|
||||||
|
put(out, 0, 4);
|
||||||
|
put(out, command.target, 8);
|
||||||
|
put(out, command.amount.energy.value, 8);
|
||||||
|
for (const auto& channel : command.amount.matter)
|
||||||
|
put(out, channel.value, 8);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (out.size() != size)
|
if (out.size() != size)
|
||||||
return std::unexpected{CellularBatchError::format};
|
return std::unexpected{CellularBatchError::format};
|
||||||
@@ -259,8 +290,8 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
|
|||||||
!std::ranges::equal(bytes.first(magic.size()), magic))
|
!std::ranges::equal(bytes.first(magic.size()), magic))
|
||||||
return std::unexpected{CellularBatchError::format};
|
return std::unexpected{CellularBatchError::format};
|
||||||
const auto format = get(bytes, 8, 4);
|
const auto format = get(bytes, 8, 4);
|
||||||
if (format > cellular_batch_inheritance_format ||
|
if (format > cellular_batch_admin_format || !known_format(static_cast<std::uint32_t>(format)) ||
|
||||||
!known_format(static_cast<std::uint32_t>(format)) || get(bytes, 12, 4) != 4)
|
get(bytes, 12, 4) != 4)
|
||||||
return std::unexpected{CellularBatchError::version};
|
return std::unexpected{CellularBatchError::version};
|
||||||
if (get(bytes, 108, 4) != 0)
|
if (get(bytes, 108, 4) != 0)
|
||||||
return std::unexpected{CellularBatchError::format};
|
return std::unexpected{CellularBatchError::format};
|
||||||
@@ -298,13 +329,16 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
|
|||||||
birth_count = get(bytes, offset, 4);
|
birth_count = get(bytes, offset, 4);
|
||||||
offset += 4;
|
offset += 4;
|
||||||
}
|
}
|
||||||
std::uint64_t mutation_count{};
|
std::uint64_t mutation_count{}, admin_count{};
|
||||||
if (format >= cellular_batch_format) {
|
if (format >= cellular_batch_format) {
|
||||||
mutation_count = get(bytes, offset, 4);
|
mutation_count = get(bytes, offset, 4);
|
||||||
if (get(bytes, offset + 4, 4) != 0)
|
admin_count = get(bytes, offset + 4, 4);
|
||||||
|
if (format != cellular_batch_admin_format && admin_count != 0)
|
||||||
return std::unexpected{CellularBatchError::format};
|
return std::unexpected{CellularBatchError::format};
|
||||||
offset += 8;
|
offset += 8;
|
||||||
}
|
}
|
||||||
|
if (admin_count > max_cellular_tick_admin_commands)
|
||||||
|
return std::unexpected{CellularBatchError::format};
|
||||||
if (count > biology::max_cellular_tick_lives ||
|
if (count > biology::max_cellular_tick_lives ||
|
||||||
count > (bytes.size() - offset) / cellular_batch_intent_bytes ||
|
count > (bytes.size() - offset) / cellular_batch_intent_bytes ||
|
||||||
birth_count > biology::max_cellular_tick_lives ||
|
birth_count > biology::max_cellular_tick_lives ||
|
||||||
@@ -381,9 +415,29 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
|
|||||||
step.mutations.push_back(mutation);
|
step.mutations.push_back(mutation);
|
||||||
offset += cellular_batch_mutation_bytes;
|
offset += cellular_batch_mutation_bytes;
|
||||||
}
|
}
|
||||||
|
if (admin_count > (bytes.size() - offset) / cellular_batch_admin_bytes)
|
||||||
|
return std::unexpected{CellularBatchError::format};
|
||||||
|
for (std::uint64_t i = 0; i < admin_count; ++i) {
|
||||||
|
const auto record = bytes.subspan(offset, cellular_batch_admin_bytes);
|
||||||
|
CellularAdminCommand command;
|
||||||
|
command.id = get(record, 0, 8);
|
||||||
|
const auto kind = get(record, 8, 2);
|
||||||
|
if (kind > 0xFF)
|
||||||
|
return std::unexpected{CellularBatchError::format};
|
||||||
|
command.kind = static_cast<CellularAdminKind>(kind);
|
||||||
|
command.count = static_cast<std::uint16_t>(get(record, 10, 2));
|
||||||
|
command.target = get(record, 16, 8);
|
||||||
|
command.amount.energy.value = get(record, 24, 8);
|
||||||
|
for (std::size_t c = 0; c < command.amount.matter.size(); ++c)
|
||||||
|
command.amount.matter[c].value = get(record, 32 + 8 * c, 8);
|
||||||
|
if (!all_zero(record.subspan(12, 4)))
|
||||||
|
return std::unexpected{CellularBatchError::format};
|
||||||
|
step.admin.push_back(command);
|
||||||
|
offset += cellular_batch_admin_bytes;
|
||||||
|
}
|
||||||
out.ticks.push_back(std::move(step));
|
out.ticks.push_back(std::move(step));
|
||||||
}
|
}
|
||||||
if (offset != bytes.size() || !valid_ticks(out.ticks))
|
if (offset != bytes.size() || !valid_ticks(out.ticks) || !payload_version_matches(out))
|
||||||
return std::unexpected{CellularBatchError::format};
|
return std::unexpected{CellularBatchError::format};
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -433,7 +487,29 @@ decode_cellular_mutation_input(const std::array<std::uint8_t, 16>& account, std:
|
|||||||
std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
||||||
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||||
std::vector<CellularMutationOutcome>& mutation_outcomes) {
|
std::vector<CellularMutationOutcome>& mutation_outcomes) {
|
||||||
|
std::vector<CellularAdminResult> ignored;
|
||||||
|
return replay_cellular_batch(base, batch, mutation_outcomes, ignored);
|
||||||
|
}
|
||||||
|
|
||||||
|
CellularTuningResolver cellular_successor_tuning(
|
||||||
|
const CellularLives& successor,
|
||||||
|
std::function<bool(std::span<const std::uint8_t>, const std::array<std::uint8_t, 32>&)> check) {
|
||||||
|
return [rules = successor.revamp_rules(), check = std::move(check)](
|
||||||
|
std::uint64_t,
|
||||||
|
const std::array<std::uint8_t, 32>& digest) -> std::optional<CellularRevampRules> {
|
||||||
|
if (!check || !check(encode_cellular_revamp_rules(rules), digest))
|
||||||
|
return std::nullopt;
|
||||||
|
return rules;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
||||||
|
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||||
|
std::vector<CellularMutationOutcome>& mutation_outcomes,
|
||||||
|
std::vector<CellularAdminResult>& admin_results,
|
||||||
|
const CellularTuningResolver& tuning) {
|
||||||
mutation_outcomes.clear();
|
mutation_outcomes.clear();
|
||||||
|
admin_results.clear();
|
||||||
if (!owner_version_matches(base, batch))
|
if (!owner_version_matches(base, batch))
|
||||||
return std::unexpected{CellularBatchError::version};
|
return std::unexpected{CellularBatchError::version};
|
||||||
const auto& h = batch.header;
|
const auto& h = batch.header;
|
||||||
@@ -448,6 +524,7 @@ replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
|||||||
if (!replay)
|
if (!replay)
|
||||||
return std::unexpected{CellularBatchError::state};
|
return std::unexpected{CellularBatchError::state};
|
||||||
std::vector<CellularMutationOutcome> complete_outcomes;
|
std::vector<CellularMutationOutcome> complete_outcomes;
|
||||||
|
std::vector<CellularAdminResult> complete_admin;
|
||||||
for (const auto& tick : batch.ticks) {
|
for (const auto& tick : batch.ticks) {
|
||||||
const auto executed = (*replay)->advance_tick_with_mutations(tick.lives, tick.mutations);
|
const auto executed = (*replay)->advance_tick_with_mutations(tick.lives, tick.mutations);
|
||||||
if (!executed)
|
if (!executed)
|
||||||
@@ -467,8 +544,17 @@ replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
|||||||
return std::unexpected{CellularBatchError::state};
|
return std::unexpected{CellularBatchError::state};
|
||||||
*replay = std::move(*born);
|
*replay = std::move(*born);
|
||||||
}
|
}
|
||||||
|
if (!tick.admin.empty()) {
|
||||||
|
std::vector<CellularAdminResult> results;
|
||||||
|
auto applied = (*replay)->admin_candidate(tick.admin, &results, tuning);
|
||||||
|
if (!applied)
|
||||||
|
return std::unexpected{CellularBatchError::state};
|
||||||
|
*replay = std::move(*applied);
|
||||||
|
complete_admin.insert(complete_admin.end(), results.begin(), results.end());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
mutation_outcomes = std::move(complete_outcomes);
|
mutation_outcomes = std::move(complete_outcomes);
|
||||||
|
admin_results = std::move(complete_admin);
|
||||||
return std::move(*replay);
|
return std::move(*replay);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,9 @@ constexpr std::size_t cellular_life_motion_bytes = 20;
|
|||||||
// reserved zero, 32), the catalog bounds (five 4-byte fields, a reserved zero and the carbon
|
// reserved zero, 32), the catalog bounds (five 4-byte fields, a reserved zero and the carbon
|
||||||
// gate, 32), the offer interval and a reserved zero (8), and 49 mutation tunables of 80 bytes.
|
// gate, 32), the offer interval and a reserved zero (8), and 49 mutation tunables of 80 bytes.
|
||||||
// ADR-0181 uses the growth/offer/bounds reserved words for safety revision,
|
// ADR-0181 uses the growth/offer/bounds reserved words for safety revision,
|
||||||
// growth fuel seconds and split launch speed; historical zeros retain their law.
|
// growth fuel seconds and split launch speed; ADR-0182 section 14 the offer interval's for the
|
||||||
|
// heat recycle share (low 16 bits) and the absorbing drip (bit 16). Historical zeros retain
|
||||||
|
// their law.
|
||||||
constexpr std::size_t cellular_revamp_mutation_bytes = 80;
|
constexpr std::size_t cellular_revamp_mutation_bytes = 80;
|
||||||
// Then the reproduction tunables: split share, split growth, organism cap, fee scale (16) and
|
// Then the reproduction tunables: split share, split growth, organism cap, fee scale (16) and
|
||||||
// the bud fee (40).
|
// the bud fee (40).
|
||||||
@@ -235,7 +237,10 @@ void write_revamp_offers(Writer& out, const CellularRevampRules& r) {
|
|||||||
out.put(r.split_launch_um_per_s, 4);
|
out.put(r.split_launch_um_per_s, 4);
|
||||||
out.put(b.carbon_for_light);
|
out.put(b.carbon_for_light);
|
||||||
out.put(r.offer_interval_ticks, 4);
|
out.put(r.offer_interval_ticks, 4);
|
||||||
out.put(0, 4);
|
// The offer interval's reserved word: the heat recycle share (bits 0-15), the absorbing
|
||||||
|
// drip (bit 16) and the wildlife cap (bits 17-31).
|
||||||
|
out.put(r.heat_recycle_per_thousand | (r.drip_absorb ? 0x10000U : 0U) | (r.wildlife_cap << 17U),
|
||||||
|
4);
|
||||||
for (const auto& m : r.mutations) {
|
for (const auto& m : r.mutations) {
|
||||||
out.put(m.enabled ? 1 : 0, 1);
|
out.put(m.enabled ? 1 : 0, 1);
|
||||||
out.zeros(3);
|
out.zeros(3);
|
||||||
@@ -282,7 +287,11 @@ bool read_revamp_offers(Reader& in, CellularRevampRules& r) {
|
|||||||
r.split_launch_um_per_s = u32();
|
r.split_launch_um_per_s = u32();
|
||||||
b.carbon_for_light = in.get();
|
b.carbon_for_light = in.get();
|
||||||
r.offer_interval_ticks = u32();
|
r.offer_interval_ticks = u32();
|
||||||
zero = zero && in.get(4) == 0;
|
const auto cycle = in.get(4);
|
||||||
|
r.heat_recycle_per_thousand = static_cast<std::uint32_t>(cycle & 0xFFFFU);
|
||||||
|
r.drip_absorb = (cycle & 0x10000U) != 0;
|
||||||
|
r.wildlife_cap = static_cast<std::uint32_t>(cycle >> 17U);
|
||||||
|
zero = zero && (cycle >> 32U) == 0;
|
||||||
for (auto& m : r.mutations) {
|
for (auto& m : r.mutations) {
|
||||||
const auto enabled = in.get(1);
|
const auto enabled = in.get(1);
|
||||||
zero = zero && enabled <= 1 && in.get(3) == 0;
|
zero = zero && enabled <= 1 && in.get(3) == 0;
|
||||||
@@ -1344,11 +1353,22 @@ CellularLives::revamp_upgrade_candidate(const CellularRevampRules& rules, std::u
|
|||||||
next.archive.archived() != 0 || count >= rules.organism_cap || count > 255 || first == 0 ||
|
next.archive.archived() != 0 || count >= rules.organism_cap || count > 255 || first == 0 ||
|
||||||
first > cellular_bud_namespace - count)
|
first > cellular_bud_namespace - count)
|
||||||
return std::unexpected{CellularLivesError::invalid_config};
|
return std::unexpected{CellularLivesError::invalid_config};
|
||||||
for (std::uint32_t index = 0; index < count; ++index) {
|
for (std::uint32_t index = 0; index < count; ++index)
|
||||||
const auto id = first + index;
|
if (const auto error =
|
||||||
|
seed_wildlife_root(next, world(), region(), tick(), first + index, nullptr))
|
||||||
|
return std::unexpected{*error};
|
||||||
|
// Restore validates bodies, identities, history and channel-by-channel closure.
|
||||||
|
return restore((*candidate)->snapshot(), world(), region(), frame(), tick());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<CellularLivesError>
|
||||||
|
CellularLives::seed_wildlife_root(State& next, std::uint64_t world, std::uint64_t region,
|
||||||
|
std::uint64_t tick, std::uint64_t id,
|
||||||
|
accounting::Inventory* imported) {
|
||||||
|
const auto& rules = next.revamp;
|
||||||
const auto founder = biology::primitive_founder(id, id, biology::primitive_founder_v6);
|
const auto founder = biology::primitive_founder(id, id, biology::primitive_founder_v6);
|
||||||
if (!founder)
|
if (!founder)
|
||||||
return std::unexpected{CellularLivesError::biology};
|
return CellularLivesError::biology;
|
||||||
biology::GenomeDraft draft{
|
biology::GenomeDraft draft{
|
||||||
.id = id,
|
.id = id,
|
||||||
.origin_event = id,
|
.origin_event = id,
|
||||||
@@ -1358,7 +1378,7 @@ CellularLives::revamp_upgrade_candidate(const CellularRevampRules& rules, std::u
|
|||||||
.schema_version = biology::genome_schema_v7,
|
.schema_version = biology::genome_schema_v7,
|
||||||
.movement_arrangement = biology::founder_movement_arrangement,
|
.movement_arrangement = biology::founder_movement_arrangement,
|
||||||
.cellular_traits = biology::founder_cellular_traits};
|
.cellular_traits = biology::founder_cellular_traits};
|
||||||
Random random{mutation_seed(world(), region(), id, 0x57494C44U)};
|
Random random{mutation_seed(world, region, id, 0x57494C44U)};
|
||||||
const auto points = [&] { return static_cast<std::uint16_t>(75 + random.next() % 51); };
|
const auto points = [&] { return static_cast<std::uint16_t>(75 + random.next() % 51); };
|
||||||
auto& traits = *draft.cellular_traits;
|
auto& traits = *draft.cellular_traits;
|
||||||
traits.density = points();
|
traits.density = points();
|
||||||
@@ -1380,26 +1400,38 @@ CellularLives::revamp_upgrade_candidate(const CellularRevampRules& rules, std::u
|
|||||||
const auto genome = biology::Genome::create(draft);
|
const auto genome = biology::Genome::create(draft);
|
||||||
const auto budget =
|
const auto budget =
|
||||||
genome ? biology::metabolic_budget(*genome, {1000, 0},
|
genome ? biology::metabolic_budget(*genome, {1000, 0},
|
||||||
{next.config.ambient_temperature_millikelvin, {}},
|
{next.config.ambient_temperature_millikelvin, {}}, 1000,
|
||||||
1000, rules.body)
|
rules.body)
|
||||||
: std::unexpected{biology::DevelopmentError::overflow};
|
: std::unexpected{biology::DevelopmentError::overflow};
|
||||||
if (!budget)
|
if (!budget)
|
||||||
return std::unexpected{CellularLivesError::biology};
|
return CellularLivesError::biology;
|
||||||
// A normal founder's starting provision, evaluated for its randomized genome.
|
// A normal founder's starting provision, evaluated for its randomized genome.
|
||||||
const accounting::Inventory reserve{
|
const accounting::Inventory reserve{{budget->demand.value * biology::founder_reserve_seconds},
|
||||||
{budget->demand.value * biology::founder_reserve_seconds}, {}};
|
{}};
|
||||||
auto empty_body = accounting::Inventory{};
|
auto empty_body = accounting::Inventory{};
|
||||||
auto nursery = next.nursery;
|
|
||||||
auto heat = next.heat;
|
|
||||||
const auto development = biology::rules_for(genome->development_version());
|
const auto development = biology::rules_for(genome->development_version());
|
||||||
if (!development || !subtract_inventory(nursery, reserve) ||
|
if (!development)
|
||||||
!rebody(empty_body, nursery, heat, budget->body,
|
return CellularLivesError::insufficient_funding;
|
||||||
development->construction_per_kilogram))
|
// ADR-0182: an import pays exactly the reserve, the body's matter and its construction.
|
||||||
return std::unexpected{CellularLivesError::insufficient_funding};
|
auto funding = next.nursery;
|
||||||
|
if (imported) {
|
||||||
|
std::uint64_t added{};
|
||||||
|
funding = reserve;
|
||||||
|
for (std::size_t c = 0; c < funding.matter.size(); ++c) {
|
||||||
|
funding.matter[c] = budget->body.matter[c];
|
||||||
|
added += budget->body.matter[c].value;
|
||||||
|
}
|
||||||
|
const auto price = development->construction_per_kilogram;
|
||||||
|
funding.energy.value += added / 1'000 * price + added % 1'000 * price / 1'000;
|
||||||
|
}
|
||||||
|
const auto paid = funding;
|
||||||
|
auto heat = next.heat;
|
||||||
|
if (!subtract_inventory(funding, reserve) ||
|
||||||
|
!rebody(empty_body, funding, heat, budget->body, development->construction_per_kilogram))
|
||||||
|
return CellularLivesError::insufficient_funding;
|
||||||
const auto extent = budget->phenotype.extent;
|
const auto extent = budget->phenotype.extent;
|
||||||
if (next.config.area.width_um <= extent + 2000 ||
|
if (next.config.area.width_um <= extent + 2000 || next.config.area.height_um <= extent + 2000)
|
||||||
next.config.area.height_um <= extent + 2000)
|
return CellularLivesError::no_placement;
|
||||||
return std::unexpected{CellularLivesError::no_placement};
|
|
||||||
std::optional<biology::CellularPosition> position;
|
std::optional<biology::CellularPosition> position;
|
||||||
for (int attempt = 0; attempt < 1024 && !position; ++attempt) {
|
for (int attempt = 0; attempt < 1024 && !position; ++attempt) {
|
||||||
const biology::CellularPosition spot{
|
const biology::CellularPosition spot{
|
||||||
@@ -1407,10 +1439,10 @@ CellularLives::revamp_upgrade_candidate(const CellularRevampRules& rules, std::u
|
|||||||
1000 + random.next() % (next.config.area.height_um - extent - 2000)};
|
1000 + random.next() % (next.config.area.height_um - extent - 2000)};
|
||||||
bool occupied = false;
|
bool occupied = false;
|
||||||
for (const auto& other : next.lives) {
|
for (const auto& other : next.lives) {
|
||||||
const auto body = budget_for(
|
const auto body = budget_for(next.archive, other,
|
||||||
next.archive, other, next.config.ambient_temperature_millikelvin, rules.body);
|
next.config.ambient_temperature_millikelvin, rules.body);
|
||||||
if (!body)
|
if (!body)
|
||||||
return std::unexpected{CellularLivesError::biology};
|
return CellularLivesError::biology;
|
||||||
const auto side = body->phenotype.extent;
|
const auto side = body->phenotype.extent;
|
||||||
occupied = occupied || (spot.x_um < other.position.x_um + side &&
|
occupied = occupied || (spot.x_um < other.position.x_um + side &&
|
||||||
other.position.x_um < spot.x_um + extent &&
|
other.position.x_um < spot.x_um + extent &&
|
||||||
@@ -1421,24 +1453,263 @@ CellularLives::revamp_upgrade_candidate(const CellularRevampRules& rules, std::u
|
|||||||
position = spot;
|
position = spot;
|
||||||
}
|
}
|
||||||
if (!position)
|
if (!position)
|
||||||
return std::unexpected{CellularLivesError::no_placement};
|
return CellularLivesError::no_placement;
|
||||||
if (!next.archive.admit(*genome) || !next.archive.record_birth(id, id, {tick()}))
|
if (!next.archive.admit(*genome) || !next.archive.record_birth(id, id, {tick}))
|
||||||
return std::unexpected{CellularLivesError::archive};
|
return CellularLivesError::archive;
|
||||||
CellularOwnedLife life{};
|
CellularOwnedLife life{};
|
||||||
life.identity = {id, id, id, id, {tick()}};
|
life.identity = {id, id, id, id, {tick}};
|
||||||
life.source = next.nursery_config.source;
|
life.source = next.nursery_config.source;
|
||||||
life.growth = {1000, 0};
|
life.growth = {1000, 0};
|
||||||
life.position = *position;
|
life.position = *position;
|
||||||
life.body = budget->body;
|
life.body = budget->body;
|
||||||
life.reserve = reserve;
|
life.reserve = reserve;
|
||||||
life.offspring_genome = id;
|
life.offspring_genome = id;
|
||||||
next.lives.push_back(life);
|
const auto at = std::ranges::lower_bound(next.lives, id, {},
|
||||||
next.nursery = nursery;
|
[](const auto& value) { return value.identity.life; });
|
||||||
next.nursery_config.funding = nursery;
|
next.lives.insert(at, life);
|
||||||
next.heat = heat;
|
if (imported) {
|
||||||
|
if (funding != accounting::Inventory{} || !add_inventory(*imported, paid))
|
||||||
|
return CellularLivesError::conservation;
|
||||||
|
} else {
|
||||||
|
next.nursery = funding;
|
||||||
|
next.nursery_config.funding = funding;
|
||||||
}
|
}
|
||||||
// Restore validates bodies, identities, history and channel-by-channel closure.
|
next.heat = heat;
|
||||||
return restore((*candidate)->snapshot(), world(), region(), frame(), tick());
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::uint8_t, 32> cellular_admin_digest(const CellularAdminCommand& c) noexcept {
|
||||||
|
std::array<std::uint8_t, 32> digest{};
|
||||||
|
const std::array<std::uint64_t, 4> words{c.amount.energy.value, c.amount.matter[0].value,
|
||||||
|
c.amount.matter[1].value, c.amount.matter[2].value};
|
||||||
|
for (std::size_t w = 0; w < words.size(); ++w)
|
||||||
|
for (std::size_t b = 0; b < 8; ++b)
|
||||||
|
digest.at(w * 8 + b) = static_cast<std::uint8_t>(words.at(w) >> (8 * b));
|
||||||
|
return digest;
|
||||||
|
}
|
||||||
|
|
||||||
|
CellularAdminCommand
|
||||||
|
cellular_adopt_tuning_command(std::uint64_t id, std::uint64_t revision,
|
||||||
|
const std::array<std::uint8_t, 32>& digest) noexcept {
|
||||||
|
CellularAdminCommand command{id, CellularAdminKind::adopt_tuning, 0, revision, {}};
|
||||||
|
std::array<std::uint64_t, 4> words{};
|
||||||
|
for (std::size_t w = 0; w < words.size(); ++w)
|
||||||
|
for (std::size_t b = 0; b < 8; ++b)
|
||||||
|
words.at(w) |= std::uint64_t{digest.at(w * 8 + b)} << (8 * b);
|
||||||
|
command.amount.energy.value = words[0];
|
||||||
|
for (std::size_t c = 0; c < 3; ++c)
|
||||||
|
command.amount.matter.at(c).value = words.at(c + 1);
|
||||||
|
return command;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::uint8_t> encode_cellular_revamp_rules(const CellularRevampRules& r) {
|
||||||
|
std::vector<std::uint8_t> bytes;
|
||||||
|
Writer out{bytes};
|
||||||
|
out.put(r.body.essential_upkeep_per_thousand, 4);
|
||||||
|
out.put((r.step.collection_percent == 100 ? 0U : r.step.collection_percent) |
|
||||||
|
(r.step.split_evenly ? 0x10000U : 0U),
|
||||||
|
4);
|
||||||
|
for (const auto rate : r.burn_pj_per_kfg)
|
||||||
|
out.put(rate);
|
||||||
|
out.put(r.step.membrane_collection_per_mille_per_point, 4);
|
||||||
|
out.put(r.step.engulf_ratio_milli, 4);
|
||||||
|
out.put(r.step.engulf_reserve_percent, 4);
|
||||||
|
out.put(r.step.kill_bubble_per_thousand, 4);
|
||||||
|
out.put(r.drip_interval_ticks, 4);
|
||||||
|
out.put(r.reserve_load_per_thousand, 4);
|
||||||
|
out.put(r.drip_bubble_pj);
|
||||||
|
out.put(r.drip_bubble_fg);
|
||||||
|
write_revamp_offers(out, r);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cellular_admin_command_valid(const CellularAdminCommand& c) noexcept {
|
||||||
|
const bool some = c.amount != accounting::Inventory{};
|
||||||
|
switch (c.kind) {
|
||||||
|
case CellularAdminKind::remove_cell:
|
||||||
|
return c.id != 0 && c.target != 0 && c.count == 0 && !some;
|
||||||
|
case CellularAdminKind::grant_reserve:
|
||||||
|
return c.id != 0 && c.target != 0 && c.count == 0 && some;
|
||||||
|
case CellularAdminKind::add_bubbles:
|
||||||
|
case CellularAdminKind::release_pool:
|
||||||
|
return c.id != 0 && c.target == 0 && c.count >= 1 && c.count <= 256 && some;
|
||||||
|
case CellularAdminKind::add_pool:
|
||||||
|
return c.id != 0 && c.target == 0 && c.count == 0 && some;
|
||||||
|
case CellularAdminKind::spawn_wildlife:
|
||||||
|
return c.id != 0 && c.count >= 1 && c.count <= 256 && !some && c.target != 0 &&
|
||||||
|
c.target <= cellular_bud_namespace - c.count;
|
||||||
|
case CellularAdminKind::adopt_tuning:
|
||||||
|
return c.id != 0 && c.count == 0 && c.target != 0 && some && c.amount.matter[3].value == 0;
|
||||||
|
case CellularAdminKind::take_reserve:
|
||||||
|
return c.id != 0 && c.target != 0 && c.count == 0 && some;
|
||||||
|
case CellularAdminKind::remove_wildlife:
|
||||||
|
return c.id != 0 && c.target == 0 && c.count == 0 && !some;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
||||||
|
CellularLives::admin_candidate(std::span<const CellularAdminCommand> commands,
|
||||||
|
std::vector<CellularAdminResult>* results,
|
||||||
|
const CellularTuningResolver& tuning) const {
|
||||||
|
if (state_->format_version != cellular_lives_revamp_format ||
|
||||||
|
state_->rules_version < cellular_lives_revamp_rules)
|
||||||
|
return std::unexpected{CellularLivesError::version};
|
||||||
|
for (std::size_t i = 0; i < commands.size(); ++i)
|
||||||
|
if (!cellular_admin_command_valid(commands[i]) ||
|
||||||
|
(i != 0 && commands[i - 1].id >= commands[i].id))
|
||||||
|
return std::unexpected{CellularLivesError::invalid_config};
|
||||||
|
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
|
||||||
|
if (!candidate)
|
||||||
|
return std::unexpected(candidate.error());
|
||||||
|
std::vector<CellularAdminResult> report;
|
||||||
|
// A removed life's body and reserve go to the spent pool, and it leaves a corpse.
|
||||||
|
const auto remove_life = [&](State& next, std::vector<CellularOwnedLife>::iterator life) {
|
||||||
|
if (!next.archive.record_death(life->identity.organism, {tick()}))
|
||||||
|
return false;
|
||||||
|
auto single = *life;
|
||||||
|
single.revamp.members = 1; // A corpse records the single-cell extent.
|
||||||
|
const auto extent = budget_for(
|
||||||
|
next.archive, single, next.config.ambient_temperature_millikelvin, next.revamp.body);
|
||||||
|
if (!extent || !add_inventory(next.spent, life->body) ||
|
||||||
|
!add_inventory(next.spent, life->reserve))
|
||||||
|
return false;
|
||||||
|
CellularOwnedCorpse corpse{life->identity.life,
|
||||||
|
life->identity.organism,
|
||||||
|
life->source,
|
||||||
|
tick(),
|
||||||
|
life->position,
|
||||||
|
life->growth,
|
||||||
|
extent->phenotype.extent,
|
||||||
|
{},
|
||||||
|
biology::CellularDeathCause::removed,
|
||||||
|
0,
|
||||||
|
life->parent_life,
|
||||||
|
life->offspring_genome};
|
||||||
|
const auto at = std::ranges::lower_bound(next.corpses, corpse.organism, {},
|
||||||
|
&CellularOwnedCorpse::organism);
|
||||||
|
next.corpses.insert(at, corpse);
|
||||||
|
next.lives.erase(life);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
for (const auto& command : commands) {
|
||||||
|
// Each command works on a copy, kept only when it applies and still closes.
|
||||||
|
auto attempt = restore((*candidate)->snapshot(), world(), region(), frame(), tick());
|
||||||
|
if (!attempt)
|
||||||
|
return std::unexpected(attempt.error());
|
||||||
|
auto& next = *(*attempt)->state_;
|
||||||
|
bool applied = false;
|
||||||
|
const auto life = std::ranges::lower_bound(next.lives, command.target, {},
|
||||||
|
[](const auto& v) { return v.identity.life; });
|
||||||
|
const bool found = life != next.lives.end() && life->identity.life == command.target;
|
||||||
|
switch (command.kind) {
|
||||||
|
case CellularAdminKind::remove_cell:
|
||||||
|
applied = found && remove_life(next, life);
|
||||||
|
break;
|
||||||
|
case CellularAdminKind::remove_wildlife: {
|
||||||
|
std::vector<std::uint64_t> wild;
|
||||||
|
for (const auto& each : next.lives)
|
||||||
|
if (each.account == LifeAccount{})
|
||||||
|
wild.push_back(each.identity.life);
|
||||||
|
applied = !wild.empty();
|
||||||
|
for (const auto id : wild) {
|
||||||
|
const auto at = std::ranges::lower_bound(
|
||||||
|
next.lives, id, {}, [](const auto& v) { return v.identity.life; });
|
||||||
|
applied = applied && remove_life(next, at);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case CellularAdminKind::take_reserve: {
|
||||||
|
if (!found)
|
||||||
|
break;
|
||||||
|
auto amount = command.amount; // Never more than the reserve holds.
|
||||||
|
for (std::size_t c = 0; c < 5; ++c) {
|
||||||
|
auto& want = c == 0 ? amount.energy.value : amount.matter[c - 1].value;
|
||||||
|
const auto have =
|
||||||
|
c == 0 ? life->reserve.energy.value : life->reserve.matter[c - 1].value;
|
||||||
|
want = std::min(want, have);
|
||||||
|
}
|
||||||
|
applied = amount != accounting::Inventory{} &&
|
||||||
|
subtract_inventory(life->reserve, amount) &&
|
||||||
|
add_inventory(next.spent, amount);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case CellularAdminKind::grant_reserve:
|
||||||
|
applied = found && add_inventory(life->reserve, command.amount) &&
|
||||||
|
add_inventory(next.boundary.incoming, command.amount);
|
||||||
|
break;
|
||||||
|
case CellularAdminKind::add_pool:
|
||||||
|
applied = add_inventory(next.spent, command.amount) &&
|
||||||
|
add_inventory(next.boundary.incoming, command.amount);
|
||||||
|
break;
|
||||||
|
case CellularAdminKind::add_bubbles:
|
||||||
|
case CellularAdminKind::release_pool: {
|
||||||
|
const bool release = command.kind == CellularAdminKind::release_pool;
|
||||||
|
auto amount = command.amount;
|
||||||
|
if (release) // Never more than the pool holds.
|
||||||
|
for (std::size_t c = 0; c < 5; ++c) {
|
||||||
|
auto& want = c == 0 ? amount.energy.value : amount.matter[c - 1].value;
|
||||||
|
const auto have =
|
||||||
|
c == 0 ? next.spent.energy.value : next.spent.matter[c - 1].value;
|
||||||
|
want = std::min(want, have);
|
||||||
|
}
|
||||||
|
auto config = next.habitat->config();
|
||||||
|
if (amount != accounting::Inventory{} &&
|
||||||
|
(release ? subtract_inventory(next.spent, amount)
|
||||||
|
: add_inventory(next.boundary.incoming, amount)) &&
|
||||||
|
cellular_scatter_bubbles(config, amount, command.count,
|
||||||
|
mutation_seed(world(), region(), command.id, tick()),
|
||||||
|
next.nursery_config.source)) {
|
||||||
|
if (auto habitat = biology::CellularHabitat::create(std::move(config))) {
|
||||||
|
next.habitat = std::move(*habitat);
|
||||||
|
applied = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case CellularAdminKind::adopt_tuning: {
|
||||||
|
// A revision nobody can name is not a refusal: replay would diverge.
|
||||||
|
const auto rules =
|
||||||
|
tuning ? tuning(command.target, cellular_admin_digest(command)) : std::nullopt;
|
||||||
|
if (!rules)
|
||||||
|
return std::unexpected{CellularLivesError::invalid_config};
|
||||||
|
// The safety revision is a recorded law of the opening; it does not change live.
|
||||||
|
if (cellular_revamp_valid(*rules) &&
|
||||||
|
rules->safety_version == next.revamp.safety_version) {
|
||||||
|
next.revamp = *rules;
|
||||||
|
applied = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case CellularAdminKind::spawn_wildlife: {
|
||||||
|
if (next.lives.size() + command.count >= next.revamp.organism_cap)
|
||||||
|
break;
|
||||||
|
accounting::Inventory imported{};
|
||||||
|
bool ok = true;
|
||||||
|
for (std::uint16_t i = 0; ok && i < command.count; ++i) {
|
||||||
|
const auto id = command.target + i;
|
||||||
|
ok = !std::ranges::binary_search(next.lives, id, {},
|
||||||
|
[](const auto& v) { return v.identity.life; }) &&
|
||||||
|
!next.archive.find(id) &&
|
||||||
|
!seed_wildlife_root(next, world(), region(), tick(), id, &imported);
|
||||||
|
}
|
||||||
|
applied = ok && add_inventory(next.boundary.incoming, imported);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (applied) {
|
||||||
|
// Restore checks bodies, identities, history and channel-by-channel closure.
|
||||||
|
auto checked = restore((*attempt)->snapshot(), world(), region(), frame(), tick());
|
||||||
|
if (checked)
|
||||||
|
candidate = std::move(checked);
|
||||||
|
else
|
||||||
|
applied = false;
|
||||||
|
}
|
||||||
|
report.push_back({command.id, applied});
|
||||||
|
}
|
||||||
|
if (results)
|
||||||
|
*results = std::move(report);
|
||||||
|
return std::move(*candidate);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::optional<accounting::Inventory> CellularLives::budding_cost(std::uint64_t id) const {
|
std::optional<accounting::Inventory> CellularLives::budding_cost(std::uint64_t id) const {
|
||||||
@@ -2354,7 +2625,8 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
|
|||||||
const bool engulfed = corpse.cause == biology::CellularDeathCause::engulfed;
|
const bool engulfed = corpse.cause == biology::CellularDeathCause::engulfed;
|
||||||
const bool revamp_cause =
|
const bool revamp_cause =
|
||||||
revamp_version && (corpse.cause == biology::CellularDeathCause::merged ||
|
revamp_version && (corpse.cause == biology::CellularDeathCause::merged ||
|
||||||
corpse.cause == biology::CellularDeathCause::emerged);
|
corpse.cause == biology::CellularDeathCause::emerged ||
|
||||||
|
corpse.cause == biology::CellularDeathCause::removed);
|
||||||
if (padding != 0 ||
|
if (padding != 0 ||
|
||||||
(corpse.cause != biology::CellularDeathCause::starved && !engulfed &&
|
(corpse.cause != biology::CellularDeathCause::starved && !engulfed &&
|
||||||
!revamp_cause) ||
|
!revamp_cause) ||
|
||||||
@@ -3370,6 +3642,9 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
|
|||||||
if (identity == 0 || !*position ||
|
if (identity == 0 || !*position ||
|
||||||
next_lives.size() >= biology::max_cellular_tick_lives ||
|
next_lives.size() >= biology::max_cellular_tick_lives ||
|
||||||
(revamp_rules && next_lives.size() >= state_->revamp.organism_cap) ||
|
(revamp_rules && next_lives.size() >= state_->revamp.organism_cap) ||
|
||||||
|
(revamp_rules && parent->account == LifeAccount{} &&
|
||||||
|
state_->revamp.wildlife_cap != 0 &&
|
||||||
|
next_lives.size() >= state_->revamp.wildlife_cap) ||
|
||||||
next_archive.organism(identity)) {
|
next_archive.organism(identity)) {
|
||||||
if (!twin)
|
if (!twin)
|
||||||
bud_results.push_back({request.life_id, 0, CellularBudResult::no_placement});
|
bud_results.push_back({request.life_id, 0, CellularBudResult::no_placement});
|
||||||
@@ -3760,6 +4035,17 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
|
|||||||
}
|
}
|
||||||
habitat_config.patches.insert(at, made);
|
habitat_config.patches.insert(at, made);
|
||||||
}
|
}
|
||||||
|
// ADR-0182 section 14: a share of the region's heat returns to the spent pool before the
|
||||||
|
// drip, so the energy cells used cycles back like matter instead of draining away.
|
||||||
|
if (revamp_rules && state_->revamp.heat_recycle_per_thousand != 0) {
|
||||||
|
const auto heat = next_heat.energy.value;
|
||||||
|
const auto share = state_->revamp.heat_recycle_per_thousand;
|
||||||
|
const auto recycled = heat / 1'000 * share + heat % 1'000 * share / 1'000;
|
||||||
|
if (recycled > std::numeric_limits<std::uint64_t>::max() - next_spent.energy.value)
|
||||||
|
return std::unexpected{CellularLivesError::overflow};
|
||||||
|
next_heat.energy.value -= recycled;
|
||||||
|
next_spent.energy.value += recycled;
|
||||||
|
}
|
||||||
// Rules 13: the spent pool drips back as bubbles at seeded random spots.
|
// Rules 13: the spent pool drips back as bubbles at seeded random spots.
|
||||||
if (revamp_rules &&
|
if (revamp_rules &&
|
||||||
!cellular_drip_spent(habitat_config, next_spent, state_->revamp, state_->world,
|
!cellular_drip_spent(habitat_config, next_spent, state_->revamp, state_->world,
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ CellularMigration::prepare(const CellularLives& source, const CellularLives& des
|
|||||||
}
|
}
|
||||||
if (moving.empty())
|
if (moving.empty())
|
||||||
return std::unexpected(CellularMigrationError::ineligible);
|
return std::unexpected(CellularMigrationError::ineligible);
|
||||||
if (destination.lives().size() + moving.size() > biology::max_cellular_tick_lives)
|
if (destination.lives().size() + moving.size() > biology::max_cellular_frozen_lives)
|
||||||
return std::unexpected(CellularMigrationError::capacity);
|
return std::unexpected(CellularMigrationError::capacity);
|
||||||
const auto area = destination.area();
|
const auto area = destination.area();
|
||||||
for (const auto& life : moving) {
|
for (const auto& life : moving) {
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ bool shape(const CellularMigrationTrace& trace) {
|
|||||||
trace.representation != CellularMigrationRepresentation::population) ||
|
trace.representation != CellularMigrationRepresentation::population) ||
|
||||||
trace.world == 0 || trace.frame == 0 || trace.tick == 0 || !valid_request(trace.request) ||
|
trace.world == 0 || trace.frame == 0 || trace.tick == 0 || !valid_request(trace.request) ||
|
||||||
trace.transferred == accounting::Inventory{} || trace.members.empty() ||
|
trace.transferred == accounting::Inventory{} || trace.members.empty() ||
|
||||||
trace.members.size() > biology::max_cellular_tick_lives ||
|
trace.members.size() > biology::max_cellular_frozen_lives ||
|
||||||
!std::ranges::is_sorted(trace.members) ||
|
!std::ranges::is_sorted(trace.members) ||
|
||||||
std::ranges::adjacent_find(trace.members) != trace.members.end())
|
std::ranges::adjacent_find(trace.members) != trace.members.end())
|
||||||
return false;
|
return false;
|
||||||
@@ -209,7 +209,7 @@ decode_migration_trace(std::span<const std::uint8_t> bytes) {
|
|||||||
for (auto& mass : trace.transferred.matter)
|
for (auto& mass : trace.transferred.matter)
|
||||||
mass.value = in.get();
|
mass.value = in.get();
|
||||||
const auto count = in.get(4);
|
const auto count = in.get(4);
|
||||||
if (in.get(4) != 0 || count == 0 || count > biology::max_cellular_tick_lives ||
|
if (in.get(4) != 0 || count == 0 || count > biology::max_cellular_frozen_lives ||
|
||||||
bytes.size() != migration_trace_header_bytes + 8 * count + 8)
|
bytes.size() != migration_trace_header_bytes + 8 * count + 8)
|
||||||
return std::unexpected(CellularMigrationError::format);
|
return std::unexpected(CellularMigrationError::format);
|
||||||
trace.members.reserve(static_cast<std::size_t>(count));
|
trace.members.reserve(static_cast<std::size_t>(count));
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ summarize_cellular_play(const CellularLives& state) {
|
|||||||
++summary.engulfed;
|
++summary.engulfed;
|
||||||
break;
|
break;
|
||||||
case biology::CellularDeathCause::unrecorded:
|
case biology::CellularDeathCause::unrecorded:
|
||||||
|
case biology::CellularDeathCause::removed: // ADR-0182: an operator's, not biology's.
|
||||||
++summary.unrecorded;
|
++summary.unrecorded;
|
||||||
break;
|
break;
|
||||||
case biology::CellularDeathCause::merged:
|
case biology::CellularDeathCause::merged:
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ bool shape(const CellularPopulationBatch& batch, bool recording) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
for (const auto& boundary : batch.boundaries) {
|
for (const auto& boundary : batch.boundaries) {
|
||||||
if (boundary.members.size() > biology::max_cellular_tick_lives)
|
if (boundary.members.size() > biology::max_cellular_frozen_lives)
|
||||||
return false;
|
return false;
|
||||||
std::uint64_t previous = 0;
|
std::uint64_t previous = 0;
|
||||||
for (const auto& member : boundary.members) {
|
for (const auto& member : boundary.members) {
|
||||||
@@ -313,7 +313,7 @@ decode_population_batch(std::span<const std::uint8_t> bytes) {
|
|||||||
CellularPopulationBoundary boundary;
|
CellularPopulationBoundary boundary;
|
||||||
boundary.sequence = boundary_reader.get();
|
boundary.sequence = boundary_reader.get();
|
||||||
const auto members = boundary_reader.get();
|
const auto members = boundary_reader.get();
|
||||||
if (members > biology::max_cellular_tick_lives || members * 16 > bytes.size() - at - 16)
|
if (members > biology::max_cellular_frozen_lives || members * 16 > bytes.size() - at - 16)
|
||||||
return std::unexpected(CellularPopulationError::format);
|
return std::unexpected(CellularPopulationError::format);
|
||||||
for (std::uint64_t member = 0; member < members; ++member)
|
for (std::uint64_t member = 0; member < members; ++member)
|
||||||
boundary.members.push_back({boundary_reader.get(), boundary_reader.get()});
|
boundary.members.push_back({boundary_reader.get(), boundary_reader.get()});
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ CellularPopulation::restore(std::span<const std::uint8_t> bytes, std::uint64_t w
|
|||||||
reader.get(8) != tick)
|
reader.get(8) != tick)
|
||||||
return std::unexpected(CellularPopulationError::identity);
|
return std::unexpected(CellularPopulationError::identity);
|
||||||
const auto biological_bytes = reader.get(8), count = reader.get(8);
|
const auto biological_bytes = reader.get(8), count = reader.get(8);
|
||||||
if (count > biology::max_cellular_tick_lives || biological_bytes > max_cellular_lives_bytes ||
|
if (count > biology::max_cellular_frozen_lives || biological_bytes > max_cellular_lives_bytes ||
|
||||||
biological_bytes == 0 ||
|
biological_bytes == 0 ||
|
||||||
bytes.size() != cellular_population_header_bytes + count * 16 + biological_bytes + 8)
|
bytes.size() != cellular_population_header_bytes + count * 16 + biological_bytes + 8)
|
||||||
return std::unexpected(CellularPopulationError::format);
|
return std::unexpected(CellularPopulationError::format);
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept {
|
|||||||
step.engulf_ratio_milli <= 1'000'000 && step.engulf_reserve_percent <= 100 &&
|
step.engulf_ratio_milli <= 1'000'000 && step.engulf_reserve_percent <= 100 &&
|
||||||
step.kill_bubble_per_thousand <= 1'000 && rules.drip_interval_ticks <= 72'000 &&
|
step.kill_bubble_per_thousand <= 1'000 && rules.drip_interval_ticks <= 72'000 &&
|
||||||
rules.drip_bubble_pj <= most && rules.drip_bubble_fg <= most &&
|
rules.drip_bubble_pj <= most && rules.drip_bubble_fg <= most &&
|
||||||
|
rules.heat_recycle_per_thousand <= 1'000 &&
|
||||||
(rules.drip_interval_ticks == 0 ||
|
(rules.drip_interval_ticks == 0 ||
|
||||||
(rules.drip_bubble_pj != 0 && rules.drip_bubble_fg != 0)) &&
|
(rules.drip_bubble_pj != 0 && rules.drip_bubble_fg != 0)) &&
|
||||||
rules.reserve_load_per_thousand <= 1'000 &&
|
rules.reserve_load_per_thousand <= 1'000 &&
|
||||||
@@ -62,9 +63,10 @@ bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept {
|
|||||||
std::ranges::all_of(rules.bud_fee.matter,
|
std::ranges::all_of(rules.bud_fee.matter,
|
||||||
[](const accounting::Femtograms& f) { return f.value <= most; }) &&
|
[](const accounting::Femtograms& f) { return f.value <= most; }) &&
|
||||||
rules.organism_cap != 0 && rules.organism_cap <= biology::max_cellular_tick_lives &&
|
rules.organism_cap != 0 && rules.organism_cap <= biology::max_cellular_tick_lives &&
|
||||||
rules.organism_load_per_thousand <= 10'000 && rules.emerge_members >= 2 &&
|
rules.wildlife_cap <= rules.organism_cap && rules.organism_load_per_thousand <= 10'000 &&
|
||||||
rules.emerge_members <= 10'000 && rules.emerge_mass_fg <= most &&
|
rules.emerge_members >= 2 && rules.emerge_members <= 10'000 &&
|
||||||
rules.emerge_reserve_pj <= most && cellular_revamp_offer_rules_valid(rules);
|
rules.emerge_mass_fg <= most && rules.emerge_reserve_pj <= most &&
|
||||||
|
cellular_revamp_offer_rules_valid(rules);
|
||||||
}
|
}
|
||||||
|
|
||||||
biology::CellularHandling cellular_loaded_handling(const biology::CellularHandling& handling,
|
biology::CellularHandling cellular_loaded_handling(const biology::CellularHandling& handling,
|
||||||
@@ -104,10 +106,34 @@ bool cellular_drip_spent(biology::CellularHabitatConfig& config, accounting::Inv
|
|||||||
// Both draws happen for every channel, so a channel's spot never depends on another's.
|
// Both draws happen for every channel, so a channel's spot never depends on another's.
|
||||||
const auto x = random.next();
|
const auto x = random.next();
|
||||||
const auto y = random.next();
|
const auto y = random.next();
|
||||||
if (pool == 0 || config.patches.size() >= biology::max_cellular_liquid_deposits)
|
if (pool == 0)
|
||||||
continue;
|
continue;
|
||||||
biology::CellularPatchAddress address{static_cast<std::uint32_t>(x % config.width_um),
|
biology::CellularPatchAddress address{static_cast<std::uint32_t>(x % config.width_um),
|
||||||
static_cast<std::uint32_t>(y % config.height_um)};
|
static_cast<std::uint32_t>(y % config.height_um)};
|
||||||
|
if (config.patches.size() >= biology::max_cellular_liquid_deposits) {
|
||||||
|
if (!rules.drip_absorb)
|
||||||
|
continue;
|
||||||
|
// At the limit an existing bubble takes the drip, as if absorbing it from the
|
||||||
|
// water: the first bubble at or after the spot in address order, wrapping.
|
||||||
|
const auto start = std::ranges::lower_bound(config.patches, address, {}, by_address);
|
||||||
|
const auto is_bubble = [](const biology::CellularPatch& patch) {
|
||||||
|
return patch.kind == biology::CellularDepositKind::mote;
|
||||||
|
};
|
||||||
|
auto host = std::ranges::find_if(start, config.patches.end(), is_bubble);
|
||||||
|
if (host == config.patches.end()) {
|
||||||
|
host = std::ranges::find_if(config.patches.begin(), start, is_bubble);
|
||||||
|
if (host == start)
|
||||||
|
continue; // No bubble at all: the drip waits.
|
||||||
|
}
|
||||||
|
const auto amount = std::min(pool, cap);
|
||||||
|
auto& stock =
|
||||||
|
channel == 0 ? host->stock.energy.value : host->stock.matter[channel - 1].value;
|
||||||
|
if (amount > std::numeric_limits<std::uint64_t>::max() - stock)
|
||||||
|
continue;
|
||||||
|
stock += amount;
|
||||||
|
pool -= amount;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
auto at = std::ranges::lower_bound(config.patches, address, {}, by_address);
|
auto at = std::ranges::lower_bound(config.patches, address, {}, by_address);
|
||||||
while (at != config.patches.end() && at->address == address) {
|
while (at != config.patches.end() && at->address == address) {
|
||||||
address.x_um = address.x_um + 1 < config.width_um ? address.x_um + 1 : 0;
|
address.x_um = address.x_um + 1 < config.width_um ? address.x_um + 1 : 0;
|
||||||
@@ -133,6 +159,44 @@ bool cellular_drip_spent(biology::CellularHabitatConfig& config, accounting::Inv
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool cellular_scatter_bubbles(biology::CellularHabitatConfig& config,
|
||||||
|
const accounting::Inventory& amount, std::uint16_t count,
|
||||||
|
std::uint64_t seed, std::uint64_t source) {
|
||||||
|
if (count == 0 || config.patches.size() + count > biology::max_cellular_liquid_deposits ||
|
||||||
|
config.next_deposit > std::numeric_limits<std::uint32_t>::max() - count ||
|
||||||
|
config.width_um == 0 || config.height_um == 0)
|
||||||
|
return false;
|
||||||
|
Random random{seed};
|
||||||
|
const auto by_address = [](const biology::CellularPatch& patch) { return patch.address; };
|
||||||
|
for (std::uint16_t i = 0; i < count; ++i) {
|
||||||
|
biology::CellularPatchAddress address{
|
||||||
|
static_cast<std::uint32_t>(random.next() % config.width_um),
|
||||||
|
static_cast<std::uint32_t>(random.next() % config.height_um)};
|
||||||
|
auto at = std::ranges::lower_bound(config.patches, address, {}, by_address);
|
||||||
|
while (at != config.patches.end() && at->address == address) {
|
||||||
|
address.x_um = address.x_um + 1 < config.width_um ? address.x_um + 1 : 0;
|
||||||
|
at = std::ranges::lower_bound(config.patches, address, {}, by_address);
|
||||||
|
}
|
||||||
|
const bool last = i + 1 == count;
|
||||||
|
const auto share = [&](std::uint64_t total) {
|
||||||
|
return total / count + (last ? total % count : 0);
|
||||||
|
};
|
||||||
|
biology::CellularPatch bubble{address,
|
||||||
|
source,
|
||||||
|
{},
|
||||||
|
config.next_deposit++,
|
||||||
|
biology::cellular_mote_radius_um,
|
||||||
|
biology::CellularDepositKind::mote};
|
||||||
|
bubble.merged = 1;
|
||||||
|
bubble.stock.energy.value = share(amount.energy.value);
|
||||||
|
for (std::size_t c = 0; c < amount.matter.size(); ++c)
|
||||||
|
bubble.stock.matter[c].value = share(amount.matter[c].value);
|
||||||
|
if (bubble.stock != accounting::Inventory{})
|
||||||
|
config.patches.insert(at, bubble);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
std::optional<CellularRevampOffer> cellular_draw_offer(const biology::Genome& plan,
|
std::optional<CellularRevampOffer> cellular_draw_offer(const biology::Genome& plan,
|
||||||
const CellularRevampLife& life,
|
const CellularRevampLife& life,
|
||||||
const CellularRevampRules& rules,
|
const CellularRevampRules& rules,
|
||||||
@@ -262,6 +326,8 @@ CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& t
|
|||||||
.drip_interval_ticks = u32(t.spent_drip_interval_ticks),
|
.drip_interval_ticks = u32(t.spent_drip_interval_ticks),
|
||||||
.drip_bubble_pj = u64(t.spent_drip_bubble_pj),
|
.drip_bubble_pj = u64(t.spent_drip_bubble_pj),
|
||||||
.drip_bubble_fg = u64(t.spent_drip_bubble_fg),
|
.drip_bubble_fg = u64(t.spent_drip_bubble_fg),
|
||||||
|
.heat_recycle_per_thousand = u32(t.spent_heat_recycle_per_mille),
|
||||||
|
.drip_absorb = t.spent_drip_absorb != 0,
|
||||||
.reserve_load_per_thousand = u32(t.body_reserve_load_per_mille),
|
.reserve_load_per_thousand = u32(t.body_reserve_load_per_mille),
|
||||||
.growth_per_tick_centi_mille = u32(t.body_growth_per_tick_centi_mille),
|
.growth_per_tick_centi_mille = u32(t.body_growth_per_tick_centi_mille),
|
||||||
.offers = {.options = u32(t.mutation_options),
|
.offers = {.options = u32(t.mutation_options),
|
||||||
@@ -288,6 +354,7 @@ CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& t
|
|||||||
accounting::Femtograms{u64(t.reproduction_bud_fee_o_fg)}}},
|
accounting::Femtograms{u64(t.reproduction_bud_fee_o_fg)}}},
|
||||||
.bud_fee_scale_percent = u32(t.reproduction_bud_fee_scale_percent),
|
.bud_fee_scale_percent = u32(t.reproduction_bud_fee_scale_percent),
|
||||||
.organism_cap = u32(t.reproduction_organism_cap),
|
.organism_cap = u32(t.reproduction_organism_cap),
|
||||||
|
.wildlife_cap = u32(t.reproduction_wildlife_cap),
|
||||||
.organism_load_per_thousand = u32(t.organism_load_per_mille),
|
.organism_load_per_thousand = u32(t.organism_load_per_mille),
|
||||||
.emerge_members = u32(t.organism_emerge_members),
|
.emerge_members = u32(t.organism_emerge_members),
|
||||||
.emerge_mass_fg = u64(t.organism_emerge_mass_fg),
|
.emerge_mass_fg = u64(t.organism_emerge_mass_fg),
|
||||||
|
|||||||
+47
-13
@@ -1,8 +1,10 @@
|
|||||||
#include "evo/server/ops_http.hpp"
|
#include "evo/server/ops_http.hpp"
|
||||||
|
#include <algorithm>
|
||||||
#include <arpa/inet.h>
|
#include <arpa/inet.h>
|
||||||
#include <cerrno>
|
#include <cerrno>
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
#include <netinet/in.h>
|
#include <netinet/in.h>
|
||||||
|
#include <optional>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
|
||||||
@@ -25,6 +27,8 @@ const char* reason(int status) {
|
|||||||
return "Too Many Requests";
|
return "Too Many Requests";
|
||||||
case 405:
|
case 405:
|
||||||
return "Method Not Allowed";
|
return "Method Not Allowed";
|
||||||
|
case 413:
|
||||||
|
return "Content Too Large";
|
||||||
case 431:
|
case 431:
|
||||||
return "Request Header Fields Too Large";
|
return "Request Header Fields Too Large";
|
||||||
case 503:
|
case 503:
|
||||||
@@ -134,7 +138,7 @@ void OpsServer::respond(Connection& c, const OpsHandler& handler) {
|
|||||||
c.out = encode(response);
|
c.out = encode(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
void OpsServer::respond_api(Connection& c, const ApiHandler& handler) {
|
void OpsServer::respond_api(Connection& c, const ApiHandler& handler, std::size_t body_limit) {
|
||||||
OpsResponse response;
|
OpsResponse response;
|
||||||
const std::string_view request = c.in;
|
const std::string_view request = c.in;
|
||||||
const auto line_end = request.find("\r\n");
|
const auto line_end = request.find("\r\n");
|
||||||
@@ -147,8 +151,14 @@ void OpsServer::respond_api(Connection& c, const ApiHandler& handler) {
|
|||||||
}
|
}
|
||||||
const auto method = line.substr(0, first);
|
const auto method = line.substr(0, first);
|
||||||
const auto path = line.substr(first + 1, second - first - 1);
|
const auto path = line.substr(first + 1, second - first - 1);
|
||||||
|
// The route is bounded separately from the query. OAuth authorization-code callbacks
|
||||||
|
// carry state, session_state, and code parameters that legitimately make the request
|
||||||
|
// target longer than the route limit; AdminApi strips the query before routing.
|
||||||
|
const auto query = path.find('?');
|
||||||
|
const auto route = path.substr(0, query);
|
||||||
std::string_view authorization;
|
std::string_view authorization;
|
||||||
bool has_body = false;
|
bool bad_body = false;
|
||||||
|
std::optional<std::size_t> length;
|
||||||
// Header lines up to the blank line; names are case-insensitive.
|
// Header lines up to the blank line; names are case-insensitive.
|
||||||
auto at = line_end + 2;
|
auto at = line_end + 2;
|
||||||
while (at < request.size()) {
|
while (at < request.size()) {
|
||||||
@@ -164,20 +174,39 @@ void OpsServer::respond_api(Connection& c, const ApiHandler& handler) {
|
|||||||
auto value = header.substr(colon + 1);
|
auto value = header.substr(colon + 1);
|
||||||
while (!value.empty() && value.front() == ' ')
|
while (!value.empty() && value.front() == ' ')
|
||||||
value.remove_prefix(1);
|
value.remove_prefix(1);
|
||||||
if (name == "authorization")
|
if (name == "authorization") {
|
||||||
authorization = value;
|
authorization = value;
|
||||||
else if ((name == "content-length" && value != "0") || name == "transfer-encoding")
|
} else if (name == "content-length") {
|
||||||
has_body = true;
|
std::size_t bytes{};
|
||||||
|
const auto [stop, ec] =
|
||||||
|
std::from_chars(value.data(), value.data() + value.size(), bytes);
|
||||||
|
if (length || value.empty() || ec != std::errc{} ||
|
||||||
|
stop != value.data() + value.size())
|
||||||
|
bad_body = true;
|
||||||
|
else
|
||||||
|
length = bytes;
|
||||||
|
} else if (name == "transfer-encoding") {
|
||||||
|
bad_body = true; // Chunked bodies are not supported.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
at = end + 2;
|
at = end + 2;
|
||||||
}
|
}
|
||||||
|
const auto body_at = request.find("\r\n\r\n") + 4;
|
||||||
|
const auto body_size = length.value_or(0);
|
||||||
|
if (!bad_body && body_size > 0 && body_size <= body_limit &&
|
||||||
|
request.size() < body_at + body_size)
|
||||||
|
return; // The rest of the body is still arriving.
|
||||||
|
const bool has_body = bad_body || body_size > 0;
|
||||||
if (method != "GET" && method != "POST")
|
if (method != "GET" && method != "POST")
|
||||||
response = {405, "method not allowed\n"};
|
response = {405, "method not allowed\n"};
|
||||||
else if (path.empty() || path.front() != '/' || path.size() > 256 || !printable(path) ||
|
else if (!bad_body && body_limit > 0 && body_size > body_limit)
|
||||||
has_body)
|
response = {413, "request body too large\n"};
|
||||||
|
else if (route.empty() || route.front() != '/' || route.size() > 256 || !printable(path) ||
|
||||||
|
(has_body && (body_limit == 0 || bad_body || method != "POST" ||
|
||||||
|
request.size() != body_at + body_size)))
|
||||||
response = {400, "bad request\n"};
|
response = {400, "bad request\n"};
|
||||||
else
|
else
|
||||||
response = handler({method, path, authorization});
|
response = handler({method, path, authorization, request.substr(body_at, body_size)});
|
||||||
if (response.body.size() > response_limit_)
|
if (response.body.size() > response_limit_)
|
||||||
response = {500, "response too large\n"};
|
response = {500, "response too large\n"};
|
||||||
c.out = encode(response);
|
c.out = encode(response);
|
||||||
@@ -187,8 +216,10 @@ void OpsServer::serve(const OpsHandler& handler) {
|
|||||||
serve_with(max_request_bytes, [&](Connection& c) { respond(c, handler); });
|
serve_with(max_request_bytes, [&](Connection& c) { respond(c, handler); });
|
||||||
}
|
}
|
||||||
|
|
||||||
void OpsServer::serve_api(const ApiHandler& handler) {
|
void OpsServer::serve_api(const ApiHandler& handler, std::size_t body_limit) {
|
||||||
serve_with(max_api_request_bytes, [&](Connection& c) { respond_api(c, handler); });
|
body_limit = std::min(body_limit, max_api_body_bytes);
|
||||||
|
serve_with(max_api_request_bytes + body_limit,
|
||||||
|
[&](Connection& c) { respond_api(c, handler, body_limit); });
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename Answer>
|
template <typename Answer>
|
||||||
@@ -211,8 +242,9 @@ void OpsServer::serve_with(std::size_t request_limit, const Answer& answer) {
|
|||||||
bool done = false;
|
bool done = false;
|
||||||
// Read before expiring: a complete request that waited behind a bounded host
|
// Read before expiring: a complete request that waited behind a bounded host
|
||||||
// step is still answered; only incomplete or unsent work expires.
|
// step is still answered; only incomplete or unsent work expires.
|
||||||
if (c.out.empty()) {
|
// A few reads per call, so a request body arrives well inside the deadline.
|
||||||
char chunk[1024];
|
for (int read = 0; read < 16 && !done && c.out.empty(); ++read) {
|
||||||
|
char chunk[4096];
|
||||||
const auto n = ::recv(c.fd, chunk, sizeof chunk, 0);
|
const auto n = ::recv(c.fd, chunk, sizeof chunk, 0);
|
||||||
if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) {
|
if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) {
|
||||||
done = true;
|
done = true;
|
||||||
@@ -221,8 +253,10 @@ void OpsServer::serve_with(std::size_t request_limit, const Answer& answer) {
|
|||||||
if (c.in.size() > request_limit)
|
if (c.in.size() > request_limit)
|
||||||
c.out = encode({431, "request too large\n"});
|
c.out = encode({431, "request too large\n"});
|
||||||
else if (c.in.find("\r\n\r\n") != std::string::npos)
|
else if (c.in.find("\r\n\r\n") != std::string::npos)
|
||||||
answer(c);
|
answer(c); // Leaves c.out empty while a body is still arriving.
|
||||||
}
|
}
|
||||||
|
if (n < static_cast<long>(sizeof chunk))
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
if (!done && !c.out.empty()) {
|
if (!done && !c.out.empty()) {
|
||||||
const auto n = ::send(c.fd, c.out.data() + c.sent, c.out.size() - c.sent, MSG_NOSIGNAL);
|
const auto n = ::send(c.fd, c.out.data() + c.sent, c.out.size() - c.sent, MSG_NOSIGNAL);
|
||||||
|
|||||||
@@ -170,6 +170,33 @@ prepare_cellular_session_tick(const CellularLives& state, std::uint64_t tick,
|
|||||||
return prepared;
|
return prepared;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<network::CarriedAction>
|
||||||
|
keep_one_action_per_account(std::vector<network::CarriedAction>& actions) {
|
||||||
|
const auto discrete = [](const network::CarriedAction& action) {
|
||||||
|
if (!action.cellular_input)
|
||||||
|
return false;
|
||||||
|
const auto input = network::decode_cellular_action_input(*action.cellular_input);
|
||||||
|
return input && (input->engulf || input->bud || input->become || input->emerge);
|
||||||
|
};
|
||||||
|
std::vector<network::CarriedAction> kept, superseded;
|
||||||
|
kept.reserve(actions.size());
|
||||||
|
for (const auto& action : actions) {
|
||||||
|
const auto same = std::ranges::find_if(kept, [&](const network::CarriedAction& other) {
|
||||||
|
return other.account.bytes == action.account.bytes;
|
||||||
|
});
|
||||||
|
if (same == kept.end()) {
|
||||||
|
kept.push_back(action);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bool replaces = discrete(action) != discrete(*same)
|
||||||
|
? discrete(action)
|
||||||
|
: action.action_id > same->action_id;
|
||||||
|
superseded.push_back(replaces ? std::exchange(*same, action) : action);
|
||||||
|
}
|
||||||
|
actions = std::move(kept);
|
||||||
|
return superseded;
|
||||||
|
}
|
||||||
|
|
||||||
std::expected<CellularSessionBatchBuilder, CellularSessionBatchError>
|
std::expected<CellularSessionBatchBuilder, CellularSessionBatchError>
|
||||||
CellularSessionBatchBuilder::create(const CellularLives& committed_state,
|
CellularSessionBatchBuilder::create(const CellularLives& committed_state,
|
||||||
const persistence::RegionHead& committed_head) {
|
const persistence::RegionHead& committed_head) {
|
||||||
@@ -201,24 +228,33 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
|||||||
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||||
std::span<const network::CarriedAction> actions,
|
std::span<const network::CarriedAction> actions,
|
||||||
std::span<const CellularTickIntents::Birth> births,
|
std::span<const CellularTickIntents::Birth> births,
|
||||||
std::span<const persistence::CellularMutationReservation> mutations) {
|
std::span<const persistence::CellularMutationReservation> mutations,
|
||||||
return append_impl(tick, baseline, actions, births, mutations, false);
|
std::span<const CellularAdminCommand> admin) {
|
||||||
|
return append_impl(tick, baseline, actions, births, mutations, admin, false);
|
||||||
}
|
}
|
||||||
std::expected<void, CellularSessionBatchError>
|
std::expected<void, CellularSessionBatchError>
|
||||||
CellularSessionBatchBuilder::append_with_birth_refusals(
|
CellularSessionBatchBuilder::append_with_birth_refusals(
|
||||||
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||||
std::span<const network::CarriedAction> actions,
|
std::span<const network::CarriedAction> actions,
|
||||||
std::span<const CellularTickIntents::Birth> births,
|
std::span<const CellularTickIntents::Birth> births,
|
||||||
std::span<const persistence::CellularMutationReservation> mutations) {
|
std::span<const persistence::CellularMutationReservation> mutations,
|
||||||
return append_impl(tick, baseline, actions, births, mutations, true);
|
std::span<const CellularAdminCommand> admin) {
|
||||||
|
return append_impl(tick, baseline, actions, births, mutations, admin, true);
|
||||||
}
|
}
|
||||||
std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::append_impl(
|
std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::append_impl(
|
||||||
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||||
std::span<const network::CarriedAction> actions,
|
std::span<const network::CarriedAction> actions,
|
||||||
std::span<const CellularTickIntents::Birth> births,
|
std::span<const CellularTickIntents::Birth> births,
|
||||||
std::span<const persistence::CellularMutationReservation> mutations, bool allow_refusals) {
|
std::span<const persistence::CellularMutationReservation> mutations,
|
||||||
|
std::span<const CellularAdminCommand> admin, bool allow_refusals) {
|
||||||
if (batch_.ticks.size() >= max_cellular_batch_ticks)
|
if (batch_.ticks.size() >= max_cellular_batch_ticks)
|
||||||
return std::unexpected{CellularSessionBatchError::batch_full};
|
return std::unexpected{CellularSessionBatchError::batch_full};
|
||||||
|
// ADR-0182: a command appears once in a publication.
|
||||||
|
for (const auto& command : admin)
|
||||||
|
for (const auto& previous_tick : batch_.ticks)
|
||||||
|
if (std::ranges::find(previous_tick.admin, command.id, &CellularAdminCommand::id) !=
|
||||||
|
previous_tick.admin.end())
|
||||||
|
return std::unexpected{CellularSessionBatchError::duplicate_action};
|
||||||
if (actions_.size() + actions.size() > max_cellular_action_records)
|
if (actions_.size() + actions.size() > max_cellular_action_records)
|
||||||
return std::unexpected{CellularSessionBatchError::action_limit};
|
return std::unexpected{CellularSessionBatchError::action_limit};
|
||||||
if (mutation_actions_.size() + mutations.size() > max_cellular_action_records)
|
if (mutation_actions_.size() + mutations.size() > max_cellular_action_records)
|
||||||
@@ -267,7 +303,7 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
|||||||
// it byte-for-byte unchanged: check the encodings first, then advance in place. A full
|
// it byte-for-byte unchanged: check the encodings first, then advance in place. A full
|
||||||
// copy per tick costs a restore of the whole region (rules-12 regions hold thousands of
|
// copy per tick costs a restore of the whole region (rules-12 regions hold thousands of
|
||||||
// deposits).
|
// deposits).
|
||||||
if (prepared->intents.births.empty()) {
|
if (prepared->intents.births.empty() && admin.empty()) {
|
||||||
auto next_batch = batch_;
|
auto next_batch = batch_;
|
||||||
next_batch.ticks.push_back(prepared->intents);
|
next_batch.ticks.push_back(prepared->intents);
|
||||||
next_batch.header.end_tick = tick;
|
next_batch.header.end_tick = tick;
|
||||||
@@ -325,8 +361,20 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
|||||||
accepted_births.push_back(birth);
|
accepted_births.push_back(birth);
|
||||||
}
|
}
|
||||||
prepared->intents.births = std::move(accepted_births);
|
prepared->intents.births = std::move(accepted_births);
|
||||||
|
std::vector<CellularAdminResult> admin_results;
|
||||||
|
if (!admin.empty()) {
|
||||||
|
auto applied = (*next)->admin_candidate(admin, &admin_results, tuning_);
|
||||||
|
if (!applied) {
|
||||||
|
last_lives_error_ = applied.error();
|
||||||
|
return std::unexpected{CellularSessionBatchError::biology};
|
||||||
|
}
|
||||||
|
*next = std::move(*applied);
|
||||||
|
prepared->intents.admin.assign(admin.begin(), admin.end());
|
||||||
|
}
|
||||||
|
|
||||||
auto next_batch = batch_;
|
auto next_batch = batch_;
|
||||||
|
if (!admin.empty())
|
||||||
|
next_batch.format_version = cellular_batch_admin_format;
|
||||||
next_batch.ticks.push_back(std::move(prepared->intents));
|
next_batch.ticks.push_back(std::move(prepared->intents));
|
||||||
next_batch.header.end_tick = tick;
|
next_batch.header.end_tick = tick;
|
||||||
if (!encode_cellular_batch(next_batch))
|
if (!encode_cellular_batch(next_batch))
|
||||||
@@ -345,6 +393,7 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
|||||||
actions_.insert(actions_.end(), prepared->actions.begin(), prepared->actions.end());
|
actions_.insert(actions_.end(), prepared->actions.begin(), prepared->actions.end());
|
||||||
mutation_actions_ = next_mutation_actions;
|
mutation_actions_ = next_mutation_actions;
|
||||||
refused_births_.insert(refused_births_.end(), refused_births.begin(), refused_births.end());
|
refused_births_.insert(refused_births_.end(), refused_births.begin(), refused_births.end());
|
||||||
|
admin_results_.insert(admin_results_.end(), admin_results.begin(), admin_results.end());
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
} // namespace evo::server
|
} // namespace evo::server
|
||||||
|
|||||||
@@ -128,6 +128,7 @@ struct RegionSessions::Impl {
|
|||||||
Clock::time_point next_ghosts{}, next_overdue{};
|
Clock::time_point next_ghosts{}, next_overdue{};
|
||||||
std::optional<network::SessionInterest> default_interest;
|
std::optional<network::SessionInterest> default_interest;
|
||||||
bool refuse_logins{}; // Load governor (ADR-0097).
|
bool refuse_logins{}; // Load governor (ADR-0097).
|
||||||
|
bool admission_closed{}; // Session window closed (ADR-0087).
|
||||||
std::uint64_t refused_load{}; // Grant logins refused for load.
|
std::uint64_t refused_load{}; // Grant logins refused for load.
|
||||||
HostFacts facts;
|
HostFacts facts;
|
||||||
std::vector<Connection> connections;
|
std::vector<Connection> connections;
|
||||||
@@ -264,6 +265,8 @@ struct RegionSessions::Impl {
|
|||||||
Clock::time_point now) {
|
Clock::time_point now) {
|
||||||
if (m.required_features != 0)
|
if (m.required_features != 0)
|
||||||
return close(c, SessionCloseReason::protocol, now);
|
return close(c, SessionCloseReason::protocol, now);
|
||||||
|
if (admission_closed) // No session window: before any signature work.
|
||||||
|
return close(c, SessionCloseReason::shutdown, now);
|
||||||
if (!control.attempt(now_seconds)) // Region-wide, before signature work.
|
if (!control.attempt(now_seconds)) // Region-wide, before signature work.
|
||||||
return close(c, SessionCloseReason::rate_limited, now);
|
return close(c, SessionCloseReason::rate_limited, now);
|
||||||
if (network::looks_like_handoff_ticket(m.grant))
|
if (network::looks_like_handoff_ticket(m.grant))
|
||||||
@@ -1079,6 +1082,14 @@ std::optional<std::uint64_t> RegionSessions::holder(const network::AccountId& ac
|
|||||||
return impl_->control.holder(account);
|
return impl_->control.holder(account);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void RegionSessions::set_admission(bool open) noexcept {
|
||||||
|
impl_->admission_closed = !open;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RegionSessions::admitting() const noexcept {
|
||||||
|
return !impl_->admission_closed;
|
||||||
|
}
|
||||||
|
|
||||||
void RegionSessions::set_load(bool refuse_logins, std::uint8_t shed) {
|
void RegionSessions::set_load(bool refuse_logins, std::uint8_t shed) {
|
||||||
impl_->refuse_logins = refuse_logins;
|
impl_->refuse_logins = refuse_logins;
|
||||||
impl_->replication.set_shed(shed);
|
impl_->replication.set_shed(shed);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#include "evo/server/lifecycle/cellular_admin_view.hpp"
|
#include "evo/server/lifecycle/cellular_admin_view.hpp"
|
||||||
#include "fixtures/cellular_ecology.hpp"
|
#include "fixtures/cellular_ecology.hpp"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
@@ -59,12 +60,96 @@ void renders_cells_and_deposits() {
|
|||||||
"deposit limit keeps ids 1 and 2");
|
"deposit limit keeps ids 1 and 2");
|
||||||
const auto none = render_cellular_admin_view(*state, {}, {.cells = 0, .deposits = 0});
|
const auto none = render_cellular_admin_view(*state, {}, {.cells = 0, .deposits = 0});
|
||||||
require(none.find("\"cells\":[],\"deposits\":[]}") != std::string::npos, "empty lists");
|
require(none.find("\"cells\":[],\"deposits\":[]}") != std::string::npos, "empty lists");
|
||||||
|
|
||||||
|
// Counts and totals cover everything, whatever the limits; no drip before rules 13.
|
||||||
|
std::array<std::uint64_t, 5> reserve{}, body{}, bubbles{};
|
||||||
|
std::array<std::size_t, 3> kinds{};
|
||||||
|
const auto add = [](std::array<std::uint64_t, 5>& totals, const accounting::Inventory& stock) {
|
||||||
|
totals[0] += stock.energy.value;
|
||||||
|
for (std::size_t i = 0; i < 4; ++i)
|
||||||
|
totals[i + 1] += stock.matter[i].value;
|
||||||
|
};
|
||||||
|
for (const auto& life : state->lives()) {
|
||||||
|
add(reserve, life.reserve);
|
||||||
|
add(body, life.body);
|
||||||
|
}
|
||||||
|
for (const auto& patch : state->habitat().patches()) {
|
||||||
|
++kinds[static_cast<std::size_t>(patch.kind)];
|
||||||
|
if (patch.kind == biology::CellularDepositKind::mote)
|
||||||
|
add(bubbles, patch.stock);
|
||||||
|
}
|
||||||
|
const auto list = [](const std::array<std::uint64_t, 5>& totals) {
|
||||||
|
std::string text = "[";
|
||||||
|
for (std::size_t i = 0; i < totals.size(); ++i)
|
||||||
|
text += (i == 0 ? "" : ",") + std::to_string(totals[i]);
|
||||||
|
return text + "]";
|
||||||
|
};
|
||||||
|
const auto counts = "\"counts\":[4,0," + std::to_string(kinds[0]) + "," +
|
||||||
|
std::to_string(kinds[1]) + "," + std::to_string(kinds[2]) + "]";
|
||||||
|
require(reserve[0] > 0 && body[1] > 0, "the fixture's cells hold stock");
|
||||||
|
for (const auto& text : {view, none}) {
|
||||||
|
require(text.find(counts) != std::string::npos, "counts");
|
||||||
|
require(text.find("\"totals\":{\"reserve\":" + list(reserve) + ",\"body\":" + list(body) +
|
||||||
|
",") != std::string::npos,
|
||||||
|
"cell totals");
|
||||||
|
require(text.find(",\"bubbles\":" + list(bubbles) + "}") != std::string::npos,
|
||||||
|
"bubble totals");
|
||||||
|
require(text.find("\"drip\"") == std::string::npos, "a drip before rules 13");
|
||||||
|
require(text.find("],\"heat\":" + std::to_string(state->heat().energy.value) +
|
||||||
|
",\"archive\":[" + std::to_string(state->archive().recorded()) +
|
||||||
|
",65536," + std::to_string(state->archive().archived()) +
|
||||||
|
",4096],\"cells_total\":") != std::string::npos,
|
||||||
|
"heat and archive");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The trial liquid rules (cellular_revamp_owner_tests).
|
||||||
|
CellularLiquidRules liquid() {
|
||||||
|
return {.currents = {5, 48'000, 48'000, 250, 2, 4, 3'000, 6'000, 60, 300},
|
||||||
|
.founder = {.thrust_q10 = 20'480,
|
||||||
|
.reverse_thrust_q10 = 20'480,
|
||||||
|
.forward_drag_ppm = 95'163,
|
||||||
|
.lateral_drag_ppm = 95'163,
|
||||||
|
.turn = 3'276},
|
||||||
|
.deposits = {.drift_radius_um = 200,
|
||||||
|
.max_drift_q10 = 100 * 1'024,
|
||||||
|
.drift_decay_ppm = 95'163,
|
||||||
|
.merged_cap = 8,
|
||||||
|
.bubble_radius_um = biology::cellular_mote_radius_um}};
|
||||||
|
}
|
||||||
|
|
||||||
|
// A rules-13 owner's view carries its spent-pool drip.
|
||||||
|
void renders_the_drip() {
|
||||||
|
auto state = opening(7, true, 2, false);
|
||||||
|
checked(state->advance_tick({}), "genesis tick");
|
||||||
|
state = checked(state->migration_upgrade_candidate(), "boundary upgrade");
|
||||||
|
state = checked(state->maturation_upgrade_candidate(), "maturation upgrade");
|
||||||
|
state = checked(state->inheritance_upgrade_candidate(), "inheritance upgrade");
|
||||||
|
state = checked(state->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade");
|
||||||
|
state = checked(state->liquid_upgrade_candidate(liquid()), "liquid upgrade");
|
||||||
|
CellularRevampRules rules{.body = {.essential_upkeep_per_thousand = 250},
|
||||||
|
.burn_pj_per_kfg = {2'000, 2'000, 2'000, 2'000},
|
||||||
|
.step = {.engulf_ratio_milli = 1'500,
|
||||||
|
.engulf_reserve_percent = 100,
|
||||||
|
.kill_bubble_per_thousand = 500},
|
||||||
|
.drip_interval_ticks = 20,
|
||||||
|
.drip_bubble_pj = 20'000'000,
|
||||||
|
.drip_bubble_fg = 1'000'000,
|
||||||
|
.heat_recycle_per_thousand = 1'000,
|
||||||
|
.drip_absorb = true,
|
||||||
|
.wildlife_cap = 200};
|
||||||
|
state = checked(state->revamp_upgrade_candidate(rules), "revamp upgrade");
|
||||||
|
const auto view = render_cellular_admin_view(*state, {});
|
||||||
|
require(view.find(",\"drip\":[20,20000000,1000000,1000,1],\"caps\":[256,200],"
|
||||||
|
"\"cells_total\":") != std::string::npos,
|
||||||
|
"rules-13 drip and energy cycle");
|
||||||
}
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
try {
|
try {
|
||||||
renders_cells_and_deposits();
|
renders_cells_and_deposits();
|
||||||
|
renders_the_drip();
|
||||||
} catch (const std::exception& error) {
|
} catch (const std::exception& error) {
|
||||||
std::fprintf(stderr, "%s\n", error.what());
|
std::fprintf(stderr, "%s\n", error.what());
|
||||||
return 1;
|
return 1;
|
||||||
|
|||||||
@@ -209,7 +209,9 @@ void version_checks(const CellularLives& base, const CellularBatch& batch) {
|
|||||||
"action matcher admitted new trace on old owner");
|
"action matcher admitted new trace on old owner");
|
||||||
empty.format_version = cellular_batch_format;
|
empty.format_version = cellular_batch_format;
|
||||||
require(replay_cellular_batch(*old, empty).has_value(), "old replay control failed");
|
require(replay_cellular_batch(*old, empty).has_value(), "old replay control failed");
|
||||||
empty.format_version = 5;
|
empty.format_version = 5; // ADR-0182 trace 5 needs a rules-13 owner.
|
||||||
|
refuse(*old, empty, CellularBatchError::version);
|
||||||
|
empty.format_version = 6;
|
||||||
refuse(*old, empty, CellularBatchError::version);
|
refuse(*old, empty, CellularBatchError::version);
|
||||||
require(!encode_cellular_batch(empty), "unknown trace encoded");
|
require(!encode_cellular_batch(empty), "unknown trace encoded");
|
||||||
auto scope = batch;
|
auto scope = batch;
|
||||||
|
|||||||
@@ -245,7 +245,7 @@ void trace_contract(bool maturing = false) {
|
|||||||
}
|
}
|
||||||
altered = trace;
|
altered = trace;
|
||||||
altered.members.clear();
|
altered.members.clear();
|
||||||
for (std::uint64_t i = 1; i <= biology::max_cellular_tick_lives; ++i)
|
for (std::uint64_t i = 1; i <= biology::max_cellular_frozen_lives; ++i)
|
||||||
altered.members.push_back(cellular_bud_identity(3, i));
|
altered.members.push_back(cellular_bud_identity(3, i));
|
||||||
auto maximum = checked(encode_migration_trace(altered), "maximum pair codec");
|
auto maximum = checked(encode_migration_trace(altered), "maximum pair codec");
|
||||||
require(maximum.size() == max_migration_trace_bytes &&
|
require(maximum.size() == max_migration_trace_bytes &&
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
@@ -1210,6 +1211,45 @@ void cellular_death_is_final_and_account_restarts() {
|
|||||||
evo::network::PrimitiveLifeResult::insufficient_funding);
|
evo::network::PrimitiveLifeResult::insufficient_funding);
|
||||||
CHECK(host->create_primitive_life(newcomer, newcomer_control->generation, 21).result ==
|
CHECK(host->create_primitive_life(newcomer, newcomer_control->generation, 21).result ==
|
||||||
evo::network::PrimitiveLifeResult::insufficient_funding);
|
evo::network::PrimitiveLifeResult::insufficient_funding);
|
||||||
|
// Schema 69: the admin ends a published, open life (the portal first checks that no cell
|
||||||
|
// holds the account); ended, refused and unknown requests are not open.
|
||||||
|
{
|
||||||
|
const std::string holder = "94949494-9494-9494-9494-949494949494";
|
||||||
|
const auto end_life = [&](std::uint64_t request) {
|
||||||
|
auto admin = connect_as(env("EVO_PG_ADMIN_USER"));
|
||||||
|
const std::array<std::string, 2> parameters{holder, std::to_string(request)};
|
||||||
|
const auto rows =
|
||||||
|
admin->query("SELECT evolution.admin_end_account_life_v1(9768, $1::uuid, $2, "
|
||||||
|
"'ops@example.test', 'stranded')::text",
|
||||||
|
parameters, 5s);
|
||||||
|
return rows && rows->size() == 1 ? rows->front().front() : std::nullopt;
|
||||||
|
};
|
||||||
|
CHECK(end_life(11) == "false"); // Died and ended by the region.
|
||||||
|
CHECK(!end_life(13)); // Refused, never published.
|
||||||
|
CHECK(!end_life(99));
|
||||||
|
CHECK(end_life(12) == "true");
|
||||||
|
CHECK(end_life(12) == "false");
|
||||||
|
// The database now admits a birth, but the region still holds the living cell and
|
||||||
|
// refuses it, so the account never gets a second life here.
|
||||||
|
CHECK(host->create_primitive_life(account, control->generation, 14).result ==
|
||||||
|
evo::network::PrimitiveLifeResult::pending);
|
||||||
|
const std::array again{
|
||||||
|
CellularBirthRefusal{host->queued_births().front(), CellularLivesError::life_exists}};
|
||||||
|
CellularBatch kept;
|
||||||
|
kept.header = header(1);
|
||||||
|
kept.ticks.push_back({{{second, {}}}, {}, {}});
|
||||||
|
CHECK(host->publish(kept));
|
||||||
|
host->refuse_births(again);
|
||||||
|
CHECK(host->queued_births().empty() && host->state()->lives().size() == 1);
|
||||||
|
CHECK(host->query_primitive_life(account, control->generation, 14).result ==
|
||||||
|
evo::network::PrimitiveLifeResult::existing_life);
|
||||||
|
auto owner_db = connect_as(env("PGUSER"));
|
||||||
|
CHECK(owner_db
|
||||||
|
->query("SELECT 1 FROM evolution.admin_life_endings WHERE request_id = 12 "
|
||||||
|
"AND author_subject = 'ops@example.test' AND reason = 'stranded'",
|
||||||
|
{}, 5s)
|
||||||
|
->size() == 1);
|
||||||
|
}
|
||||||
const auto snapshot = host->state()->snapshot();
|
const auto snapshot = host->state()->snapshot();
|
||||||
host->drain();
|
host->drain();
|
||||||
host.reset();
|
host.reset();
|
||||||
@@ -1492,9 +1532,187 @@ void run_starting_wildlife_publication_tests() {
|
|||||||
auto tick = publish_cellular_batch(*runtime, **objects, *lease, head, batch, *recovered->state,
|
auto tick = publish_cellular_batch(*runtime, **objects, *lease, head, batch, *recovered->state,
|
||||||
identity(8), build, 5s);
|
identity(8), build, 5s);
|
||||||
CHECK(tick);
|
CHECK(tick);
|
||||||
|
head = tick->committed;
|
||||||
recovered = recover_cellular_checkpoint(*runtime, **objects, key, *lease, builds, 5s);
|
recovered = recover_cellular_checkpoint(*runtime, **objects, key, *lease, builds, 5s);
|
||||||
CHECK(recovered && recovered->state->snapshot() == tick_bytes &&
|
CHECK(recovered && recovered->state->snapshot() == tick_bytes &&
|
||||||
recovered->state->lives().size() == 32);
|
recovered->state->lives().size() == 32);
|
||||||
|
|
||||||
|
// ADR-0182 (schema 63): queued admin commands publish in trace 5 and bind once.
|
||||||
|
CHECK(owner->query("INSERT INTO evolution.life_allocators(world_id, next_identity) "
|
||||||
|
"VALUES ($1, 5000000) ON CONFLICT DO NOTHING",
|
||||||
|
std::array{std::to_string(key.world)}, 5s));
|
||||||
|
const auto enqueue = [&](int kind, int count, std::uint64_t target, std::uint64_t energy) {
|
||||||
|
const auto rows = owner->query(
|
||||||
|
"SELECT command_id, target FROM evolution.admin_enqueue_command_v1($1, $2, $3, $4, "
|
||||||
|
"$5, $6, 0, 0, 0, 0, 'ops', 'test')",
|
||||||
|
std::array{std::to_string(key.world), std::to_string(key.region), std::to_string(kind),
|
||||||
|
std::to_string(count), std::to_string(target), std::to_string(energy)},
|
||||||
|
5s);
|
||||||
|
CHECK(rows && rows->size() == 1);
|
||||||
|
return std::pair{std::stoull(*(*rows)[0][0]), std::stoull(*(*rows)[0][1])};
|
||||||
|
};
|
||||||
|
CHECK(!owner->query("SELECT * FROM evolution.admin_enqueue_command_v1($1, $2, 4, 0, 0, 0, 0, "
|
||||||
|
"0, 0, 0, 'ops', '')",
|
||||||
|
std::array{std::to_string(key.world), std::to_string(key.region)}, 5s));
|
||||||
|
owner = connect_as(env("PGUSER"));
|
||||||
|
const auto victim = recovered->state->lives().front().identity.life;
|
||||||
|
const auto [pool_id, pool_target] = enqueue(4, 0, 0, 1'000'000'000);
|
||||||
|
const auto [spawn_id, first_wild] = enqueue(6, 2, 0, 0);
|
||||||
|
const auto [remove_id, remove_target] = enqueue(1, 0, victim, 0);
|
||||||
|
CHECK(pool_target == 0 && first_wild == 5'000'000 && remove_target == victim);
|
||||||
|
using Kind = evo::server::CellularAdminKind;
|
||||||
|
const std::vector<evo::server::CellularAdminCommand> commands{
|
||||||
|
{static_cast<std::uint64_t>(pool_id), Kind::add_pool, 0, 0, {{1'000'000'000}, {}}},
|
||||||
|
{static_cast<std::uint64_t>(spawn_id), Kind::spawn_wildlife, 2, first_wild, {}},
|
||||||
|
{static_cast<std::uint64_t>(remove_id), Kind::remove_cell, 0, victim, {}}};
|
||||||
|
const auto pending = [&] {
|
||||||
|
const auto rows =
|
||||||
|
runtime->query("SELECT count(*) FROM evolution.load_pending_admin_commands_v1($1, $2)",
|
||||||
|
std::array{std::to_string(key.world), std::to_string(key.region)}, 5s);
|
||||||
|
CHECK(rows && rows->size() == 1);
|
||||||
|
return std::stoull(*(*rows)[0][0]);
|
||||||
|
};
|
||||||
|
CHECK(pending() == 3);
|
||||||
|
const auto admin_batch = [&](std::vector<evo::server::CellularAdminCommand> recorded) {
|
||||||
|
CellularBatch made{{key.world, key.region, 1, head.head.commit, head.head.digest, 2, 3},
|
||||||
|
{{}}};
|
||||||
|
made.format_version = evo::server::cellular_batch_admin_format;
|
||||||
|
made.ticks.front().lives = checked_value(wildlife_intents(*recovered->state, 3));
|
||||||
|
made.ticks.front().admin = std::move(recorded);
|
||||||
|
return made;
|
||||||
|
};
|
||||||
|
// A command that differs from its queue row is refused and the head stays.
|
||||||
|
auto tampered = commands;
|
||||||
|
tampered.front().amount.energy.value = 2'000'000'000;
|
||||||
|
auto wrong = admin_batch(tampered);
|
||||||
|
auto wrong_base = evo::fixture::restore(*recovered->state);
|
||||||
|
CHECK(wrong_base->advance_tick(wrong.ticks.front().lives));
|
||||||
|
auto wrong_state = wrong_base->admin_candidate(tampered);
|
||||||
|
CHECK(wrong_state);
|
||||||
|
CHECK(!publish_cellular_batch(*runtime, **objects, *lease, head, wrong, **wrong_state,
|
||||||
|
identity(9), build, 5s));
|
||||||
|
runtime = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
CHECK(pending() == 3);
|
||||||
|
// The exact commands publish, bind and recover.
|
||||||
|
auto admin = admin_batch(commands);
|
||||||
|
CHECK(recovered->state->advance_tick(admin.ticks.front().lives));
|
||||||
|
std::vector<evo::server::CellularAdminResult> results;
|
||||||
|
auto applied = recovered->state->admin_candidate(commands, &results);
|
||||||
|
CHECK(applied && results.size() == 3 &&
|
||||||
|
std::ranges::all_of(results, [](auto r) { return r.applied; }));
|
||||||
|
const auto applied_bytes = (*applied)->snapshot();
|
||||||
|
auto published = publish_cellular_batch(*runtime, **objects, *lease, head, admin, **applied,
|
||||||
|
identity(10), build, 5s);
|
||||||
|
CHECK(published);
|
||||||
|
head = published->committed;
|
||||||
|
CHECK(pending() == 0);
|
||||||
|
const auto bound = owner->query(
|
||||||
|
"SELECT count(*), min(tick), max(tick) FROM evolution.admin_command_applications "
|
||||||
|
"WHERE command_id IN ($1, $2, $3)",
|
||||||
|
std::array{std::to_string(pool_id), std::to_string(spawn_id), std::to_string(remove_id)},
|
||||||
|
5s);
|
||||||
|
CHECK(bound && (*bound)[0][0] == "3" && (*bound)[0][1] == "3" && (*bound)[0][2] == "3");
|
||||||
|
recovered = recover_cellular_checkpoint(*runtime, **objects, key, *lease, builds, 5s);
|
||||||
|
CHECK(recovered && recovered->state->snapshot() == applied_bytes &&
|
||||||
|
recovered->state->lives().size() == 33);
|
||||||
|
// The same commands cannot bind to another commit.
|
||||||
|
auto again = admin_batch(commands);
|
||||||
|
again.header = {key.world, key.region, 1, head.head.commit, head.head.digest, 3, 4};
|
||||||
|
again.ticks.front().lives = checked_value(wildlife_intents(*recovered->state, 4));
|
||||||
|
auto again_base = evo::fixture::restore(*recovered->state);
|
||||||
|
CHECK(again_base->advance_tick(again.ticks.front().lives));
|
||||||
|
auto again_state = again_base->admin_candidate(commands);
|
||||||
|
CHECK(again_state);
|
||||||
|
CHECK(!publish_cellular_batch(*runtime, **objects, *lease, head, again, **again_state,
|
||||||
|
identity(11), build, 5s));
|
||||||
|
runtime = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
|
||||||
|
// ADR-0182 (schema 66): a tuning revision's adoption publishes, binds and recovers; the
|
||||||
|
// publisher and recovery name its rules from the successor state, checked by digest.
|
||||||
|
auto tuned_rules = recovered->state->revamp_rules();
|
||||||
|
auto& upkeep = tuned_rules.body.essential_upkeep_per_thousand;
|
||||||
|
upkeep = upkeep == 100 ? 101 : 100;
|
||||||
|
tuned_rules.organism_cap = 4'096; // Section 17: room for the crowded tick below.
|
||||||
|
CHECK(evo::server::cellular_revamp_valid(tuned_rules) &&
|
||||||
|
tuned_rules != recovered->state->revamp_rules());
|
||||||
|
const auto tuned_digest = checked_value(
|
||||||
|
evo::persistence::sha256(evo::server::encode_cellular_revamp_rules(tuned_rules)));
|
||||||
|
std::string tuned_hex;
|
||||||
|
for (const auto byte : tuned_digest) {
|
||||||
|
constexpr std::string_view digits = "0123456789abcdef";
|
||||||
|
tuned_hex.push_back(digits[byte >> 4U]);
|
||||||
|
tuned_hex.push_back(digits[byte & 0x0FU]);
|
||||||
|
}
|
||||||
|
const auto revision_rows = owner->query(
|
||||||
|
"SELECT evolution.admin_set_tuning_v1($1, 'not parsed by publication', "
|
||||||
|
"decode($2, 'hex'), ARRAY[$3::bigint], 'ops', 'test')",
|
||||||
|
std::array{std::to_string(key.world), tuned_hex, std::to_string(key.region)}, 5s);
|
||||||
|
CHECK(revision_rows && revision_rows->size() == 1);
|
||||||
|
const auto tuning_revision = std::stoull(revision_rows.value().at(0).at(0).value_or(""));
|
||||||
|
const auto queued_adoption = runtime->query(
|
||||||
|
"SELECT command_id FROM evolution.load_pending_admin_commands_v1($1, $2) WHERE kind = 7",
|
||||||
|
std::array{std::to_string(key.world), std::to_string(key.region)}, 5s);
|
||||||
|
CHECK(queued_adoption && queued_adoption->size() == 1);
|
||||||
|
const auto adoption = evo::server::cellular_adopt_tuning_command(
|
||||||
|
std::stoull(queued_adoption.value().at(0).at(0).value_or("")), tuning_revision,
|
||||||
|
tuned_digest);
|
||||||
|
auto adopt_batch = admin_batch({adoption});
|
||||||
|
adopt_batch.header = {key.world, key.region, 1, head.head.commit, head.head.digest, 3, 4};
|
||||||
|
adopt_batch.ticks.front().lives = checked_value(wildlife_intents(*recovered->state, 4));
|
||||||
|
auto adopted = evo::fixture::restore(*recovered->state);
|
||||||
|
CHECK(adopted->advance_tick(adopt_batch.ticks.front().lives));
|
||||||
|
std::vector<evo::server::CellularAdminResult> adopt_results;
|
||||||
|
auto adopted_state =
|
||||||
|
adopted->admin_candidate(std::vector{adoption}, &adopt_results,
|
||||||
|
[&](std::uint64_t, const std::array<std::uint8_t, 32>&) {
|
||||||
|
return std::optional{tuned_rules};
|
||||||
|
});
|
||||||
|
CHECK(adopted_state && adopt_results.size() == 1 && adopt_results.front().applied);
|
||||||
|
const auto adopted_bytes = (*adopted_state)->snapshot();
|
||||||
|
auto adopted_publish = publish_cellular_batch(*runtime, **objects, *lease, head, adopt_batch,
|
||||||
|
**adopted_state, identity(12), build, 5s);
|
||||||
|
CHECK(adopted_publish);
|
||||||
|
head = adopted_publish->committed;
|
||||||
|
CHECK(pending() == 0);
|
||||||
|
recovered = recover_cellular_checkpoint(*runtime, **objects, key, *lease, builds, 5s);
|
||||||
|
CHECK(recovered && recovered->state->snapshot() == adopted_bytes &&
|
||||||
|
recovered->state->revamp_rules() == tuned_rules);
|
||||||
|
|
||||||
|
// ADR-0182 section 17 (schema 68): 256 wildlife in one command, then a tick of more than
|
||||||
|
// 256 lives, publish and recover exactly.
|
||||||
|
const auto [crowd_id, crowd_first] = enqueue(6, 256, 0, 0);
|
||||||
|
const std::vector<evo::server::CellularAdminCommand> crowd{
|
||||||
|
{static_cast<std::uint64_t>(crowd_id), Kind::spawn_wildlife, 256, crowd_first, {}}};
|
||||||
|
auto spawn_batch = admin_batch(crowd);
|
||||||
|
spawn_batch.header = {key.world, key.region, 1, head.head.commit, head.head.digest, 4, 5};
|
||||||
|
spawn_batch.ticks.front().lives = checked_value(wildlife_intents(*recovered->state, 5));
|
||||||
|
CHECK(recovered->state->advance_tick(spawn_batch.ticks.front().lives));
|
||||||
|
std::vector<evo::server::CellularAdminResult> crowd_results;
|
||||||
|
auto spawned = recovered->state->admin_candidate(crowd, &crowd_results);
|
||||||
|
CHECK(spawned && crowd_results.size() == 1 && crowd_results.front().applied &&
|
||||||
|
(*spawned)->lives().size() > 256);
|
||||||
|
auto spawn_publish = publish_cellular_batch(*runtime, **objects, *lease, head, spawn_batch,
|
||||||
|
**spawned, identity(13), build, 5s);
|
||||||
|
CHECK(spawn_publish);
|
||||||
|
head = spawn_publish->committed;
|
||||||
|
recovered = recover_cellular_checkpoint(*runtime, **objects, key, *lease, builds, 5s);
|
||||||
|
CHECK(recovered && recovered->state->snapshot() == (*spawned)->snapshot());
|
||||||
|
auto& crowded = recovered->state;
|
||||||
|
CellularBatch crowded_batch{
|
||||||
|
{key.world, key.region, 1, head.head.commit, head.head.digest, 5, 6}, {{}}};
|
||||||
|
crowded_batch.ticks.front().lives = checked_value(wildlife_intents(*crowded, 6));
|
||||||
|
CHECK(crowded_batch.ticks.front().lives.size() > 256);
|
||||||
|
CHECK(crowded->advance_tick(crowded_batch.ticks.front().lives));
|
||||||
|
const auto crowded_bytes = crowded->snapshot();
|
||||||
|
auto crowded_publish = publish_cellular_batch(*runtime, **objects, *lease, head, crowded_batch,
|
||||||
|
*crowded, identity(14), build, 5s);
|
||||||
|
CHECK(crowded_publish);
|
||||||
|
head = crowded_publish->committed;
|
||||||
|
recovered = recover_cellular_checkpoint(*runtime, **objects, key, *lease, builds, 5s);
|
||||||
|
CHECK(recovered && recovered->state->snapshot() == crowded_bytes &&
|
||||||
|
recovered->state->lives().size() > 256);
|
||||||
|
std::printf("crowded tick: %zu lives, %zu snapshot bytes (%zu at 33 lives)\n",
|
||||||
|
recovered->state->lives().size(), crowded_bytes.size(), applied_bytes.size());
|
||||||
CHECK(release_region_lease(*runtime, key, *lease, 5s));
|
CHECK(release_region_lease(*runtime, key, *lease, 5s));
|
||||||
std::puts("starting wildlife publication and replacement-owner replay passed");
|
std::puts("starting wildlife publication and replacement-owner replay passed");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -874,6 +874,378 @@ void trace_replays() {
|
|||||||
"Emerge did not survive the trace");
|
"Emerge did not survive the trace");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ADR-0182: operator commands import through the boundary ledger, remove into the spent pool,
|
||||||
|
// spawn funded wildlife, refuse what does not apply, and replay exactly from trace 5.
|
||||||
|
void admin_commands_apply_and_replay() {
|
||||||
|
using Kind = CellularAdminKind;
|
||||||
|
auto live = revamp_region();
|
||||||
|
const auto base = restore(*live);
|
||||||
|
accounting::Inventory pool{{5'000'000'000}, {}};
|
||||||
|
accounting::Inventory bubbles{{400'000'000}, {}};
|
||||||
|
bubbles.matter[0].value = 4'000;
|
||||||
|
const std::vector<CellularAdminCommand> commands{
|
||||||
|
{1, Kind::add_pool, 0, 0, pool},
|
||||||
|
{2, Kind::add_bubbles, 4, 0, bubbles},
|
||||||
|
{3, Kind::grant_reserve, 0, 100, {{1'000'000}, {}}},
|
||||||
|
{4, Kind::spawn_wildlife, 3, 900'000, {}},
|
||||||
|
{5, Kind::remove_cell, 0, 101, {}},
|
||||||
|
{6, Kind::release_pool, 2, 0, {{1'000'000'000}, {}}},
|
||||||
|
{7, Kind::remove_cell, 0, 424'242, {}}, // No such life: refused, nothing changes.
|
||||||
|
};
|
||||||
|
for (const auto& bad : {CellularAdminCommand{8, Kind::add_pool, 0, 0, {}},
|
||||||
|
CellularAdminCommand{8, Kind::spawn_wildlife, 257, 900'000, {}},
|
||||||
|
CellularAdminCommand{8, Kind::add_bubbles, 0, 0, pool},
|
||||||
|
CellularAdminCommand{0, Kind::add_pool, 0, 0, pool}})
|
||||||
|
require(!cellular_admin_command_valid(bad), "an invalid command shape was accepted");
|
||||||
|
require(!live->admin_candidate(std::vector{commands[1], commands[0]}),
|
||||||
|
"commands out of order were accepted");
|
||||||
|
|
||||||
|
// The live run: one tick, then the commands after it.
|
||||||
|
const auto intents = swim(*live, {});
|
||||||
|
checked(live->advance_tick(intents), "tick before the commands");
|
||||||
|
const auto spent_before = live->spent();
|
||||||
|
const auto deposits_before = live->habitat().patches().size();
|
||||||
|
const auto removed_body = life_of(*live, 101).body;
|
||||||
|
const auto removed_reserve = life_of(*live, 101).reserve;
|
||||||
|
std::vector<CellularAdminResult> results;
|
||||||
|
auto after = checked(live->admin_candidate(commands, &results), "commands apply");
|
||||||
|
require(results.size() == 7 &&
|
||||||
|
std::ranges::all_of(results.begin(), results.begin() + 6,
|
||||||
|
[](const auto& r) { return r.applied; }) &&
|
||||||
|
!results.back().applied,
|
||||||
|
"unexpected command results");
|
||||||
|
closed(*after);
|
||||||
|
require(after->lives().size() == live->lives().size() - 1 + 3, "wrong cell count");
|
||||||
|
std::size_t wildlife = 0;
|
||||||
|
for (const auto& life : after->lives())
|
||||||
|
if (life.account == LifeAccount{} && life.identity.life >= 900'000 &&
|
||||||
|
life.identity.life < 900'003)
|
||||||
|
++wildlife;
|
||||||
|
require(wildlife == 3, "spawned wildlife missing");
|
||||||
|
require(life_of(*after, 100).reserve.energy.value ==
|
||||||
|
life_of(*live, 100).reserve.energy.value + 1'000'000,
|
||||||
|
"the grant did not reach the reserve");
|
||||||
|
const auto corpse = std::ranges::find(after->corpses(), 101ULL, &CellularOwnedCorpse::life_id);
|
||||||
|
require(corpse != after->corpses().end() &&
|
||||||
|
corpse->cause == biology::CellularDeathCause::removed,
|
||||||
|
"the removed cell left no removed corpse");
|
||||||
|
auto expected_spent = spent_before;
|
||||||
|
expected_spent.energy.value += pool.energy.value - 1'000'000'000;
|
||||||
|
for (const auto& part : {removed_body, removed_reserve}) {
|
||||||
|
expected_spent.energy.value += part.energy.value;
|
||||||
|
for (std::size_t c = 0; c < 4; ++c)
|
||||||
|
expected_spent.matter[c].value += part.matter[c].value;
|
||||||
|
}
|
||||||
|
require(after->spent() == expected_spent, "the spent pool is off");
|
||||||
|
require(after->habitat().patches().size() == deposits_before + 4 + 2, "bubbles were not added");
|
||||||
|
require(restore(*after)->snapshot() == after->snapshot(), "commands do not restore");
|
||||||
|
auto again = checked(live->admin_candidate(commands), "commands apply again");
|
||||||
|
require(again->snapshot() == after->snapshot(), "commands are not deterministic");
|
||||||
|
|
||||||
|
// The same tick and commands from trace 5 replay to the same state.
|
||||||
|
CellularBatch batch;
|
||||||
|
batch.format_version = cellular_batch_admin_format;
|
||||||
|
batch.header = {base->world(), base->region(), base->frame(), {}, {}, base->tick(), 0};
|
||||||
|
batch.header.predecessor.fill(1);
|
||||||
|
batch.header.predecessor_digest.fill(2);
|
||||||
|
batch.ticks.push_back({intents, {}, {}, commands});
|
||||||
|
batch.header.end_tick = base->tick() + 1;
|
||||||
|
const auto bytes = checked(encode_cellular_batch(batch), "trace 5 encodes");
|
||||||
|
const auto decoded = checked(decode_cellular_batch(bytes), "trace 5 decodes");
|
||||||
|
require(decoded == batch, "trace 5 did not round-trip");
|
||||||
|
std::vector<CellularMutationOutcome> outcomes;
|
||||||
|
std::vector<CellularAdminResult> replayed_results;
|
||||||
|
const auto replayed = checked(replay_cellular_batch(*base, decoded, outcomes, replayed_results),
|
||||||
|
"trace 5 replays");
|
||||||
|
require(replayed->snapshot() == after->snapshot() && replayed_results == results,
|
||||||
|
"trace 5 replay diverged");
|
||||||
|
// Trace 4 cannot carry commands, and older owners cannot replay trace 5.
|
||||||
|
auto old_format = batch;
|
||||||
|
old_format.format_version = cellular_batch_inheritance_format;
|
||||||
|
require(!encode_cellular_batch(old_format), "trace 4 carried commands");
|
||||||
|
auto mangled = bytes;
|
||||||
|
mangled[8] = 4; // The version byte: a trace-4 header with nonzero command counts.
|
||||||
|
require(!decode_cellular_batch(mangled), "a trace 4 with commands decoded");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schema 67: take_reserve moves at most what a reserve holds to the spent pool, and
|
||||||
|
// remove_wildlife removes every life without an account in one command.
|
||||||
|
void take_and_cull() {
|
||||||
|
using Kind = CellularAdminKind;
|
||||||
|
for (const auto& bad : {CellularAdminCommand{1, Kind::take_reserve, 0, 100, {}},
|
||||||
|
CellularAdminCommand{1, Kind::take_reserve, 0, 0, {{1}, {}}},
|
||||||
|
CellularAdminCommand{1, Kind::remove_wildlife, 1, 0, {}},
|
||||||
|
CellularAdminCommand{1, Kind::remove_wildlife, 0, 100, {}},
|
||||||
|
CellularAdminCommand{1, Kind::remove_wildlife, 0, 0, {{1}, {}}}})
|
||||||
|
require(!cellular_admin_command_valid(bad), "an invalid take or cull shape was accepted");
|
||||||
|
auto live = revamp_region();
|
||||||
|
checked(live->advance_tick(swim(*live, {})), "tick before the commands");
|
||||||
|
live = checked(live->admin_candidate(std::vector<CellularAdminCommand>{
|
||||||
|
{1, Kind::spawn_wildlife, 3, 900'000, {}}}),
|
||||||
|
"wildlife to cull");
|
||||||
|
require(live->lives().size() == 5, "the wildlife was not spawned");
|
||||||
|
const auto reserve = life_of(*live, 100).reserve;
|
||||||
|
const auto spent = live->spent();
|
||||||
|
accounting::Inventory carbon{};
|
||||||
|
carbon.matter[0].value = 1;
|
||||||
|
const std::vector<CellularAdminCommand> commands{
|
||||||
|
{2, Kind::take_reserve, 0, 100, {{reserve.energy.value + 5}, {}}}, // All of it.
|
||||||
|
{3, Kind::take_reserve, 0, 100, {{1}, {}}}, // Nothing left to take: refused.
|
||||||
|
{4, Kind::take_reserve, 0, 424'242, {{1}, {}}}, // No such life: refused.
|
||||||
|
{5, Kind::remove_wildlife, 0, 0, {}},
|
||||||
|
{6, Kind::remove_wildlife, 0, 0, {}}, // No wildlife left: refused.
|
||||||
|
};
|
||||||
|
std::vector<CellularAdminResult> results;
|
||||||
|
auto after = checked(live->admin_candidate(commands, &results), "take and cull apply");
|
||||||
|
require(results.size() == 5 && results[0].applied && !results[1].applied &&
|
||||||
|
!results[2].applied && results[3].applied && !results[4].applied,
|
||||||
|
"unexpected take and cull results");
|
||||||
|
closed(*after);
|
||||||
|
require(life_of(*after, 100).reserve.energy.value == 0 &&
|
||||||
|
life_of(*after, 100).reserve.matter == reserve.matter,
|
||||||
|
"the take did not empty only the energy");
|
||||||
|
require(after->lives().size() == 2 &&
|
||||||
|
std::ranges::all_of(after->lives(),
|
||||||
|
[](const auto& l) { return l.account != LifeAccount{}; }),
|
||||||
|
"the cull missed wildlife or removed a player");
|
||||||
|
require(after->spent().energy.value > spent.energy.value + reserve.energy.value,
|
||||||
|
"the taken energy and culled cells did not reach the spent pool");
|
||||||
|
std::size_t removed = 0;
|
||||||
|
for (const auto& corpse : after->corpses())
|
||||||
|
if (corpse.cause == biology::CellularDeathCause::removed)
|
||||||
|
++removed;
|
||||||
|
require(removed == 3, "each culled cell should leave a removed corpse");
|
||||||
|
require(restore(*after)->snapshot() == after->snapshot(), "take and cull do not restore");
|
||||||
|
require(checked(live->admin_candidate(commands), "again")->snapshot() == after->snapshot(),
|
||||||
|
"take and cull are not deterministic");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The wildlife cap keeps the slots above it for players: wildlife buds are refused there,
|
||||||
|
// while an uncapped twin buds. It rides the heat word of the rules encoding.
|
||||||
|
void the_wildlife_cap_leaves_room() {
|
||||||
|
auto rules = revamp();
|
||||||
|
auto capped_rules = rules;
|
||||||
|
capped_rules.wildlife_cap = 32;
|
||||||
|
require(cellular_revamp_valid(capped_rules) &&
|
||||||
|
encode_cellular_revamp_rules(capped_rules).size() ==
|
||||||
|
encode_cellular_revamp_rules(rules).size() &&
|
||||||
|
encode_cellular_revamp_rules(capped_rules) != encode_cellular_revamp_rules(rules),
|
||||||
|
"the wildlife cap is not a same-size distinct encoding");
|
||||||
|
auto over = capped_rules;
|
||||||
|
over.wildlife_cap = over.organism_cap + 1;
|
||||||
|
require(!cellular_revamp_valid(over), "a wildlife cap above the organism cap was valid");
|
||||||
|
auto source = opening(77, true, 64, false);
|
||||||
|
checked(source->advance_tick({}), "opening tick");
|
||||||
|
source = checked(source->migration_upgrade_candidate(), "boundary");
|
||||||
|
source = checked(source->maturation_upgrade_candidate(), "maturation");
|
||||||
|
source = checked(source->inheritance_upgrade_candidate(), "inheritance");
|
||||||
|
source = checked(source->photosynthesis_upgrade_candidate({0, 1, {0}}), "light");
|
||||||
|
source = checked(source->liquid_upgrade_candidate(liquid()), "liquid");
|
||||||
|
auto free = checked(source->revamp_upgrade_candidate(rules, 32, 900'000), "free wildlife");
|
||||||
|
auto capped = checked(source->revamp_upgrade_candidate(capped_rules, 32, 900'000), "capped");
|
||||||
|
require(restore(*capped)->revamp_rules() == capped_rules, "the wildlife cap did not restore");
|
||||||
|
const auto first = free->next_bud_sequence();
|
||||||
|
int ticks = 0;
|
||||||
|
for (; ticks < 12'000 && free->next_bud_sequence() == first; ++ticks)
|
||||||
|
checked(free->advance_tick(checked(wildlife_intents(*free, free->tick() + 1), "intents")),
|
||||||
|
"uncapped wildlife tick");
|
||||||
|
require(free->next_bud_sequence() != first, "uncapped wildlife never budded");
|
||||||
|
// A death (hunting) frees a slot a bud may take; the count never passes the cap.
|
||||||
|
for (int tick = 0; tick < 2 * ticks; ++tick) {
|
||||||
|
checked(capped->advance_tick(
|
||||||
|
checked(wildlife_intents(*capped, capped->tick() + 1), "capped intents")),
|
||||||
|
"capped wildlife tick");
|
||||||
|
require(capped->lives().size() <= 32, "wildlife budded at the wildlife cap");
|
||||||
|
}
|
||||||
|
closed(*capped);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADR-0182 tuning amendments: adopt_tuning swaps the rules at a recorded tick; whoever applies
|
||||||
|
// or replays it must name the rules for its revision and digest, and the safety revision stays.
|
||||||
|
void tuning_is_adopted_and_replayed() {
|
||||||
|
auto live = revamp_region();
|
||||||
|
const auto base = restore(*live);
|
||||||
|
const auto& before = live->revamp_rules();
|
||||||
|
auto changed = before;
|
||||||
|
changed.drip_interval_ticks += 7;
|
||||||
|
changed.drip_bubble_pj *= 2;
|
||||||
|
changed.body.essential_upkeep_per_thousand = 200;
|
||||||
|
require(cellular_revamp_valid(changed) &&
|
||||||
|
encode_cellular_revamp_rules(changed) != encode_cellular_revamp_rules(before),
|
||||||
|
"the changed rules are not distinct valid rules");
|
||||||
|
std::array<std::uint8_t, 32> digest{};
|
||||||
|
for (std::size_t i = 0; i < digest.size(); ++i)
|
||||||
|
digest.at(i) = static_cast<std::uint8_t>(i * 7 + 1);
|
||||||
|
const auto adopt = cellular_adopt_tuning_command(1, 5, digest);
|
||||||
|
require(cellular_admin_command_valid(adopt) && cellular_admin_digest(adopt) == digest &&
|
||||||
|
adopt.target == 5,
|
||||||
|
"the adoption command does not carry its revision and digest");
|
||||||
|
auto zero = cellular_adopt_tuning_command(1, 5, {});
|
||||||
|
auto counted = adopt;
|
||||||
|
counted.count = 1;
|
||||||
|
auto other = adopt;
|
||||||
|
other.amount.matter[3].value = 1;
|
||||||
|
for (const auto& bad : {zero, counted, other})
|
||||||
|
require(!cellular_admin_command_valid(bad), "an invalid adoption was accepted");
|
||||||
|
const CellularTuningResolver resolver =
|
||||||
|
[&](std::uint64_t revision,
|
||||||
|
const std::array<std::uint8_t, 32>& named) -> std::optional<CellularRevampRules> {
|
||||||
|
if (revision != 5 || named != digest)
|
||||||
|
return std::nullopt;
|
||||||
|
return changed;
|
||||||
|
};
|
||||||
|
|
||||||
|
const auto intents = swim(*live, {});
|
||||||
|
checked(live->advance_tick(intents), "tick before the adoption");
|
||||||
|
const std::vector commands{adopt};
|
||||||
|
// Nobody can name the rules: an error, not a refusal (replay would diverge).
|
||||||
|
require(!live->admin_candidate(commands), "an unnamed revision was applied or refused");
|
||||||
|
std::vector<CellularAdminResult> results;
|
||||||
|
auto after = checked(live->admin_candidate(commands, &results, resolver), "adoption applies");
|
||||||
|
require(results.size() == 1 && results.front().applied && after->revamp_rules() == changed,
|
||||||
|
"the rules were not adopted");
|
||||||
|
require(restore(*after)->snapshot() == after->snapshot(), "adopted rules do not restore");
|
||||||
|
// The safety revision is a law of the opening: such a revision is refused, nothing changes.
|
||||||
|
auto unsafe = changed;
|
||||||
|
unsafe.safety_version = before.safety_version + 1;
|
||||||
|
std::vector<CellularAdminResult> refused;
|
||||||
|
const auto kept =
|
||||||
|
checked(live->admin_candidate(commands, &refused,
|
||||||
|
[&](std::uint64_t, const std::array<std::uint8_t, 32>&) {
|
||||||
|
return std::optional{unsafe};
|
||||||
|
}),
|
||||||
|
"an unsafe adoption is a refusal");
|
||||||
|
require(refused.size() == 1 && !refused.front().applied && kept->revamp_rules() == before,
|
||||||
|
"a safety revision change was adopted");
|
||||||
|
|
||||||
|
// Trace 5 replays the adoption with the same resolver, and the successor state names it.
|
||||||
|
CellularBatch batch;
|
||||||
|
batch.format_version = cellular_batch_admin_format;
|
||||||
|
batch.header = {base->world(), base->region(), base->frame(), {}, {}, base->tick(), 0};
|
||||||
|
batch.header.predecessor.fill(1);
|
||||||
|
batch.header.predecessor_digest.fill(2);
|
||||||
|
batch.ticks.push_back({intents, {}, {}, commands});
|
||||||
|
batch.header.end_tick = base->tick() + 1;
|
||||||
|
const auto decoded =
|
||||||
|
checked(decode_cellular_batch(checked(encode_cellular_batch(batch), "encodes")), "decodes");
|
||||||
|
std::vector<CellularMutationOutcome> outcomes;
|
||||||
|
std::vector<CellularAdminResult> replayed_results;
|
||||||
|
require(!replay_cellular_batch(*base, decoded, outcomes, replayed_results),
|
||||||
|
"an adoption replayed without its rules");
|
||||||
|
const auto replayed =
|
||||||
|
checked(replay_cellular_batch(*base, decoded, outcomes, replayed_results, resolver),
|
||||||
|
"the adoption replays");
|
||||||
|
require(replayed->snapshot() == after->snapshot(), "the adoption replay diverged");
|
||||||
|
const auto encoded = encode_cellular_revamp_rules(changed);
|
||||||
|
const auto successor = cellular_successor_tuning(
|
||||||
|
*replayed, [&](std::span<const std::uint8_t> bytes, const std::array<std::uint8_t, 32>& d) {
|
||||||
|
return d == digest && std::ranges::equal(bytes, encoded);
|
||||||
|
});
|
||||||
|
const auto from_successor =
|
||||||
|
checked(replay_cellular_batch(*base, decoded, outcomes, replayed_results, successor),
|
||||||
|
"the successor names the adopted rules");
|
||||||
|
require(from_successor->snapshot() == after->snapshot(), "the successor's rules diverged");
|
||||||
|
// One adoption per batch: its successor can name only one set of rules.
|
||||||
|
auto twice = batch;
|
||||||
|
twice.ticks.front().admin.push_back(cellular_adopt_tuning_command(2, 6, digest));
|
||||||
|
require(!encode_cellular_batch(twice), "two adoptions shared a batch");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADR-0182 section 14: adopted energy cycling returns the region's heat (what its cells used,
|
||||||
|
// and what had built up before) to the spent pool before the drip. The fields sit in a reserved
|
||||||
|
// word, so historical rules keep their bytes; adopted rules restore and replay.
|
||||||
|
void heat_cycles_back() {
|
||||||
|
auto live = revamp_region();
|
||||||
|
for (int tick = 0; tick < 30; ++tick)
|
||||||
|
checked(live->advance_tick(swim(*live, {1'000, 0})), "cells use energy");
|
||||||
|
const auto heat = live->heat().energy.value;
|
||||||
|
require(heat > 0, "the cells used no energy");
|
||||||
|
const auto before = live->revamp_rules();
|
||||||
|
auto cycling = before;
|
||||||
|
cycling.heat_recycle_per_thousand = 1'000;
|
||||||
|
cycling.drip_absorb = true;
|
||||||
|
cycling.drip_interval_ticks = 0; // No drip: the whole recycled heat stays in the pool.
|
||||||
|
const auto old_bytes = encode_cellular_revamp_rules(before);
|
||||||
|
const auto new_bytes = encode_cellular_revamp_rules(cycling);
|
||||||
|
require(cellular_revamp_valid(cycling) && old_bytes.size() == new_bytes.size() &&
|
||||||
|
old_bytes != new_bytes,
|
||||||
|
"the energy cycle is not a same-size distinct encoding");
|
||||||
|
auto excessive = cycling;
|
||||||
|
excessive.heat_recycle_per_thousand = 1'001;
|
||||||
|
require(!cellular_revamp_valid(excessive), "more than all the heat was recycled");
|
||||||
|
|
||||||
|
std::array<std::uint8_t, 32> digest{};
|
||||||
|
digest.fill(9);
|
||||||
|
const std::vector commands{cellular_adopt_tuning_command(1, 7, digest)};
|
||||||
|
std::vector<CellularAdminResult> results;
|
||||||
|
auto after =
|
||||||
|
checked(live->admin_candidate(commands, &results,
|
||||||
|
[&](std::uint64_t, const std::array<std::uint8_t, 32>&) {
|
||||||
|
return std::optional{cycling};
|
||||||
|
}),
|
||||||
|
"the energy cycle is adopted");
|
||||||
|
require(results.size() == 1 && results.front().applied && after->revamp_rules() == cycling,
|
||||||
|
"the energy cycle was not adopted");
|
||||||
|
require(restore(*after)->revamp_rules() == cycling &&
|
||||||
|
restore(*after)->snapshot() == after->snapshot(),
|
||||||
|
"the energy cycle does not restore");
|
||||||
|
|
||||||
|
const auto spent = after->spent().energy.value;
|
||||||
|
const auto twin = restore(*after);
|
||||||
|
const auto intents = swim(*after, {1'000, 0});
|
||||||
|
checked(after->advance_tick(intents), "a cycling tick");
|
||||||
|
require(after->heat().energy.value == 0 && after->spent().energy.value > spent + heat,
|
||||||
|
"the heat, old and new, did not reach the spent pool");
|
||||||
|
checked(twin->advance_tick(intents), "the cycling tick again");
|
||||||
|
require(twin->snapshot() == after->snapshot(), "the cycling tick is not deterministic");
|
||||||
|
// Without the cycle the heat keeps building.
|
||||||
|
checked(live->advance_tick(intents), "a historical tick");
|
||||||
|
require(live->heat().energy.value > heat, "historical rules recycled heat");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A drip at the deposit limit waits, or with the absorbing drip joins an existing bubble.
|
||||||
|
void full_drip_is_absorbed() {
|
||||||
|
biology::CellularHabitatConfig full{};
|
||||||
|
full.world = full.region = full.frame = 1;
|
||||||
|
full.width_um = full.height_um = 1'000;
|
||||||
|
full.format = biology::cellular_habitat_liquid_format;
|
||||||
|
for (std::uint32_t i = 0; i < biology::max_cellular_liquid_deposits; ++i) {
|
||||||
|
biology::CellularPatch bubble{
|
||||||
|
{i % 128 * 7, i / 128 * 11}, 1, {}, i + 1, biology::cellular_mote_radius_um,
|
||||||
|
biology::CellularDepositKind::mote};
|
||||||
|
bubble.merged = 1;
|
||||||
|
bubble.stock.matter[0].value = 10;
|
||||||
|
full.patches.push_back(bubble);
|
||||||
|
}
|
||||||
|
std::ranges::sort(full.patches, {}, &biology::CellularPatch::address);
|
||||||
|
full.next_deposit = biology::max_cellular_liquid_deposits + 1;
|
||||||
|
auto rules = revamp();
|
||||||
|
rules.drip_interval_ticks = 1;
|
||||||
|
accounting::Inventory pool{};
|
||||||
|
pool.energy.value = 30'000'000;
|
||||||
|
pool.matter[0].value = 5;
|
||||||
|
const auto energy = [](const biology::CellularHabitatConfig& c) {
|
||||||
|
std::uint64_t total = 0;
|
||||||
|
for (const auto& patch : c.patches)
|
||||||
|
total += patch.stock.energy.value;
|
||||||
|
return total;
|
||||||
|
};
|
||||||
|
|
||||||
|
auto waiting = full;
|
||||||
|
auto kept = pool;
|
||||||
|
require(cellular_drip_spent(waiting, kept, rules, 1, 1, 1, 1) && kept == pool &&
|
||||||
|
waiting == full,
|
||||||
|
"a full habitat took a drip without absorbing");
|
||||||
|
rules.drip_absorb = true;
|
||||||
|
auto absorbing = full;
|
||||||
|
auto left = pool;
|
||||||
|
require(cellular_drip_spent(absorbing, left, rules, 1, 1, 1, 1), "the absorbing drip");
|
||||||
|
require(absorbing.patches.size() == full.patches.size() &&
|
||||||
|
left.energy.value == pool.energy.value - rules.drip_bubble_pj &&
|
||||||
|
left.matter[0].value == 0 && energy(absorbing) == rules.drip_bubble_pj,
|
||||||
|
"the drip did not join existing bubbles");
|
||||||
|
}
|
||||||
|
|
||||||
// The safety revision preserves all five channels, follows both control choices,
|
// The safety revision preserves all five channels, follows both control choices,
|
||||||
// separates eligible predator/prey siblings and replays their actual motion exactly.
|
// separates eligible predator/prey siblings and replays their actual motion exactly.
|
||||||
void safety_split(bool become) {
|
void safety_split(bool become) {
|
||||||
@@ -1032,6 +1404,12 @@ void safe_bud_provision(bool become) {
|
|||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
int main() try {
|
int main() try {
|
||||||
|
admin_commands_apply_and_replay();
|
||||||
|
take_and_cull();
|
||||||
|
the_wildlife_cap_leaves_room();
|
||||||
|
tuning_is_adopted_and_replayed();
|
||||||
|
heat_cycles_back();
|
||||||
|
full_drip_is_absorbed();
|
||||||
safety_split(false);
|
safety_split(false);
|
||||||
safety_split(true);
|
safety_split(true);
|
||||||
safe_bud_provision(false);
|
safe_bud_provision(false);
|
||||||
|
|||||||
@@ -74,6 +74,10 @@ CellularRevampTuning trial(bool safety = true) {
|
|||||||
t.reproduction_safety_version = 0;
|
t.reproduction_safety_version = 0;
|
||||||
t.body_growth_reserve_seconds = 0;
|
t.body_growth_reserve_seconds = 0;
|
||||||
t.reproduction_split_launch_um_per_s = 0;
|
t.reproduction_split_launch_um_per_s = 0;
|
||||||
|
// The DEV revamp file cycles energy (ADR-0182 section 14).
|
||||||
|
t.spent_heat_recycle_per_mille = 1'000;
|
||||||
|
t.spent_drip_absorb = 1;
|
||||||
|
t.reproduction_wildlife_cap = 200; // Leaves 56 of the 256 lives to players.
|
||||||
}
|
}
|
||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
@@ -155,6 +159,29 @@ void refusals() {
|
|||||||
historical.erase(at, historical.find('\n', at) - at + 1);
|
historical.erase(at, historical.find('\n', at) - at + 1);
|
||||||
}
|
}
|
||||||
CHECK(parse_cellular_revamp_tuning(historical)->reproduction_safety_version == 0);
|
CHECK(parse_cellular_revamp_tuning(historical)->reproduction_safety_version == 0);
|
||||||
|
// The energy cycle keys (ADR-0182 section 14) are optional and bounded.
|
||||||
|
auto uncycled = base;
|
||||||
|
for (const auto* key : {"spent.heat_recycle_per_mille", "spent.drip_absorb"}) {
|
||||||
|
const auto at = uncycled.find(key);
|
||||||
|
uncycled.erase(at, uncycled.find('\n', at) - at + 1);
|
||||||
|
}
|
||||||
|
CHECK(parse_cellular_revamp_tuning(uncycled) == trial());
|
||||||
|
const auto cycled = parse_cellular_revamp_tuning(
|
||||||
|
with(with(base, "spent.heat_recycle_per_mille", "1_000"), "spent.drip_absorb", "1"));
|
||||||
|
CHECK(cycled && cycled->spent_heat_recycle_per_mille == 1'000 &&
|
||||||
|
cycled->spent_drip_absorb == 1);
|
||||||
|
CHECK(error_of(with(base, "spent.heat_recycle_per_mille", "1001")) ==
|
||||||
|
CellularTuningErrorKind::out_of_range);
|
||||||
|
CHECK(error_of(with(base, "spent.drip_absorb", "2")) == CellularTuningErrorKind::out_of_range);
|
||||||
|
// The wildlife cap is optional, at most the organism cap.
|
||||||
|
auto uncapped = base;
|
||||||
|
const auto cap_at = uncapped.find("reproduction.wildlife_cap");
|
||||||
|
uncapped.erase(cap_at, uncapped.find('\n', cap_at) - cap_at + 1);
|
||||||
|
CHECK(parse_cellular_revamp_tuning(uncapped) == trial());
|
||||||
|
CHECK(parse_cellular_revamp_tuning(with(base, "reproduction.wildlife_cap", "200"))
|
||||||
|
->reproduction_wildlife_cap == 200);
|
||||||
|
CHECK(error_of(with(with(base, "reproduction.organism_cap", "100"), "reproduction.wildlife_cap",
|
||||||
|
"101")) == CellularTuningErrorKind::inconsistent);
|
||||||
CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "256")) ==
|
CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "256")) ==
|
||||||
CellularTuningErrorKind::out_of_range);
|
CellularTuningErrorKind::out_of_range);
|
||||||
CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "-1")) ==
|
CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "-1")) ==
|
||||||
|
|||||||
@@ -174,6 +174,24 @@ void actions_bind_to_owned_life_and_preserve_other_inputs() {
|
|||||||
const std::array duplicate{action, action};
|
const std::array duplicate{action, action};
|
||||||
CHECK(prepare_cellular_session_tick(**state, 2, baseline, duplicate).error() ==
|
CHECK(prepare_cellular_session_tick(**state, 2, baseline, duplicate).error() ==
|
||||||
CellularSessionBatchError::duplicate_action);
|
CellularSessionBatchError::duplicate_action);
|
||||||
|
// Two actions of one account on one tick: the discrete one is kept, even when older,
|
||||||
|
// so the tick is not refused for every player; between movements the newest is kept.
|
||||||
|
{
|
||||||
|
const network::CarriedAction bud{network::AccountId{controlled.account}, 80, 2,
|
||||||
|
network::ActionKind::cellular, bud_input};
|
||||||
|
auto later = action;
|
||||||
|
later.action_id = 90;
|
||||||
|
std::vector<network::CarriedAction> both{bud, later};
|
||||||
|
const auto superseded = keep_one_action_per_account(both);
|
||||||
|
CHECK(both.size() == 1 && both[0] == bud && superseded.size() == 1 &&
|
||||||
|
superseded[0] == later);
|
||||||
|
CHECK(prepare_cellular_session_tick(**state, 2, baseline, both));
|
||||||
|
std::vector<network::CarriedAction> moves{action, later};
|
||||||
|
CHECK(keep_one_action_per_account(moves) == std::vector{action} && moves.size() == 1 &&
|
||||||
|
moves[0] == later);
|
||||||
|
std::vector<network::CarriedAction> single{action};
|
||||||
|
CHECK(keep_one_action_per_account(single).empty() && single.size() == 1);
|
||||||
|
}
|
||||||
auto unknown = action;
|
auto unknown = action;
|
||||||
unknown.account.bytes.back() = 3;
|
unknown.account.bytes.back() = 3;
|
||||||
const std::array unknown_actions{unknown};
|
const std::array unknown_actions{unknown};
|
||||||
|
|||||||
@@ -6,13 +6,18 @@
|
|||||||
#include "evo/persistence/account_identity_store.hpp"
|
#include "evo/persistence/account_identity_store.hpp"
|
||||||
#include "evo/persistence/region_lease_store.hpp"
|
#include "evo/persistence/region_lease_store.hpp"
|
||||||
#include "evo/server/admin/admin_api.hpp"
|
#include "evo/server/admin/admin_api.hpp"
|
||||||
|
#include "evo/server/admin/region_switch.hpp"
|
||||||
#include "evo/server/broker/grant_broker.hpp"
|
#include "evo/server/broker/grant_broker.hpp"
|
||||||
#include "evo/server/broker/json.hpp"
|
#include "evo/server/broker/json.hpp"
|
||||||
|
|
||||||
#include <openssl/core_names.h>
|
#include <openssl/core_names.h>
|
||||||
#include <openssl/evp.h>
|
#include <openssl/evp.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
|
#include <fstream>
|
||||||
|
#include <iterator>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <source_location>
|
#include <source_location>
|
||||||
@@ -383,7 +388,7 @@ void admin_api_tests(const Realm& realm) {
|
|||||||
*TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules),
|
*TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules),
|
||||||
[&, online]() -> std::unique_ptr<persistence::Postgres> {
|
[&, online]() -> std::unique_ptr<persistence::Postgres> {
|
||||||
++connects;
|
++connects;
|
||||||
return online ? connect_as(env("EVO_PG_RUNTIME_USER")) : nullptr;
|
return online ? connect_as(env("EVO_PG_ADMIN_USER")) : nullptr;
|
||||||
},
|
},
|
||||||
[&](std::uint64_t region) -> std::optional<std::string> {
|
[&](std::uint64_t region) -> std::optional<std::string> {
|
||||||
++fetches;
|
++fetches;
|
||||||
@@ -477,9 +482,585 @@ void admin_api_tests(const Realm& realm) {
|
|||||||
CHECK(offline.handle({"GET", "/api/accounts", admin}, now, t0).status == 503);
|
CHECK(offline.handle({"GET", "/api/accounts", admin}, now, t0).status == 503);
|
||||||
CHECK(offline.handle({"GET", "/api/regions", admin}, now, t0).status == 503);
|
CHECK(offline.handle({"GET", "/api/regions", admin}, now, t0).status == 503);
|
||||||
|
|
||||||
// The read views are the only way in: the runtime role still cannot read the tables.
|
// Session windows (schema 62): none yet, so sessions are closed.
|
||||||
|
const auto window_of = [&](std::string_view id) {
|
||||||
|
return must(JsonValue::parse(
|
||||||
|
get("/api/regions/" + std::string(id) + "/session-window", admin).body));
|
||||||
|
};
|
||||||
|
const auto post = [&](std::string_view target) {
|
||||||
|
return api.handle({"POST", target, admin}, now, t0);
|
||||||
|
};
|
||||||
|
CHECK(window_of("1").member("open")->boolean() == false &&
|
||||||
|
window_of("1").member("history")->array()->empty());
|
||||||
|
for (const std::string_view bad :
|
||||||
|
{"/api/regions/1/session-window", "/api/regions/1/session-window?minutes=241",
|
||||||
|
"/api/regions/1/session-window?minutes=x", "/api/regions/1/session-window?minutes=1000",
|
||||||
|
"/api/regions/1/session-window?minutes=60&reason=%zz",
|
||||||
|
"/api/regions/1/session-window?minutes=60&reason=a%0Ab"})
|
||||||
|
CHECK(post(bad).status == 400);
|
||||||
|
CHECK(
|
||||||
|
api.handle({"POST", "/api/regions/1/session-window?minutes=60", player}, now, t0).status ==
|
||||||
|
403);
|
||||||
|
CHECK(post("/api/accounts").status == 405 && post("/api/regions/1/view").status == 405);
|
||||||
|
CHECK(post("/api/regions/2/session-window?minutes=60").status == 503); // No such region.
|
||||||
|
|
||||||
|
// Open for an hour, with a reason; the region list and the history show it.
|
||||||
|
const auto opened = post("/api/regions/1/session-window?minutes=60&reason=Playtest+A%21");
|
||||||
|
CHECK(opened.status == 200);
|
||||||
|
const auto first = must(JsonValue::parse(opened.body));
|
||||||
|
const auto first_id = std::string(must(first.member("activation")->string()));
|
||||||
|
CHECK(first_id.starts_with("adm-") && first.member("expires_at")->integer());
|
||||||
|
const auto open_now = window_of("1");
|
||||||
|
const auto& latest = open_now.member("history")->array()->at(0);
|
||||||
|
CHECK(open_now.member("open")->boolean() == true &&
|
||||||
|
latest.member("activation")->string() == first_id &&
|
||||||
|
latest.member("author")->string() == "ops@example.test (ops)" &&
|
||||||
|
latest.member("reason")->string() == "Playtest A!" &&
|
||||||
|
latest.member("expires_at")->integer() == first.member("expires_at")->integer());
|
||||||
|
const auto listed_regions = must(JsonValue::parse(get("/api/regions", admin).body));
|
||||||
|
CHECK(listed_regions.member("regions")->array()->at(0).member("window_open")->boolean() ==
|
||||||
|
true);
|
||||||
|
|
||||||
|
// Extending writes a new activation; closing writes a closing row. Rows never change.
|
||||||
|
const auto extended =
|
||||||
|
must(JsonValue::parse(post("/api/regions/1/session-window?minutes=240").body));
|
||||||
|
CHECK(extended.member("activation")->string() != first_id);
|
||||||
|
CHECK(post("/api/regions/1/session-window?minutes=0&reason=done").status == 200);
|
||||||
|
const auto closed_now = window_of("1");
|
||||||
|
CHECK(closed_now.member("open")->boolean() == false &&
|
||||||
|
closed_now.member("history")->array()->size() == 3 &&
|
||||||
|
closed_now.member("history")->array()->at(0).member("expires_at")->kind() ==
|
||||||
|
JsonValue::Kind::null);
|
||||||
|
|
||||||
|
// The region reads only the newest row; the table refuses rewrites and long windows.
|
||||||
auto runtime = connect_as(env("EVO_PG_RUNTIME_USER"));
|
auto runtime = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
const auto current = runtime->query(
|
||||||
|
"SELECT activation_id, expires_at IS NULL FROM evolution.load_session_window_v1(9831, 1)",
|
||||||
|
{}, 5s);
|
||||||
|
CHECK(current && current->size() == 1 && (*current)[0][1] == "t");
|
||||||
|
CHECK(!runtime->query(
|
||||||
|
"SELECT * FROM evolution.admin_set_session_window_v1(9831, 1, 60, 'x', '')", {}, 5s));
|
||||||
|
runtime = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
CHECK(!runtime->query("SELECT * FROM evolution.admin_accounts_v1(9831)", {}, 5s));
|
||||||
|
auto owner = connect_as(env("PGUSER"));
|
||||||
|
CHECK(!owner->query("UPDATE evolution.session_windows SET reason = 'x'", {}, 5s));
|
||||||
|
owner = connect_as(env("PGUSER"));
|
||||||
|
CHECK(!owner->query("DELETE FROM evolution.session_windows", {}, 5s));
|
||||||
|
owner = connect_as(env("PGUSER"));
|
||||||
|
CHECK(!owner->query("INSERT INTO evolution.session_windows(world_id, region_id, "
|
||||||
|
"activation_id, expires_at, author_subject) VALUES (9831, 1, 'long', "
|
||||||
|
"clock_timestamp() + interval '5 hours', 'x')",
|
||||||
|
{}, 5s));
|
||||||
|
owner = connect_as(env("PGUSER"));
|
||||||
|
CHECK(!owner->query(
|
||||||
|
"SELECT * FROM evolution.admin_set_session_window_v1(9831, 1, 14401, 'x', '')", {}, 5s));
|
||||||
|
|
||||||
|
// Admin commands (schema 63): queued with the admin's identity, shape-checked, listed.
|
||||||
|
for (const std::string_view bad :
|
||||||
|
{"/api/regions/1/commands", "/api/regions/1/commands?kind=explode",
|
||||||
|
"/api/regions/1/commands?kind=add_pool", "/api/regions/1/commands?kind=add_pool&energy=x",
|
||||||
|
"/api/regions/1/commands?kind=remove_cell&target=7&energy=5",
|
||||||
|
"/api/regions/1/commands?kind=spawn_wildlife&count=257",
|
||||||
|
"/api/regions/1/commands?kind=take_reserve&target=7",
|
||||||
|
"/api/regions/1/commands?kind=remove_wildlife&target=7",
|
||||||
|
"/api/regions/1/commands?kind=remove_wildlife&energy=1"})
|
||||||
|
CHECK(post(bad).status == 400);
|
||||||
|
// Schema 67: take_reserve and remove_wildlife.
|
||||||
|
CHECK(post("/api/regions/1/commands?kind=take_reserve&target=424242&energy=5").status == 200);
|
||||||
|
CHECK(post("/api/regions/1/commands?kind=remove_wildlife").status == 200);
|
||||||
|
const auto queued =
|
||||||
|
must(JsonValue::parse(post("/api/regions/1/commands?kind=add_pool&energy=1000&carbon=7"
|
||||||
|
"&reason=top+up")
|
||||||
|
.body));
|
||||||
|
CHECK(queued.member("id") && queued.member("target")->string() == "0");
|
||||||
|
CHECK(post("/api/regions/1/commands?kind=remove_cell&target=424242").status == 200);
|
||||||
|
CHECK(post("/api/regions/2/commands?kind=add_pool&energy=1").status == 400);
|
||||||
|
const auto listed_commands = must(JsonValue::parse(get("/api/regions/1/commands", admin).body));
|
||||||
|
const auto& newest = listed_commands.member("commands")->array()->at(0);
|
||||||
|
const auto& older = listed_commands.member("commands")->array()->at(1);
|
||||||
|
CHECK(newest.member("kind")->string() == "remove_cell" &&
|
||||||
|
newest.member("target")->string() == "424242" &&
|
||||||
|
newest.member("applied_tick")->kind() == JsonValue::Kind::null &&
|
||||||
|
older.member("kind")->string() == "add_pool" &&
|
||||||
|
older.member("amount")->array()->at(0).string() == "1000" &&
|
||||||
|
older.member("amount")->array()->at(1).string() == "7" &&
|
||||||
|
older.member("reason")->string() == "top up" &&
|
||||||
|
older.member("author")->string() == "ops@example.test (ops)");
|
||||||
|
{
|
||||||
|
auto reader = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
const auto pending = reader->query(
|
||||||
|
"SELECT count(*) FROM evolution.load_pending_admin_commands_v1(9831, 1)", {}, 5s);
|
||||||
|
CHECK(pending && (*pending)[0][0] == "4");
|
||||||
|
CHECK(!reader->query("SELECT * FROM evolution.admin_enqueue_command_v1(9831, 1, 4, 0, 0, "
|
||||||
|
"1, 0, 0, 0, 0, 'x', '')",
|
||||||
|
{}, 5s));
|
||||||
|
reader = connect_as(env("PGUSER"));
|
||||||
|
CHECK(!reader->query("DELETE FROM evolution.admin_commands", {}, 5s));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resource schedules (schema 65): a due schedule queues one command, never a second
|
||||||
|
// while that one waits; the list shows the run; stopping writes a new version.
|
||||||
|
for (const std::string_view bad :
|
||||||
|
{"/api/regions/1/schedules?kind=add_pool&count=1&interval=5&energy=1",
|
||||||
|
"/api/regions/1/schedules?kind=add_bubbles&count=4&interval=0&energy=1",
|
||||||
|
"/api/regions/1/schedules?kind=add_bubbles&count=4&interval=90000&energy=1",
|
||||||
|
"/api/regions/1/schedules?kind=add_bubbles&count=4&interval=5"})
|
||||||
|
CHECK(post(bad).status == 400);
|
||||||
|
const auto made = must(JsonValue::parse(
|
||||||
|
post("/api/regions/1/schedules?kind=add_bubbles&count=4&interval=60&energy=100&"
|
||||||
|
"reason=feed")
|
||||||
|
.body));
|
||||||
|
const auto schedule_id = std::string(must(made.member("id")->string()));
|
||||||
|
const auto pending_now = [&] {
|
||||||
|
auto reader = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
const auto rows = reader->query(
|
||||||
|
"SELECT count(*) FROM evolution.load_pending_admin_commands_v1(9831, 1)", {}, 5s);
|
||||||
|
CHECK(rows && rows->size() == 1);
|
||||||
|
return std::string(*(*rows)[0][0]);
|
||||||
|
};
|
||||||
|
CHECK(pending_now() == "5" && pending_now() == "5");
|
||||||
|
const auto listed_schedules =
|
||||||
|
must(JsonValue::parse(get("/api/regions/1/schedules", admin).body));
|
||||||
|
const auto& schedule = listed_schedules.member("schedules")->array()->at(0);
|
||||||
|
CHECK(schedule.member("id")->string() == schedule_id &&
|
||||||
|
schedule.member("kind")->string() == "add_bubbles" &&
|
||||||
|
schedule.member("runs")->integer() == 1 &&
|
||||||
|
schedule.member("enabled")->boolean() == true &&
|
||||||
|
schedule.member("interval")->integer() == 60);
|
||||||
|
const auto queued_by_schedule =
|
||||||
|
must(JsonValue::parse(get("/api/regions/1/commands", admin).body));
|
||||||
|
CHECK(queued_by_schedule.member("commands")->array()->at(0).member("author")->string() ==
|
||||||
|
"schedule " + schedule_id);
|
||||||
|
CHECK(post("/api/regions/1/schedules?kind=add_bubbles&count=4&interval=60&energy=100&"
|
||||||
|
"enabled=0&id=" +
|
||||||
|
schedule_id)
|
||||||
|
.status == 200);
|
||||||
|
const auto stopped = must(JsonValue::parse(get("/api/regions/1/schedules", admin).body));
|
||||||
|
CHECK(stopped.member("schedules")->array()->size() == 1 &&
|
||||||
|
stopped.member("schedules")->array()->at(0).member("enabled")->boolean() == false);
|
||||||
|
CHECK(post("/api/regions/1/schedules?kind=add_bubbles&count=4&interval=60&energy=1&id=999999")
|
||||||
|
.status == 400);
|
||||||
|
|
||||||
|
// Tuning revisions (schema 66): a request body in the Git revamp file format, checked,
|
||||||
|
// stored with the admin's identity and queued as an adopt_tuning command per region.
|
||||||
|
{
|
||||||
|
const auto file = [](std::string_view name) {
|
||||||
|
std::ifstream in{env("EVO_SOURCE_ROOT") + "/deploy/kubernetes/region/dev/tuning/" +
|
||||||
|
std::string(name),
|
||||||
|
std::ios::binary};
|
||||||
|
return std::string{std::istreambuf_iterator<char>{in}, {}};
|
||||||
|
};
|
||||||
|
const auto baseline = file("cellular-revamp.tuning");
|
||||||
|
CHECK(!baseline.empty());
|
||||||
|
server::admin::AdminConfig config;
|
||||||
|
config.world = 9831;
|
||||||
|
config.view_regions = {1};
|
||||||
|
config.baseline_tuning = baseline;
|
||||||
|
config.region_tuning = file("cellular.tuning");
|
||||||
|
AdminApi tuned{config,
|
||||||
|
*TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules),
|
||||||
|
[] { return connect_as(env("EVO_PG_ADMIN_USER")); },
|
||||||
|
[](std::uint64_t) { return std::optional<std::string>{}; },
|
||||||
|
{}};
|
||||||
|
const auto send = [&](std::string_view target, std::string_view body) {
|
||||||
|
return tuned.handle({"POST", target, admin, body}, now, t0);
|
||||||
|
};
|
||||||
|
const auto read = [&](std::string_view target) {
|
||||||
|
return tuned.handle({"GET", target, admin}, now, t0);
|
||||||
|
};
|
||||||
|
const auto none = must(JsonValue::parse(read("/api/tuning").body));
|
||||||
|
const auto digest =
|
||||||
|
std::string(must(none.member("baseline")->member("rules_sha256")->string()));
|
||||||
|
CHECK(none.member("newest")->kind() == JsonValue::Kind::null &&
|
||||||
|
none.member("revisions")->array()->empty() &&
|
||||||
|
none.member("baseline")->member("text")->string() == baseline &&
|
||||||
|
digest.size() == 64 && none.member("regions")->array()->at(0).string() == "1" &&
|
||||||
|
none.member("region_file")->string() == config.region_tuning);
|
||||||
|
|
||||||
|
// Bodies go to /api/tuning only; check=1 stores nothing.
|
||||||
|
CHECK(tuned
|
||||||
|
.handle({"POST", "/api/regions/1/commands?kind=add_pool&energy=1", admin, "x"},
|
||||||
|
now, t0)
|
||||||
|
.status == 400);
|
||||||
|
const auto checked = must(JsonValue::parse(send("/api/tuning?check=1", baseline).body));
|
||||||
|
CHECK(checked.member("valid")->boolean() == true &&
|
||||||
|
checked.member("rules_sha256")->string() == digest &&
|
||||||
|
checked.member("safety_version")->integer() == 0);
|
||||||
|
// Problems name the kind, line and key; the safety revision cannot change live.
|
||||||
|
const auto lines = std::ranges::count(baseline, '\n');
|
||||||
|
const auto unknown = must(
|
||||||
|
JsonValue::parse(send("/api/tuning?check=1", baseline + "no.such_key = 1\n").body));
|
||||||
|
CHECK(unknown.member("error")->string() == "invalid_tuning" &&
|
||||||
|
unknown.member("kind")->string() == "unknown_key" &&
|
||||||
|
unknown.member("key")->string() == "no.such_key" &&
|
||||||
|
unknown.member("line")->integer() == lines + 1);
|
||||||
|
CHECK(send("/api/tuning", "").status == 400 &&
|
||||||
|
send("/api/tuning", "a = \x01").status == 400);
|
||||||
|
const auto unsafe = must(JsonValue::parse(
|
||||||
|
send("/api/tuning?check=1", file("cellular-reproduction-safety.tuning")).body));
|
||||||
|
CHECK(unsafe.member("error")->string() == "safety_version_changed" &&
|
||||||
|
unsafe.member("expected")->integer() == 0);
|
||||||
|
CHECK(
|
||||||
|
must(JsonValue::parse(read("/api/tuning").body)).member("revisions")->array()->empty());
|
||||||
|
|
||||||
|
// A slower drip: stored, listed, and queued for region 1 with its digest.
|
||||||
|
auto changed = baseline;
|
||||||
|
const auto at = changed.find("spent.drip_interval_ticks = 20");
|
||||||
|
CHECK(at != std::string::npos);
|
||||||
|
changed.replace(at, 30, "spent.drip_interval_ticks = 40");
|
||||||
|
const auto stored =
|
||||||
|
must(JsonValue::parse(send("/api/tuning?reason=slower+drip", changed).body));
|
||||||
|
const auto revision = std::string(must(stored.member("revision")->string()));
|
||||||
|
const auto changed_digest = std::string(must(stored.member("rules_sha256")->string()));
|
||||||
|
CHECK(changed_digest != digest && stored.member("regions")->integer() == 1);
|
||||||
|
const auto listed_tuning = must(JsonValue::parse(read("/api/tuning").body));
|
||||||
|
const auto& entry = listed_tuning.member("revisions")->array()->at(0);
|
||||||
|
CHECK(listed_tuning.member("newest")->member("revision")->string() == revision &&
|
||||||
|
listed_tuning.member("newest")->member("text")->string() == changed &&
|
||||||
|
entry.member("rules_sha256")->string() == changed_digest &&
|
||||||
|
entry.member("reason")->string() == "slower drip" &&
|
||||||
|
entry.member("author")->string() == "ops@example.test (ops)" &&
|
||||||
|
entry.member("regions")->integer() == 1 && entry.member("adopted")->integer() == 0);
|
||||||
|
CHECK(
|
||||||
|
must(JsonValue::parse(read("/api/tuning/" + revision).body)).member("text")->string() ==
|
||||||
|
changed);
|
||||||
|
CHECK(read("/api/tuning/999999").status == 404 && read("/api/tuning/0").status == 404 &&
|
||||||
|
read("/api/tuning/x").status == 404);
|
||||||
|
std::uint64_t first_word = 0;
|
||||||
|
for (std::size_t b = 0; b < 8; ++b)
|
||||||
|
first_word |= std::stoull(changed_digest.substr(b * 2, 2), nullptr, 16) << (8 * b);
|
||||||
|
auto reader = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
const auto adoption =
|
||||||
|
reader->query("SELECT cell_count, target, energy, other FROM "
|
||||||
|
"evolution.load_pending_admin_commands_v1(9831, 1) WHERE kind = 7",
|
||||||
|
{}, 5s);
|
||||||
|
CHECK(adoption && adoption->size() == 1 && (*adoption)[0][0] == "0" &&
|
||||||
|
(*adoption)[0][1] == revision && (*adoption)[0][2] == std::to_string(first_word) &&
|
||||||
|
(*adoption)[0][3] == "0");
|
||||||
|
const auto text = reader->query(
|
||||||
|
"SELECT text, encode(rules_sha256, 'hex') FROM evolution.load_tuning_revision_v1(9831, "
|
||||||
|
"$1::bigint)",
|
||||||
|
std::array{revision}, 5s);
|
||||||
|
CHECK(text && text->size() == 1 && (*text)[0][0] == changed &&
|
||||||
|
(*text)[0][1] == changed_digest);
|
||||||
|
// Only the admin stores revisions, rows never change, and kind 7 is never queued by hand.
|
||||||
|
CHECK(!reader->query("SELECT evolution.admin_set_tuning_v1(9831, 'x', "
|
||||||
|
"decode(repeat('ab', 32), 'hex'), '{1}', 'x', '')",
|
||||||
|
{}, 5s));
|
||||||
|
reader = connect_as(env("PGUSER"));
|
||||||
|
CHECK(!reader->query("UPDATE evolution.tuning_revisions SET reason = 'x'", {}, 5s));
|
||||||
|
CHECK(post("/api/regions/1/commands?kind=adopt_tuning&target=1").status == 400);
|
||||||
|
CHECK(post("/api/regions/1/schedules?kind=adopt_tuning&count=1&interval=60").status == 400);
|
||||||
|
// An unknown region (3 has no lease) refuses the whole revision.
|
||||||
|
CHECK(api.handle({"POST", "/api/tuning", admin, changed}, now, t0).status == 400);
|
||||||
|
CHECK(
|
||||||
|
must(JsonValue::parse(read("/api/tuning").body)).member("revisions")->array()->size() ==
|
||||||
|
1);
|
||||||
|
|
||||||
|
// The guided editor sends only changes against a base: the newest revision or the
|
||||||
|
// baseline file. Values are replaced in place (comments kept), absent keys appended,
|
||||||
|
// and a base that is no longer the newest is refused.
|
||||||
|
const auto back = must(JsonValue::parse(
|
||||||
|
send("/api/tuning?check=1&base=" + revision, "spent.drip_interval_ticks = 20\n").body));
|
||||||
|
CHECK(back.member("rules_sha256")->string() == digest);
|
||||||
|
CHECK(send("/api/tuning?check=1&base=baseline", "").status == 200);
|
||||||
|
CHECK(send("/api/tuning?check=1&base=999999", "").status == 409);
|
||||||
|
CHECK(send("/api/tuning?check=1&base=x", "").status == 400);
|
||||||
|
CHECK(send("/api/tuning?check=1&base=baseline", "spent.drip_interval_ticks = 1 # x\n")
|
||||||
|
.status == 400);
|
||||||
|
CHECK(send("/api/tuning?check=1&base=baseline",
|
||||||
|
"spent.drip_absorb = 1\nspent.drip_absorb = 0\n")
|
||||||
|
.status == 400);
|
||||||
|
const auto appended = must(
|
||||||
|
JsonValue::parse(send("/api/tuning?check=1&base=baseline", "no.such_key = 1\n").body));
|
||||||
|
CHECK(appended.member("kind")->string() == "unknown_key");
|
||||||
|
const auto guided = must(JsonValue::parse(
|
||||||
|
send("/api/tuning?reason=guided&base=" + revision, "spent.drip_interval_ticks = 30\n")
|
||||||
|
.body));
|
||||||
|
const auto guided_revision = std::string(must(guided.member("revision")->string()));
|
||||||
|
auto expected = changed;
|
||||||
|
expected.replace(expected.find("spent.drip_interval_ticks = 40"), 30,
|
||||||
|
"spent.drip_interval_ticks = 30");
|
||||||
|
CHECK(must(JsonValue::parse(read("/api/tuning/" + guided_revision).body))
|
||||||
|
.member("text")
|
||||||
|
->string() == expected);
|
||||||
|
CHECK(send("/api/tuning?check=1&base=" + revision, "").status == 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADR-0182 section 15: opening a region. The HTTPS reader and the four-file switch first,
|
||||||
|
// over the repository's own files, then the endpoints against fake Gitea and Argo CD.
|
||||||
|
{
|
||||||
|
using server::admin::HttpsRequest;
|
||||||
|
using server::admin::HttpsResponse;
|
||||||
|
using server::admin::parse_http_response;
|
||||||
|
using server::admin::region_switch_paths;
|
||||||
|
const auto sized = parse_http_response(
|
||||||
|
"HTTP/1.1 201 Created\r\nContent-Length: 5\r\nX: y\r\n\r\nhello", 100);
|
||||||
|
CHECK(sized && sized->status == 201 && sized->body == "hello");
|
||||||
|
const auto chunked =
|
||||||
|
parse_http_response("HTTP/1.1 200 OK\r\nTransfer-Encoding: "
|
||||||
|
"chunked\r\n\r\n4\r\nwiki\r\n5;x=1\r\npedia\r\n0\r\n\r\n",
|
||||||
|
100);
|
||||||
|
CHECK(chunked && chunked->status == 200 && chunked->body == "wikipedia");
|
||||||
|
CHECK(!parse_http_response("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nwi",
|
||||||
|
100));
|
||||||
|
CHECK(!parse_http_response("HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nshort", 100));
|
||||||
|
CHECK(!parse_http_response("HTTP/1.1 200 OK\r\n\r\nlong enough", 4));
|
||||||
|
CHECK(!parse_http_response("SSH-2.0 hello\r\n\r\n", 100));
|
||||||
|
const auto with_prefix = server::admin::parse_https_base("https://git.example:8443/gitea/");
|
||||||
|
CHECK(with_prefix && with_prefix->host == "git.example" && with_prefix->port == 8443 &&
|
||||||
|
with_prefix->prefix == "/gitea");
|
||||||
|
const auto bare =
|
||||||
|
server::admin::parse_https_base("argocd-server.argocd.svc.cluster.local:443");
|
||||||
|
CHECK(bare && bare->host == "argocd-server.argocd.svc.cluster.local" && bare->port == 443 &&
|
||||||
|
bare->prefix.empty());
|
||||||
|
CHECK(!server::admin::parse_https_base("http://plain.example"));
|
||||||
|
|
||||||
|
server::admin::RegionSwitchFiles files;
|
||||||
|
for (std::size_t i = 0; i < files.size(); ++i) {
|
||||||
|
std::ifstream in{env("EVO_SOURCE_ROOT") + "/" + std::string(region_switch_paths.at(i)),
|
||||||
|
std::ios::binary};
|
||||||
|
files.at(i) = std::string{std::istreambuf_iterator<char>{in}, {}};
|
||||||
|
}
|
||||||
|
const auto layout = server::admin::read_region_layout(files);
|
||||||
|
CHECK(layout && layout->region != 0 && layout->wildlife_first != 0);
|
||||||
|
auto to = *layout;
|
||||||
|
to.region += 1;
|
||||||
|
to.wildlife_first += 100;
|
||||||
|
to.commit = std::string(32, 'e');
|
||||||
|
const auto switched =
|
||||||
|
server::admin::switch_region(files, to, "region opened_region by a test");
|
||||||
|
CHECK(switched && server::admin::read_region_layout(*switched) == to);
|
||||||
|
// Only the named lines change (and the note above the opening is added).
|
||||||
|
const auto lines = [](const std::string& text) {
|
||||||
|
std::vector<std::string> out;
|
||||||
|
for (std::size_t at = 0; at < text.size();) {
|
||||||
|
const auto end = std::min(text.find('\n', at), text.size());
|
||||||
|
const auto line = text.substr(at, end - at);
|
||||||
|
if (line.find("# Admin portal (ADR-0182 section 15)") == std::string::npos)
|
||||||
|
out.push_back(line);
|
||||||
|
at = end + 1;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
for (std::size_t i = 0; switched && i < files.size(); ++i) {
|
||||||
|
const auto before = lines(files.at(i));
|
||||||
|
const auto after = lines(switched->at(i));
|
||||||
|
CHECK(before.size() == after.size());
|
||||||
|
for (std::size_t l = 0; l < std::min(before.size(), after.size()); ++l)
|
||||||
|
if (before[l] != after[l])
|
||||||
|
CHECK(std::ranges::any_of(
|
||||||
|
std::array<std::string_view, 8>{"REGION_ID", "REGION_LIFE_ROUTES",
|
||||||
|
"--commit", "--playtest-wildlife-first-id",
|
||||||
|
"Region host", "BROKER_DEFAULT_REGION",
|
||||||
|
"BROKER_ROUTES", "ADMIN_REGIONS"},
|
||||||
|
[&](std::string_view key) {
|
||||||
|
return after[l].find(key) != std::string::npos;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
CHECK(switched &&
|
||||||
|
switched->at(0).find("# Admin portal (ADR-0182 section 15): region opened_region "
|
||||||
|
"by a test\n - {name: REGION_OPENING") !=
|
||||||
|
std::string::npos);
|
||||||
|
CHECK(server::admin::switch_region(*switched, to, "again").error() == "target");
|
||||||
|
CHECK(server::admin::switch_region(files, to, "two\nlines").error() == "note");
|
||||||
|
auto broken = files;
|
||||||
|
broken.at(0).replace(broken.at(0).find("{name: REGION_ID"), 4, "{nom");
|
||||||
|
CHECK(server::admin::read_region_layout(broken).error() == "REGION_ID");
|
||||||
|
|
||||||
|
// The endpoints against fake services serving the repository files for world 9831.
|
||||||
|
for (auto& text : files)
|
||||||
|
for (const auto& from : {std::string{"REGION_WORLD, value: \"100\""},
|
||||||
|
std::string{"evolution-dev: world 100,"}})
|
||||||
|
for (auto at = text.find(from); at != std::string::npos; at = text.find(from, at))
|
||||||
|
text.replace(at, from.size(),
|
||||||
|
from == "evolution-dev: world 100,"
|
||||||
|
? std::string{"evolution-dev: world 9831,"}
|
||||||
|
: std::string{"REGION_WORLD, value: \"9831\""});
|
||||||
|
const auto head = std::string(40, 'a');
|
||||||
|
const auto made_commit = std::string(40, 'c');
|
||||||
|
std::vector<HttpsRequest> seen;
|
||||||
|
std::string argo_phase = "Succeeded";
|
||||||
|
int commit_status = 201;
|
||||||
|
const server::admin::HttpsTransport fake =
|
||||||
|
[&](const HttpsRequest& request) -> std::optional<HttpsResponse> {
|
||||||
|
seen.push_back(request);
|
||||||
|
const auto& t = request.target;
|
||||||
|
if (request.host == "argo.test") {
|
||||||
|
if (request.method == "POST")
|
||||||
|
return HttpsResponse{200, "{}"};
|
||||||
|
return HttpsResponse{200,
|
||||||
|
"{\"items\":[{\"metadata\":{\"name\":\"aevolution-dev\"},"
|
||||||
|
"\"status\":{\"sync\":{\"status\":\"Synced\",\"revision\":\"" +
|
||||||
|
head +
|
||||||
|
"\"},\"health\":{\"status\":\"Healthy\"},"
|
||||||
|
"\"operationState\":{\"phase\":\"" +
|
||||||
|
argo_phase + "\",\"message\":\"done\"}}}]}"};
|
||||||
|
}
|
||||||
|
if (t == "/api/v1/repos/dingo/AEvolution/branches/main")
|
||||||
|
return HttpsResponse{200,
|
||||||
|
"{\"name\":\"main\",\"commit\":{\"id\":\"" + head + "\"}}"};
|
||||||
|
if (request.method == "POST" && t == "/api/v1/repos/dingo/AEvolution/contents")
|
||||||
|
return HttpsResponse{commit_status,
|
||||||
|
"{\"commit\":{\"sha\":\"" + made_commit + "\"}}"};
|
||||||
|
for (std::size_t i = 0; i < region_switch_paths.size(); ++i) {
|
||||||
|
const std::string path(region_switch_paths.at(i));
|
||||||
|
std::string raw = "/api/v1/repos/dingo/AEvolution/raw/";
|
||||||
|
raw.append(path).append("?ref=").append(head);
|
||||||
|
if (t == raw)
|
||||||
|
return HttpsResponse{200, files.at(i)};
|
||||||
|
}
|
||||||
|
constexpr std::string_view listing = "/api/v1/repos/dingo/AEvolution/contents/";
|
||||||
|
if (t.starts_with(listing)) {
|
||||||
|
const auto dir = t.substr(listing.size(), t.find('?') - listing.size());
|
||||||
|
std::string out = "[";
|
||||||
|
for (std::size_t i = 0; i < region_switch_paths.size(); ++i) {
|
||||||
|
const std::string path(region_switch_paths.at(i));
|
||||||
|
if (path.substr(0, path.rfind('/')) == dir)
|
||||||
|
out += std::string(out.size() == 1 ? "" : ",") + "{\"name\":\"" +
|
||||||
|
path.substr(path.rfind('/') + 1) + "\",\"sha\":\"" +
|
||||||
|
std::string(40, static_cast<char>('1' + i)) + "\"}";
|
||||||
|
}
|
||||||
|
return HttpsResponse{200, out + "]"};
|
||||||
|
}
|
||||||
|
return HttpsResponse{404, "{}"};
|
||||||
|
};
|
||||||
|
server::admin::AdminConfig config;
|
||||||
|
config.world = 9831;
|
||||||
|
config.view_regions = {1};
|
||||||
|
std::ifstream revamp{env("EVO_SOURCE_ROOT") +
|
||||||
|
"/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning",
|
||||||
|
std::ios::binary};
|
||||||
|
config.baseline_tuning = std::string{std::istreambuf_iterator<char>{revamp}, {}};
|
||||||
|
AdminApi deploying{config,
|
||||||
|
*TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules),
|
||||||
|
[] { return connect_as(env("EVO_PG_ADMIN_USER")); },
|
||||||
|
[](std::uint64_t) { return std::optional<std::string>{}; },
|
||||||
|
{}};
|
||||||
|
const auto ask = [&](std::string_view method, std::string_view target) {
|
||||||
|
return deploying.handle({method, target, admin}, now, t0);
|
||||||
|
};
|
||||||
|
CHECK(ask("GET", "/api/deploy").body == "{\"configured\":false}\n");
|
||||||
|
CHECK(ask("POST", "/api/deploy/region?region=17").status == 503);
|
||||||
|
deploying.enable_deploy({.gitea_base = "https://git.test",
|
||||||
|
.gitea_repository = "dingo/AEvolution",
|
||||||
|
.gitea_token = "gitea-secret",
|
||||||
|
.branch = "main",
|
||||||
|
.argo_server = "argo.test:443",
|
||||||
|
.argo_application = "aevolution-dev",
|
||||||
|
.argo_token = "argo-secret",
|
||||||
|
.argo_verify = false},
|
||||||
|
fake);
|
||||||
|
const auto status = must(JsonValue::parse(ask("GET", "/api/deploy").body));
|
||||||
|
const auto served = std::to_string(layout->region);
|
||||||
|
const auto next = std::string(must(status.member("next")->member("region")->string()));
|
||||||
|
CHECK(status.member("configured")->boolean() == true &&
|
||||||
|
status.member("current")->member("region")->string() == served &&
|
||||||
|
status.member("current")->member("world")->string() == "9831" &&
|
||||||
|
status.member("next")->member("wildlife_first")->string() ==
|
||||||
|
std::to_string(layout->wildlife_first + 100) &&
|
||||||
|
status.member("argo")->member("phase")->string() == "Succeeded" &&
|
||||||
|
status.member("git")->member("head")->string() == head &&
|
||||||
|
std::stoull(next) > layout->region);
|
||||||
|
CHECK(must(JsonValue::parse(ask("GET", "/api/deploy?argo=1").body)).member("current") ==
|
||||||
|
nullptr);
|
||||||
|
// Credentials only in headers; Argo's in-cluster hop may skip verification, Gitea's not.
|
||||||
|
for (const auto& request : seen)
|
||||||
|
CHECK(request.target.find("secret") == std::string::npos &&
|
||||||
|
std::ranges::count(request.headers,
|
||||||
|
std::pair<std::string, std::string>{
|
||||||
|
"Authorization", request.host == "argo.test"
|
||||||
|
? "Bearer argo-secret"
|
||||||
|
: "token gitea-secret"}) == 1 &&
|
||||||
|
request.verify == (request.host != "argo.test"));
|
||||||
|
// Refusals: a stale region number, a sync already running, a refused commit.
|
||||||
|
CHECK(ask("POST", "/api/deploy/region?region=" + std::to_string(std::stoull(next) + 1))
|
||||||
|
.status == 409);
|
||||||
|
argo_phase = "Running";
|
||||||
|
CHECK(ask("POST", "/api/deploy/region?region=" + next).status == 409);
|
||||||
|
argo_phase = "Succeeded";
|
||||||
|
commit_status = 409;
|
||||||
|
CHECK(ask("POST", "/api/deploy/region?region=" + next).status == 409);
|
||||||
|
commit_status = 201;
|
||||||
|
seen.clear();
|
||||||
|
const auto opened_region =
|
||||||
|
ask("POST", "/api/deploy/region?region=" + next + "&reason=fresh+start");
|
||||||
|
const auto result = must(JsonValue::parse(opened_region.body));
|
||||||
|
CHECK(opened_region.status == 200 && result.member("region")->string() == next &&
|
||||||
|
result.member("from")->string() == served &&
|
||||||
|
result.member("commit")->string() == made_commit &&
|
||||||
|
result.member("sync_started")->boolean() == true);
|
||||||
|
const auto commit = std::ranges::find_if(
|
||||||
|
seen, [](const HttpsRequest& r) { return r.method == "POST" && r.host == "git.test"; });
|
||||||
|
const auto sync = std::ranges::find_if(seen, [](const HttpsRequest& r) {
|
||||||
|
return r.method == "POST" && r.host == "argo.test";
|
||||||
|
});
|
||||||
|
CHECK(commit != seen.end() && sync != seen.end() &&
|
||||||
|
sync->target == "/api/v1/applications/aevolution-dev/sync" &&
|
||||||
|
sync->body == "{\"revision\":\"" + made_commit + "\",\"prune\":true}");
|
||||||
|
if (commit != seen.end()) {
|
||||||
|
const auto body = must(JsonValue::parse(commit->body, 1U << 20U));
|
||||||
|
CHECK(body.member("branch")->string() == "main" &&
|
||||||
|
std::string(must(body.member("message")->string())).find("open region " + next) !=
|
||||||
|
std::string::npos &&
|
||||||
|
std::string(must(body.member("message")->string())).find("ops@example.test") !=
|
||||||
|
std::string::npos &&
|
||||||
|
body.member("files")->array()->size() == 4);
|
||||||
|
const auto& first_file = body.member("files")->array()->at(0);
|
||||||
|
CHECK(first_file.member("path")->string() == region_switch_paths.at(0) &&
|
||||||
|
first_file.member("sha")->string() == std::string(40, '1') &&
|
||||||
|
first_file.member("operation")->string() == "update");
|
||||||
|
const auto encoded = std::string(must(first_file.member("content")->string()));
|
||||||
|
std::string decoded(encoded.size(), '\0');
|
||||||
|
const auto length =
|
||||||
|
EVP_DecodeBlock(reinterpret_cast<unsigned char*>(decoded.data()),
|
||||||
|
reinterpret_cast<const unsigned char*>(encoded.data()),
|
||||||
|
static_cast<int>(encoded.size()));
|
||||||
|
CHECK(length > 0);
|
||||||
|
decoded.resize(static_cast<std::size_t>(length) -
|
||||||
|
static_cast<std::size_t>(std::ranges::count(encoded, '=')));
|
||||||
|
CHECK(decoded.find("{name: REGION_ID, value: \"" + next + "\"}") != std::string::npos &&
|
||||||
|
decoded.find("--playtest-wildlife-first-id " +
|
||||||
|
std::to_string(layout->wildlife_first + 100)) != std::string::npos &&
|
||||||
|
decoded.find("in place of " + served + "; seeded wildlife") != std::string::npos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accounts (schema 64): control claims recorded alice's sessions; a ban refuses grants
|
||||||
|
// and is listed with its reason; lifting it restores them; an admin logout succeeds.
|
||||||
|
CHECK(alice->member("sessions")->integer().value_or(0) >= 1 &&
|
||||||
|
alice->member("banned")->boolean() == false);
|
||||||
|
const auto alice_path = "/api/accounts/" + alice_id;
|
||||||
|
CHECK(post(alice_path + "/ban?banned=2").status == 400);
|
||||||
|
CHECK(post(alice_path + "/other").status == 405); // Not an account action.
|
||||||
|
CHECK(api.handle({"POST", alice_path, admin}, now, t0).status == 405);
|
||||||
|
CHECK(post(alice_path + "/ban?banned=1&reason=cheating").body == "{\"banned\":true}\n");
|
||||||
|
const auto banned_view = must(JsonValue::parse(get(alice_path, admin).body));
|
||||||
|
CHECK(banned_view.member("account")->member("banned")->boolean() == true &&
|
||||||
|
banned_view.member("bans")->array()->at(0).member("reason")->string() == "cheating");
|
||||||
|
{
|
||||||
|
auto broker_db = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
|
const auto refused =
|
||||||
|
persistence::issue_account_grant(*broker_db, 9831, issuer, "alice-sub", 5s);
|
||||||
|
CHECK(!refused && refused.error() == persistence::AccountIdentityError::banned);
|
||||||
|
CHECK(post(alice_path + "/ban?banned=0").body == "{\"banned\":false}\n");
|
||||||
|
CHECK(persistence::issue_account_grant(*broker_db, 9831, issuer, "alice-sub", 5s));
|
||||||
|
}
|
||||||
|
CHECK(post(alice_path + "/logout").body == "{\"logged_out\":true}\n");
|
||||||
|
// Schema 69: only a published life can be ended (cellular_publication_tests ends one).
|
||||||
|
CHECK(post(alice_path + "/end-life").status == 400 &&
|
||||||
|
post(alice_path + "/end-life?request=0").status == 400);
|
||||||
|
const auto unpublished = post(alice_path + "/end-life?request=1");
|
||||||
|
CHECK(unpublished.status == 404 &&
|
||||||
|
unpublished.body.find("no_published_life") != std::string::npos);
|
||||||
|
|
||||||
|
// The read views are the only way in: the runtime role still cannot read the tables.
|
||||||
|
runtime = connect_as(env("EVO_PG_RUNTIME_USER"));
|
||||||
CHECK(!runtime->query("SELECT count(*) FROM evolution.life_reservations", {}, 5s));
|
CHECK(!runtime->query("SELECT count(*) FROM evolution.life_reservations", {}, 5s));
|
||||||
|
CHECK(!runtime->query("SELECT count(*) FROM evolution.session_windows", {}, 5s));
|
||||||
|
CHECK(server::admin::query_value("a=1&reason=x%20y+z&b=2", "reason") == "x y z" &&
|
||||||
|
!server::admin::query_value("a=1", "reason") &&
|
||||||
|
!server::admin::query_value("reason=abc", "reason", 2));
|
||||||
CHECK(server::admin::json_string("a\"b\\c\n\x01") == "\"a\\\"b\\\\c\\u000a\\u0001\"");
|
CHECK(server::admin::json_string("a\"b\\c\n\x01") == "\"a\\\"b\\\\c\\u000a\\u0001\"");
|
||||||
}
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|||||||
@@ -227,6 +227,14 @@ void upgrade_across_migration_and_barrier() {
|
|||||||
" -v migration_sha_59=$(s 0059_durable_mutation_queue.sql)"
|
" -v migration_sha_59=$(s 0059_durable_mutation_queue.sql)"
|
||||||
" -v migration_sha_60=$(s 0060_cellular_revamp_bundle.sql)"
|
" -v migration_sha_60=$(s 0060_cellular_revamp_bundle.sql)"
|
||||||
" -v migration_sha_61=$(s 0061_admin_read_views.sql)"
|
" -v migration_sha_61=$(s 0061_admin_read_views.sql)"
|
||||||
|
" -v migration_sha_62=$(s 0062_session_windows.sql)"
|
||||||
|
" -v migration_sha_63=$(s 0063_admin_commands.sql)"
|
||||||
|
" -v migration_sha_64=$(s 0064_account_admin.sql)"
|
||||||
|
" -v migration_sha_65=$(s 0065_admin_schedules.sql)"
|
||||||
|
" -v migration_sha_66=$(s 0066_tuning_revisions.sql)"
|
||||||
|
" -v migration_sha_67=$(s 0067_admin_take_and_cull.sql)"
|
||||||
|
" -v migration_sha_68=$(s 0068_larger_region_ticks.sql)"
|
||||||
|
" -v migration_sha_69=$(s 0069_admin_end_life.sql)"
|
||||||
" -v runtime_role=evo_runtime_test -f migrations/apply.sql"
|
" -v runtime_role=evo_runtime_test -f migrations/apply.sql"
|
||||||
" > /dev/null 2>&1") != 0);
|
" > /dev/null 2>&1") != 0);
|
||||||
CHECK(history(*owner_db) == "1,2,3,4,5,6,7");
|
CHECK(history(*owner_db) == "1,2,3,4,5,6,7");
|
||||||
@@ -242,9 +250,10 @@ void upgrade_across_migration_and_barrier() {
|
|||||||
CHECK(shell("PGDATABASE=" + database +
|
CHECK(shell("PGDATABASE=" + database +
|
||||||
" EVO_PG_RUNTIME_ROLE=evo_runtime_test bash \"$EVO_SOURCE_ROOT/"
|
" EVO_PG_RUNTIME_ROLE=evo_runtime_test bash \"$EVO_SOURCE_ROOT/"
|
||||||
"tools/migrate-postgres.sh\" > /dev/null") == 0);
|
"tools/migrate-postgres.sh\" > /dev/null") == 0);
|
||||||
CHECK(history(*owner_db) == "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,"
|
CHECK(history(*owner_db) ==
|
||||||
|
"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,"
|
||||||
"25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,"
|
"25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,"
|
||||||
"47,48,49,50,51,52,53,54,55,56,57,58,59,60,61");
|
"47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69");
|
||||||
CHECK(scalar(*owner_db, "SELECT (c.condeferrable AND c.condeferred AND "
|
CHECK(scalar(*owner_db, "SELECT (c.condeferrable AND c.condeferred AND "
|
||||||
"c.confrelid = 'evolution.region_commits'::regclass)::text "
|
"c.confrelid = 'evolution.region_commits'::regclass)::text "
|
||||||
"FROM pg_catalog.pg_constraint c WHERE c.conrelid = "
|
"FROM pg_catalog.pg_constraint c WHERE c.conrelid = "
|
||||||
|
|||||||
@@ -229,6 +229,63 @@ void accept_work_is_bounded_per_serve() {
|
|||||||
::close(fd);
|
::close(fd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ADR-0182: API request bodies only when asked for, complete (Content-Length, possibly over
|
||||||
|
// several reads), bounded (413) and nothing else: no chunking, no body on GET, no extra bytes.
|
||||||
|
void api_bodies_are_bounded_and_complete() {
|
||||||
|
using evo::server::OpsServer;
|
||||||
|
for (const std::size_t limit : {std::size_t{0}, std::size_t{64}}) {
|
||||||
|
auto made = OpsServer::listen("127.0.0.1:0");
|
||||||
|
CHECK(made);
|
||||||
|
auto& ops = **made;
|
||||||
|
std::atomic<bool> stop{false};
|
||||||
|
std::thread serving([&] {
|
||||||
|
while (!stop.load()) {
|
||||||
|
ops.serve_api(
|
||||||
|
[](const evo::server::ApiRequest& r) {
|
||||||
|
return evo::server::OpsResponse{200, std::string(r.method) + ":" +
|
||||||
|
std::string(r.body)};
|
||||||
|
},
|
||||||
|
limit);
|
||||||
|
std::this_thread::sleep_for(1ms);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const auto port = ops.port();
|
||||||
|
const auto post = [&](const std::string& headers, const std::string& body) {
|
||||||
|
std::string request = "POST /x HTTP/1.1\r\n";
|
||||||
|
request.append(headers).append("\r\n").append(body);
|
||||||
|
return http_exchange(port, request);
|
||||||
|
};
|
||||||
|
CHECK(post("", "").body == "POST:");
|
||||||
|
CHECK(post("Content-Length: 0\r\n", "").body == "POST:");
|
||||||
|
const auto hello = post("Content-Length: 5\r\n", "hello");
|
||||||
|
CHECK(limit == 0 ? hello.status == 400 : hello.status == 200 && hello.body == "POST:hello");
|
||||||
|
if (limit > 0) {
|
||||||
|
// A body arriving after the headers, in a later read.
|
||||||
|
const int fd = connect_local(port);
|
||||||
|
const std::string first = "POST /x HTTP/1.1\r\nContent-Length: 5\r\n\r\nhe";
|
||||||
|
CHECK(::send(fd, first.data(), first.size(), MSG_NOSIGNAL) ==
|
||||||
|
static_cast<ssize_t>(first.size()));
|
||||||
|
std::this_thread::sleep_for(50ms);
|
||||||
|
CHECK(::send(fd, "llo", 3, MSG_NOSIGNAL) == 3);
|
||||||
|
std::string raw;
|
||||||
|
char chunk[512];
|
||||||
|
for (ssize_t n = 0; (n = ::recv(fd, chunk, sizeof chunk, 0)) > 0;)
|
||||||
|
raw.append(chunk, static_cast<std::size_t>(n));
|
||||||
|
::close(fd);
|
||||||
|
CHECK(raw.starts_with("HTTP/1.1 200") && raw.ends_with("\r\n\r\nPOST:hello"));
|
||||||
|
}
|
||||||
|
CHECK(post("Content-Length: 65\r\n", std::string(65, 'a')).status ==
|
||||||
|
(limit == 0 ? 400 : 413));
|
||||||
|
CHECK(post("Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n").status == 400);
|
||||||
|
CHECK(post("Content-Length: 2\r\n", "hixx").status == 400);
|
||||||
|
CHECK(post("Content-Length: 2\r\nContent-Length: 2\r\n", "hi").status == 400);
|
||||||
|
CHECK(post("Content-Length: two\r\n", "hi").status == 400);
|
||||||
|
CHECK(http_exchange(port, "GET /x HTTP/1.1\r\nContent-Length: 2\r\n\r\nhi").status == 400);
|
||||||
|
stop = true;
|
||||||
|
serving.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// A real server under sustained connection churn keeps its lease and readiness.
|
// A real server under sustained connection churn keeps its lease and readiness.
|
||||||
void connection_pressure_keeps_authority() {
|
void connection_pressure_keeps_authority() {
|
||||||
const auto r = provision(54, 0x0D);
|
const auto r = provision(54, 0x0D);
|
||||||
@@ -266,6 +323,7 @@ void connection_pressure_keeps_authority() {
|
|||||||
|
|
||||||
void run_region_ops_tests() {
|
void run_region_ops_tests() {
|
||||||
accept_work_is_bounded_per_serve();
|
accept_work_is_bounded_per_serve();
|
||||||
|
api_bodies_are_bounded_and_complete();
|
||||||
connection_pressure_keeps_authority();
|
connection_pressure_keeps_authority();
|
||||||
probes_follow_authority_and_stay_bounded();
|
probes_follow_authority_and_stay_bounded();
|
||||||
unavailable_database_is_live_not_ready();
|
unavailable_database_is_live_not_ready();
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#include "evo/server/session_window.hpp"
|
#include "evo/server/session_window.hpp"
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
using evo::server::SessionWindow;
|
using evo::server::SessionWindow;
|
||||||
@@ -52,5 +53,32 @@ int main() {
|
|||||||
CHECK(close.has_value());
|
CHECK(close.has_value());
|
||||||
close->close();
|
close->close();
|
||||||
CHECK(!close->accepting(1'001));
|
CHECK(!close->accepting(1'001));
|
||||||
|
|
||||||
|
// ADR-0087 amendment: the database feed. No record keeps sessions closed.
|
||||||
|
using Feed = evo::server::SessionWindowFeed;
|
||||||
|
using Change = Feed::Change;
|
||||||
|
Feed feed;
|
||||||
|
CHECK(feed.observe(std::nullopt, now) == Change::none && !feed.accepting(now));
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-1", 1'200}, now) == Change::opened);
|
||||||
|
const auto& admitted = feed.window();
|
||||||
|
CHECK(feed.accepting(1'100) && admitted && admitted->deadline_seconds() == 1'200);
|
||||||
|
// Re-reading the same record changes nothing; a newer activation extends.
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-1", 1'200}, 1'150) == Change::none);
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-2", 5'000}, 1'150) == Change::opened);
|
||||||
|
CHECK(feed.accepting(1'250) && admitted && admitted->activation_id() == "adm-2");
|
||||||
|
// Its own deadline still closes it, and the same record cannot reopen it.
|
||||||
|
CHECK(!feed.accepting(5'000));
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-2", 5'000}, 4'000) == Change::none);
|
||||||
|
CHECK(!feed.accepting(4'001));
|
||||||
|
// A closing record closes; an expired or over-long newer one is refused and stays closed.
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-3", 9'000}, 6'000) == Change::opened);
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-4", std::nullopt}, 6'001) == Change::closed);
|
||||||
|
CHECK(!feed.accepting(6'002));
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-5", 6'000}, 6'010) == Change::refused);
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-6", 6'010 + 14'401}, 6'010) == Change::refused);
|
||||||
|
CHECK(!feed.accepting(6'011));
|
||||||
|
// A record that disappears (a restored database) closes the window.
|
||||||
|
CHECK(feed.observe(Feed::Record{"adm-7", 7'000}, 6'100) == Change::opened);
|
||||||
|
CHECK(feed.observe(std::nullopt, 6'101) == Change::closed && !feed.accepting(6'102));
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,8 @@
|
|||||||
# The cluster and its files are removed on exit unless --keep. Binaries come from
|
# The cluster and its files are removed on exit unless --keep. Binaries come from
|
||||||
# EVO_WORLD_CLONE_BIN / EVO_SERVER_BIN or PATH. Port: EVO_VERIFY_PORT (55499).
|
# EVO_WORLD_CLONE_BIN / EVO_SERVER_BIN or PATH. Port: EVO_VERIFY_PORT (55499).
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
# The private cluster has only its own roles: no admin role grants (ADR-0182) apply here.
|
||||||
|
unset EVO_PG_ADMIN_ROLE
|
||||||
usage() { echo "usage: $0 BUNDLE [--isolate WORLD [--source-world W]] [--keep]" >&2; exit 2; }
|
usage() { echo "usage: $0 BUNDLE [--isolate WORLD [--source-world W]] [--keep]" >&2; exit 2; }
|
||||||
[ $# -ge 1 ] || usage
|
[ $# -ge 1 ] || usage
|
||||||
bundle="$(realpath -- "$1")"; shift
|
bundle="$(realpath -- "$1")"; shift
|
||||||
|
|||||||
@@ -44,8 +44,9 @@ import re
|
|||||||
# restart after expiry, delayed application, extend/close races, clock movement,
|
# restart after expiry, delayed application, extend/close races, clock movement,
|
||||||
# synthetic inputs stopping while commits drain). The runtime contract and focused
|
# synthetic inputs stopping while commits drain). The runtime contract and focused
|
||||||
# expiry tests are now implemented in the M10 QUIC
|
# expiry tests are now implemented in the M10 QUIC
|
||||||
# bridge. The route remains constrained to the dev overlay and a committed absolute
|
# bridge. The route remains constrained to the dev overlay. Since the ADR-0087 amendment of
|
||||||
# window; delayed application fails closed in the server.
|
# 2026-10-27 the window lives in SQL (evolution.session_windows, set from the admin portal)
|
||||||
|
# and the region re-reads it; Git carries no window.
|
||||||
ROUTE_ENABLING_PERMITTED = True
|
ROUTE_ENABLING_PERMITTED = True
|
||||||
# Addresses the route may use: RFC 1918 plus internal ranges the maintainer has
|
# Addresses the route may use: RFC 1918 plus internal ranges the maintainer has
|
||||||
# explicitly approved in ADR-0087 (none yet; the cluster LAN 172.10.0.0/16 is not
|
# explicitly approved in ADR-0087 (none yet; the cluster LAN 172.10.0.0/16 is not
|
||||||
@@ -703,22 +704,11 @@ for overlay, docs in renders.items():
|
|||||||
check(env.get('REGION_SESSION_LISTEN') == listen,
|
check(env.get('REGION_SESSION_LISTEN') == listen,
|
||||||
f'{where}: REGION_SESSION_LISTEN must be {listen} (route {"on" if route_active else "off"})')
|
f'{where}: REGION_SESSION_LISTEN must be {listen} (route {"on" if route_active else "off"})')
|
||||||
check(text.count('--m10-listen') == 1 and '--m10-listen "$REGION_SESSION_LISTEN"' in text
|
check(text.count('--m10-listen') == 1 and '--m10-listen "$REGION_SESSION_LISTEN"' in text
|
||||||
and '--session-window "$REGION_SESSION_WINDOW"' in text,
|
and '--session-window-source db' in text and '--session-window ' not in text,
|
||||||
f'{where}: one M10 listener and absolute session window, addressed only by GitOps env')
|
f'{where}: one M10 listener whose session window is read from SQL (ADR-0087)')
|
||||||
# The server refuses a window ending more than 4 h after it starts
|
# The window lives in SQL; a Git-committed one would never be read.
|
||||||
# (SessionWindow::max_duration_seconds) and exits in a loop. The id carries
|
check('REGION_SESSION_WINDOW' not in env,
|
||||||
# its UTC activation (dev-YYYYMMDDTHHMMSS-...); the expiry must fall within
|
f'{where}: the session window lives in SQL, not in REGION_SESSION_WINDOW')
|
||||||
# 4 h of it. Checked here because the server sees it only at startup.
|
|
||||||
window = env.get('REGION_SESSION_WINDOW') or ''
|
|
||||||
if route_active and window:
|
|
||||||
import calendar, re, time
|
|
||||||
m = re.fullmatch(r'[0-9A-Za-z._-]*?(\d{8}T\d{6})Z?[0-9A-Za-z._-]*:(\d+)', window)
|
|
||||||
ok = False
|
|
||||||
if m:
|
|
||||||
start = calendar.timegm(time.strptime(m.group(1), '%Y%m%dT%H%M%S'))
|
|
||||||
ok = start < int(m.group(2)) <= start + 4 * 60 * 60
|
|
||||||
check(ok, f'{where}: REGION_SESSION_WINDOW must name its UTC activation and end '
|
|
||||||
'within 4 h of it (the server maximum)')
|
|
||||||
else:
|
else:
|
||||||
check('--m10-listen' not in text and '--synthetic-inputs' not in text,
|
check('--m10-listen' not in text and '--synthetic-inputs' not in text,
|
||||||
f'{where}: only evo-server may listen for sessions')
|
f'{where}: only evo-server may listen for sessions')
|
||||||
|
|||||||
@@ -132,14 +132,14 @@ CASES = [
|
|||||||
('non-RFC 1918 VIP without approval', lambda t: edit(t, ROUTE + 'service.yaml', '172.10.1.202',
|
('non-RFC 1918 VIP without approval', lambda t: edit(t, ROUTE + 'service.yaml', '172.10.1.202',
|
||||||
'172.11.1.210'), 'internal address'),
|
'172.11.1.210'), 'internal address'),
|
||||||
# Review M9.8f P1: inline/JSON patches and namespace changes, seen only when rendered.
|
# Review M9.8f P1: inline/JSON patches and namespace changes, seen only when rendered.
|
||||||
('session window longer than the server maximum', lambda t: inline_patch(
|
('session window committed to Git again', lambda t: inline_patch(
|
||||||
t, 'deploy/kubernetes/dev/kustomization.yaml',
|
t, 'deploy/kubernetes/dev/kustomization.yaml',
|
||||||
env_patch('REGION_SESSION_WINDOW', 'dev-20261008T111342-32432:1791477222')),
|
env_patch('REGION_SESSION_WINDOW', 'dev-20261008T111342-32432:1791477222')),
|
||||||
'end within 4 h of it'),
|
'the session window lives in SQL'),
|
||||||
('session window without an activation time', lambda t: inline_patch(
|
('fixed session window argument', lambda t: edit(
|
||||||
t, 'deploy/kubernetes/dev/kustomization.yaml',
|
t, 'deploy/kubernetes/region/base/deployment.yaml', '--session-window-source db',
|
||||||
env_patch('REGION_SESSION_WINDOW', 'dev-manual:1791477222')),
|
'--session-window "$REGION_SESSION_LISTEN"'),
|
||||||
'end within 4 h of it'),
|
'session window is read from SQL'),
|
||||||
('inline patch: synthetic inputs on', lambda t: inline_patch(
|
('inline patch: synthetic inputs on', lambda t: inline_patch(
|
||||||
t, 'deploy/kubernetes/dev/kustomization.yaml', env_patch('REGION_INPUTS', 'development-v1')),
|
t, 'deploy/kubernetes/dev/kustomization.yaml', env_patch('REGION_INPUTS', 'development-v1')),
|
||||||
'sessions must be dev only with the route'),
|
'sessions must be dev only with the route'),
|
||||||
@@ -155,7 +155,7 @@ CASES = [
|
|||||||
{'kind': 'Deployment', 'name': 'evo-region'}), 'container ports must be'),
|
{'kind': 'Deployment', 'name': 'evo-region'}), 'container ports must be'),
|
||||||
('JSON patch: second listener argument', lambda t: inline_patch(
|
('JSON patch: second listener argument', lambda t: inline_patch(
|
||||||
t, DEV, '- op: add\n path: /spec/template/spec/containers/0/args/-\n value: --m10-listen 0.0.0.0:7401\n',
|
t, DEV, '- op: add\n path: /spec/template/spec/containers/0/args/-\n value: --m10-listen 0.0.0.0:7401\n',
|
||||||
{'kind': 'Deployment', 'name': 'evo-region'}), 'one M10 listener and absolute session window'),
|
{'kind': 'Deployment', 'name': 'evo-region'}), 'one M10 listener whose session window is read from SQL'),
|
||||||
('namespace transformation', lambda t: edit(t, DEV, 'namespace: evolution-dev', 'namespace: evolution-stage'),
|
('namespace transformation', lambda t: edit(t, DEV, 'namespace: evolution-dev', 'namespace: evolution-stage'),
|
||||||
'expected evolution-dev'),
|
'expected evolution-dev'),
|
||||||
('inline quota patch in stage', lambda t: inline_patch(
|
('inline quota patch in stage', lambda t: inline_patch(
|
||||||
|
|||||||
@@ -74,7 +74,73 @@ awk '/^CREATE FUNCTION evolution\.(publish_cellular_checkpoint|publish_cellular_
|
|||||||
# Schema 58 widened the canonical action input; restore schema 36's validator.
|
# Schema 58 widened the canonical action input; restore schema 36's validator.
|
||||||
awk '/^CREATE OR REPLACE FUNCTION evolution\.valid_cellular_action_input\(/ {capture=1} capture {print} capture && /^END \$\$;/ {capture=0}' \
|
awk '/^CREATE OR REPLACE FUNCTION evolution\.valid_cellular_action_input\(/ {capture=1} capture {print} capture && /^END \$\$;/ {capture=0}' \
|
||||||
"$root/migrations/0036_cellular_v5_budding_bundle.sql" | sql > /dev/null
|
"$root/migrations/0036_cellular_v5_budding_bundle.sql" | sql > /dev/null
|
||||||
|
# Schema 68 raised the trace checker's tick counts; restore schema 43's (renamed _v45 by 46).
|
||||||
|
awk '/^CREATE OR REPLACE FUNCTION evolution\.cellular_births\(/ {capture=1; sub(/cellular_births\(/,"cellular_births_v45(")} capture {print} capture && /^END \$\$;/ {capture=0}' \
|
||||||
|
"$root/migrations/0043_cellular_v9_foraging_bundle.sql" | sql > /dev/null
|
||||||
|
# Schema 69 let the rejection record existing_life; restore schema 15's.
|
||||||
|
awk '/^CREATE FUNCTION evolution\.reject_primitive_life\(/ {capture=1; sub(/^CREATE FUNCTION/,"CREATE OR REPLACE FUNCTION")} capture {print} capture && /^END \$\$;/ {capture=0}' \
|
||||||
|
"$root/migrations/0015_life_reservations.sql" | sql > /dev/null
|
||||||
sql -v runtime_role="$EVO_PG_RUNTIME_ROLE" > /dev/null <<'SQL'
|
sql -v runtime_role="$EVO_PG_RUNTIME_ROLE" > /dev/null <<'SQL'
|
||||||
|
DROP FUNCTION evolution.admin_end_account_life_v1(evolution.u64,uuid,evolution.u64,text,text);
|
||||||
|
DROP TABLE evolution.admin_life_endings;
|
||||||
|
DROP FUNCTION evolution.admin_tuning_text_v1(evolution.u64,bigint);
|
||||||
|
DROP FUNCTION evolution.admin_tuning_revisions_v1(evolution.u64);
|
||||||
|
DROP FUNCTION evolution.load_tuning_revision_v1(evolution.u64,bigint);
|
||||||
|
DROP FUNCTION evolution.admin_set_tuning_v1(evolution.u64,text,bytea,bigint[],text,text);
|
||||||
|
DROP TABLE evolution.tuning_revisions;
|
||||||
|
ALTER TABLE evolution.admin_commands DROP CONSTRAINT admin_commands_kind_check;
|
||||||
|
ALTER TABLE evolution.admin_commands ADD CONSTRAINT admin_commands_kind_check CHECK (kind BETWEEN 1 AND 6);
|
||||||
|
DROP FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64,evolution.u64);
|
||||||
|
ALTER FUNCTION evolution.load_pending_admin_commands_v64(evolution.u64,evolution.u64) RENAME TO load_pending_admin_commands_v1;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64,evolution.u64) TO :"runtime_role";
|
||||||
|
DROP FUNCTION evolution.queue_due_schedules(evolution.u64,evolution.u64);
|
||||||
|
DROP FUNCTION evolution.admin_schedules_v1(evolution.u64,evolution.u64);
|
||||||
|
DROP FUNCTION evolution.admin_set_schedule_v1(evolution.u64,evolution.u64,bigint,integer,integer,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,integer,boolean,text,text);
|
||||||
|
DROP TABLE evolution.admin_schedules;
|
||||||
|
DROP SEQUENCE evolution.admin_schedule_ids;
|
||||||
|
ALTER TABLE evolution.admin_commands DROP COLUMN schedule_id;
|
||||||
|
DROP FUNCTION evolution.release_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64);
|
||||||
|
ALTER FUNCTION evolution.release_account_control_v63(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64) RENAME TO release_account_control;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.release_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64) TO :"runtime_role";
|
||||||
|
DROP FUNCTION evolution.renew_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,integer);
|
||||||
|
ALTER FUNCTION evolution.renew_account_control_v63(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,integer) RENAME TO renew_account_control;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.renew_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,integer) TO :"runtime_role";
|
||||||
|
DROP FUNCTION evolution.claim_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,integer);
|
||||||
|
ALTER FUNCTION evolution.claim_account_control_v63(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,integer) RENAME TO claim_account_control;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,integer) TO :"runtime_role";
|
||||||
|
DROP FUNCTION evolution.issue_account_grant(evolution.u64,text,text);
|
||||||
|
ALTER FUNCTION evolution.issue_account_grant_v63(evolution.u64,text,text) RENAME TO issue_account_grant;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.issue_account_grant(evolution.u64,text,text) TO :"runtime_role";
|
||||||
|
DROP FUNCTION evolution.admin_account_bans_v1(uuid);
|
||||||
|
DROP FUNCTION evolution.admin_account_status_v1(evolution.u64);
|
||||||
|
DROP FUNCTION evolution.admin_logout_account_v1(evolution.u64,uuid);
|
||||||
|
DROP FUNCTION evolution.admin_set_account_ban_v1(evolution.u64,uuid,boolean,text,text);
|
||||||
|
DROP FUNCTION evolution.revoke_account_by_id(evolution.u64,uuid);
|
||||||
|
DROP FUNCTION evolution.account_banned(uuid);
|
||||||
|
DROP TABLE evolution.session_intervals, evolution.account_bans;
|
||||||
|
DROP FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,bytea,bytea);
|
||||||
|
ALTER FUNCTION evolution.publish_cellular_mutation_checkpoint_v62(bytea,bytea,bytea,bytea,bytea,bytea) RENAME TO publish_cellular_mutation_checkpoint;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,bytea,bytea) TO :"runtime_role";
|
||||||
|
DROP FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea);
|
||||||
|
ALTER FUNCTION evolution.publish_cellular_checkpoint_v62(bytea,bytea,bytea,bytea) RENAME TO publish_cellular_checkpoint;
|
||||||
|
GRANT EXECUTE ON FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea) TO :"runtime_role";
|
||||||
|
DROP FUNCTION evolution.bind_cellular_admin_commands(bytea,bytea);
|
||||||
|
DROP FUNCTION evolution.admin_commands_v1(evolution.u64,evolution.u64);
|
||||||
|
DROP FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64,evolution.u64);
|
||||||
|
DROP FUNCTION evolution.admin_enqueue_command_v1(evolution.u64,evolution.u64,integer,integer,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,text,text);
|
||||||
|
DROP TABLE evolution.admin_command_applications, evolution.admin_commands;
|
||||||
|
DROP FUNCTION evolution.cellular_mutation_selections(bytea,bytea);
|
||||||
|
ALTER FUNCTION evolution.cellular_mutation_selections_v62(bytea,bytea) RENAME TO cellular_mutation_selections;
|
||||||
|
DROP FUNCTION evolution.cellular_births(bytea,bytea);
|
||||||
|
ALTER FUNCTION evolution.cellular_births_v62(bytea,bytea) RENAME TO cellular_births;
|
||||||
|
DROP FUNCTION evolution.cellular_trace_normal(bytea,bytea);
|
||||||
|
DROP FUNCTION evolution.cellular_trace_admin(bytea,bytea);
|
||||||
|
DROP FUNCTION evolution.cellular_trace_without_admin(bytea);
|
||||||
|
DROP FUNCTION evolution.le_bytes(numeric,integer);
|
||||||
|
DROP FUNCTION evolution.admin_session_windows_v1(evolution.u64,evolution.u64);
|
||||||
|
DROP FUNCTION evolution.admin_set_session_window_v1(evolution.u64,evolution.u64,integer,text,text);
|
||||||
|
DROP FUNCTION evolution.load_session_window_v1(evolution.u64,evolution.u64);
|
||||||
|
DROP TABLE evolution.session_windows;
|
||||||
DROP FUNCTION evolution.admin_regions_v1(evolution.u64);
|
DROP FUNCTION evolution.admin_regions_v1(evolution.u64);
|
||||||
DROP FUNCTION evolution.admin_account_lives_v1(evolution.u64,uuid);
|
DROP FUNCTION evolution.admin_account_lives_v1(evolution.u64,uuid);
|
||||||
DROP FUNCTION evolution.admin_accounts_v1(evolution.u64);
|
DROP FUNCTION evolution.admin_accounts_v1(evolution.u64);
|
||||||
|
|||||||
@@ -71,6 +71,10 @@ fi
|
|||||||
psql -X -v ON_ERROR_STOP=1 -c 'CREATE ROLE evo_runtime_test NOLOGIN' \
|
psql -X -v ON_ERROR_STOP=1 -c 'CREATE ROLE evo_runtime_test NOLOGIN' \
|
||||||
-c 'CREATE ROLE evo_runtime_login LOGIN IN ROLE evo_runtime_test'
|
-c 'CREATE ROLE evo_runtime_login LOGIN IN ROLE evo_runtime_test'
|
||||||
export EVO_PG_RUNTIME_ROLE=evo_runtime_test EVO_PG_RUNTIME_USER=evo_runtime_login
|
export EVO_PG_RUNTIME_ROLE=evo_runtime_test EVO_PG_RUNTIME_USER=evo_runtime_login
|
||||||
|
# ADR-0182: the admin API's own group role and login, outside the runtime group.
|
||||||
|
psql -X -v ON_ERROR_STOP=1 -c 'CREATE ROLE evo_admin_test NOLOGIN' \
|
||||||
|
-c 'CREATE ROLE evo_admin_login LOGIN IN ROLE evo_admin_test'
|
||||||
|
export EVO_PG_ADMIN_ROLE=evo_admin_test EVO_PG_ADMIN_USER=evo_admin_login
|
||||||
phase migrate
|
phase migrate
|
||||||
bash "$root/tools/migrate-postgres.sh"
|
bash "$root/tools/migrate-postgres.sh"
|
||||||
bash "$root/tools/migrate-postgres.sh" # exact supported upgrade/restart is a no-op
|
bash "$root/tools/migrate-postgres.sh" # exact supported upgrade/restart is a no-op
|
||||||
@@ -168,7 +172,7 @@ PGDATABASE=upgrade_path psql -X -v ON_ERROR_STOP=1 -1 -v "migration_sha=$v1_sha"
|
|||||||
-f "$root/migrations/0001_region_bootstrap.sql" > /dev/null
|
-f "$root/migrations/0001_region_bootstrap.sql" > /dev/null
|
||||||
test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1
|
test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1
|
||||||
PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh"
|
PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh"
|
||||||
test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61
|
test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69
|
||||||
# v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2.
|
# v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2.
|
||||||
v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")"
|
v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")"
|
||||||
v2_sha="${v2_sha%% *}"
|
v2_sha="${v2_sha%% *}"
|
||||||
@@ -189,7 +193,7 @@ PGDATABASE=v3_commits psql -X -v ON_ERROR_STOP=1 \
|
|||||||
-c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \
|
-c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \
|
||||||
-c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null
|
-c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null
|
||||||
PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh"
|
PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh"
|
||||||
test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 61:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61
|
test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 69:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69
|
||||||
test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1
|
test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1
|
||||||
# Review P1: a v4 database holding a published (possibly terminal) checkpoint has
|
# Review P1: a v4 database holding a published (possibly terminal) checkpoint has
|
||||||
# no durable decisions for it. The v5 upgrade must refuse before changing anything.
|
# no durable decisions for it. The v5 upgrade must refuse before changing anything.
|
||||||
@@ -243,7 +247,7 @@ PGDATABASE=v6_populated psql -X -v ON_ERROR_STOP=1 \
|
|||||||
-c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \
|
-c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \
|
||||||
-c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null
|
-c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null
|
||||||
PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh"
|
PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh"
|
||||||
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61
|
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69
|
||||||
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1
|
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1
|
||||||
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick
|
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick
|
||||||
phase permission-audit
|
phase permission-audit
|
||||||
@@ -301,9 +305,9 @@ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.load_world_cellular_m
|
|||||||
expect_audit_failure 'GRANT EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) TO evo_runtime_test' 'REVOKE EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) FROM evo_runtime_test'
|
expect_audit_failure 'GRANT EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) TO evo_runtime_test' 'REVOKE EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) FROM evo_runtime_test'
|
||||||
phase checksum-drift
|
phase checksum-drift
|
||||||
# Unknown future versions and checksum drift must not be repaired silently.
|
# Unknown future versions and checksum drift must not be repaired silently.
|
||||||
psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=62 WHERE version=61'
|
psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=70 WHERE version=69'
|
||||||
if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi
|
if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi
|
||||||
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=61 WHERE version=62"
|
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=69 WHERE version=70"
|
||||||
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14"
|
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14"
|
||||||
if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi
|
if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi
|
||||||
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13"
|
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13"
|
||||||
|
|||||||
@@ -3,6 +3,10 @@ set -euo pipefail
|
|||||||
root="$(cd "$(dirname "$0")/.." && pwd)"
|
root="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
# Operator-created NOLOGIN group role granted to the region runtime login (ADR-0060).
|
# Operator-created NOLOGIN group role granted to the region runtime login (ADR-0060).
|
||||||
runtime_role="${EVO_PG_RUNTIME_ROLE:?set EVO_PG_RUNTIME_ROLE to the runtime group role}"
|
runtime_role="${EVO_PG_RUNTIME_ROLE:?set EVO_PG_RUNTIME_ROLE to the runtime group role}"
|
||||||
|
# Optional operator-created NOLOGIN group role of the admin API's login (ADR-0182): when set,
|
||||||
|
# every run grants it exactly the admin functions and audits it.
|
||||||
|
admin=()
|
||||||
|
if [ -n "${EVO_PG_ADMIN_ROLE:-}" ]; then admin=(--set="admin_role=$EVO_PG_ADMIN_ROLE"); fi
|
||||||
if [ -n "${EVO_PGPASS_SOURCE:-}" ]; then
|
if [ -n "${EVO_PGPASS_SOURCE:-}" ]; then
|
||||||
umask 077
|
umask 077
|
||||||
export PGPASSFILE
|
export PGPASSFILE
|
||||||
@@ -134,6 +138,22 @@ digest_60="$(sha256sum "$root/migrations/0060_cellular_revamp_bundle.sql")"
|
|||||||
digest_60="${digest_60%% *}"
|
digest_60="${digest_60%% *}"
|
||||||
digest_61="$(sha256sum "$root/migrations/0061_admin_read_views.sql")"
|
digest_61="$(sha256sum "$root/migrations/0061_admin_read_views.sql")"
|
||||||
digest_61="${digest_61%% *}"
|
digest_61="${digest_61%% *}"
|
||||||
|
digest_62="$(sha256sum "$root/migrations/0062_session_windows.sql")"
|
||||||
|
digest_62="${digest_62%% *}"
|
||||||
|
digest_63="$(sha256sum "$root/migrations/0063_admin_commands.sql")"
|
||||||
|
digest_63="${digest_63%% *}"
|
||||||
|
digest_64="$(sha256sum "$root/migrations/0064_account_admin.sql")"
|
||||||
|
digest_64="${digest_64%% *}"
|
||||||
|
digest_65="$(sha256sum "$root/migrations/0065_admin_schedules.sql")"
|
||||||
|
digest_65="${digest_65%% *}"
|
||||||
|
digest_66="$(sha256sum "$root/migrations/0066_tuning_revisions.sql")"
|
||||||
|
digest_66="${digest_66%% *}"
|
||||||
|
digest_67="$(sha256sum "$root/migrations/0067_admin_take_and_cull.sql")"
|
||||||
|
digest_67="${digest_67%% *}"
|
||||||
|
digest_68="$(sha256sum "$root/migrations/0068_larger_region_ticks.sql")"
|
||||||
|
digest_68="${digest_68%% *}"
|
||||||
|
digest_69="$(sha256sum "$root/migrations/0069_admin_end_life.sql")"
|
||||||
|
digest_69="${digest_69%% *}"
|
||||||
psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \
|
psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \
|
||||||
--set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \
|
--set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \
|
||||||
--set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \
|
--set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \
|
||||||
@@ -183,5 +203,8 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \
|
|||||||
--set="migration_sha_55=$digest_55" --set="migration_sha_56=$digest_56" \
|
--set="migration_sha_55=$digest_55" --set="migration_sha_56=$digest_56" \
|
||||||
--set="migration_sha_57=$digest_57" --set="migration_sha_58=$digest_58" --set="migration_sha_59=$digest_59" \
|
--set="migration_sha_57=$digest_57" --set="migration_sha_58=$digest_58" --set="migration_sha_59=$digest_59" \
|
||||||
--set="migration_sha_60=$digest_60" --set="migration_sha_61=$digest_61" \
|
--set="migration_sha_60=$digest_60" --set="migration_sha_61=$digest_61" \
|
||||||
|
--set="migration_sha_62=$digest_62" --set="migration_sha_63=$digest_63" \
|
||||||
|
--set="migration_sha_64=$digest_64" --set="migration_sha_65=$digest_65" \
|
||||||
|
--set="migration_sha_66=$digest_66" --set="migration_sha_67=$digest_67" --set="migration_sha_68=$digest_68" --set="migration_sha_69=$digest_69" "${admin[@]}" \
|
||||||
--set="runtime_role=$runtime_role" \
|
--set="runtime_role=$runtime_role" \
|
||||||
--file="$root/migrations/apply.sql"
|
--file="$root/migrations/apply.sql"
|
||||||
|
|||||||
@@ -90,16 +90,14 @@ restore() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
world="$(env_of REGION_WORLD)" region="$(env_of REGION_ID)" frame="$(env_of REGION_FRAME)"
|
world="$(env_of REGION_WORLD)" region="$(env_of REGION_ID)" frame="$(env_of REGION_FRAME)"
|
||||||
window="$(env_of REGION_SESSION_WINDOW)"
|
|
||||||
[ -n "$world" ] && [ -n "$region" ] && [ -n "$frame" ] || fail "cannot read the region identity"
|
[ -n "$world" ] && [ -n "$region" ] && [ -n "$frame" ] || fail "cannot read the region identity"
|
||||||
[ -z "$(env_of REGION_INPUTS)" ] || fail "REGION_INPUTS is already set: another drill may be running"
|
[ -z "$(env_of REGION_INPUTS)" ] || fail "REGION_INPUTS is already set: another drill may be running"
|
||||||
# The drill must end before the session window closes.
|
# The drill must end before the session window closes: the window is in SQL (ADR-0087
|
||||||
|
# amendment), so open it in the admin portal for at least the drill's duration first.
|
||||||
count=$(echo "$steps" | tr ',' '\n' | wc -l)
|
count=$(echo "$steps" | tr ',' '\n' | wc -l)
|
||||||
most=$(echo "$steps" | tr ',' '\n' | sort -n | tail -1)
|
most=$(echo "$steps" | tr ',' '\n' | sort -n | tail -1)
|
||||||
needed=$(( count * (hold + warmup + most / 10 + 5) + 600 ))
|
needed=$(( count * (hold + warmup + most / 10 + 5) + 600 ))
|
||||||
expiry="${window##*:}"
|
say "the drill needs about ${needed} s of open session window (admin portal)"
|
||||||
[ -n "$expiry" ] && [ "$expiry" -gt $(( $(date -u +%s) + needed )) ] 2> /dev/null ||
|
|
||||||
fail "the session window ($window) closes within the drill's ${needed} s: renew it first"
|
|
||||||
size=$(wc -c < "$tokens/load-grants.bin")
|
size=$(wc -c < "$tokens/load-grants.bin")
|
||||||
[ $(( size / 160 )) -ge $(( most * per_bot )) ] ||
|
[ $(( size / 160 )) -ge $(( most * per_bot )) ] ||
|
||||||
fail "load-grants.bin holds $(( size / 160 )) grants; $most bots x $per_bot need $(( most * per_bot ))"
|
fail "load-grants.bin holds $(( size / 160 )) grants; $most bots x $per_bot need $(( most * per_bot ))"
|
||||||
|
|||||||
Reference in New Issue
Block a user