#include "evo/persistence/region_lease_store.hpp" #include #include #include #include #include #include namespace evo::persistence { namespace { using std::chrono::milliseconds; constexpr std::string_view digits = "0123456789abcdef"; LeaseStoreFailure classify(const PgFailure& f) { const std::string_view state(f.sqlstate.data(), 5); auto kind = LeaseStoreError::store; if (f.kind == PgError::unknown) kind = LeaseStoreError::unknown; else if (f.kind == PgError::config || f.kind == PgError::bounds || state == "22023") kind = LeaseStoreError::invalid; else if (state == "EVL01") kind = LeaseStoreError::busy; else if (state == "EVL02") kind = LeaseStoreError::fenced; else if (state == "EVL03") kind = LeaseStoreError::head_mismatch; else if (state == "EVL04") kind = LeaseStoreError::not_provisioned; else if (state == "EVL05") kind = LeaseStoreError::exhausted; else if (state == "EVL06") kind = LeaseStoreError::unsupported; else if (state == "EVL07") kind = LeaseStoreError::commit_conflict; else if (state == "EVL08") kind = LeaseStoreError::outcome_final; else if (state == "EVL09") kind = LeaseStoreError::immutable; return {kind, f}; } LeaseStoreFailure malformed(bool mutation) { // A mutation whose reply cannot be parsed may still have committed. return {mutation ? LeaseStoreError::unknown : LeaseStoreError::store, {}}; } std::string hex(std::span bytes) { std::string out; out.reserve(bytes.size() * 2); for (const auto b : bytes) { out.push_back(digits[static_cast(b >> 4U)]); out.push_back(digits[static_cast(b & 0x0FU)]); } return out; } std::optional nibble(char c) { const auto at = digits.find(c); if (at == std::string_view::npos) return std::nullopt; return static_cast(at); } template std::optional> unhex(std::string_view s) { if (s.size() != N * 2) return std::nullopt; std::array out{}; for (std::size_t i = 0; i < N; ++i) { const auto high = nibble(s[i * 2]); const auto low = nibble(s[(i * 2) + 1]); if (!high || !low) return std::nullopt; out[i] = static_cast((*high << 4U) | *low); } return out; } std::optional> unhex_bytes(std::string_view s) { if (s.size() % 2 != 0) return std::nullopt; std::vector out(s.size() / 2); for (std::size_t i = 0; i < out.size(); ++i) { const auto high = nibble(s[i * 2]); const auto low = nibble(s[(i * 2) + 1]); if (!high || !low) return std::nullopt; out[i] = static_cast((*high << 4U) | *low); } return out; } std::string uuid_text(const Uuid& id) { const auto h = hex(id); return h.substr(0, 8) + '-' + h.substr(8, 4) + '-' + h.substr(12, 4) + '-' + h.substr(16, 4) + '-' + h.substr(20); } std::optional parse_uuid(const std::optional& s) { if (!s || s->size() != 36) return std::nullopt; std::string compact; for (std::size_t i = 0; i < s->size(); ++i) { const bool dash = i == 8 || i == 13 || i == 18 || i == 23; if (dash != ((*s)[i] == '-')) return std::nullopt; if (!dash) compact.push_back((*s)[i]); } return unhex<16>(compact); } template std::optional parse_integer(const std::optional& s) { if (!s || s->empty() || s->size() > 20 || s->front() == '-' || s->front() == '+') return std::nullopt; T value{}; const auto* end = s->data() + s->size(); const auto [at, error] = std::from_chars(s->data(), end, value); if (error != std::errc{} || at != end) return std::nullopt; return value; } std::string bytea(std::span b) { return "\\x" + hex(b); } // Head columns: frame, sequence, commit, digest hex, end tick (+ optional extras). std::optional parse_head(const PgRows& rows, std::size_t columns = 5) { if (rows.size() != 1 || rows[0].size() != columns) return std::nullopt; const auto& r = rows[0]; const auto frame = parse_integer(r[0]); const auto sequence = parse_integer(r[1]); const auto commit = parse_uuid(r[2]); const auto& digest_text = r[3]; const auto digest = digest_text ? unhex<32>(*digest_text) : std::nullopt; const auto tick = parse_integer(r[4]); if (!frame || !sequence || !commit || !digest || !tick) return std::nullopt; return RegionHead{*frame, *sequence, *commit, *digest, *tick}; } } // namespace std::expected acquire_region_lease(Postgres& db, RegionKey key, const Sha256Digest& build, milliseconds duration, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region), std::to_string(duration.count()), bytea(build)}; auto rows = db.query("SELECT * FROM evolution.acquire_region_lease($1::evolution.u64, " "$2::evolution.u64, $3::integer, $4::bytea)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; if (rows->size() != 1 || (*rows)[0].size() != 4) return std::unexpected{malformed(true)}; const auto& r = (*rows)[0]; const auto holder = parse_uuid(r[0]); const auto epoch = parse_integer(r[1]); const auto frame = parse_integer(r[2]); const auto granted = parse_integer(r[3]); if (!holder || !epoch || !frame || !granted || *epoch == 0) return std::unexpected{malformed(true)}; return LeaseGrant{*holder, *epoch, *frame, milliseconds{*granted}}; } std::expected renew_region_lease(Postgres& db, RegionKey key, const LeaseGrant& lease, milliseconds duration, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region), uuid_text(lease.holder), std::to_string(lease.epoch), std::to_string(duration.count())}; auto rows = db.query("SELECT evolution.renew_region_lease($1::evolution.u64, " "$2::evolution.u64, $3::uuid, $4::evolution.u64, $5::integer)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; const auto granted = rows->size() == 1 && (*rows)[0].size() == 1 ? parse_integer((*rows)[0][0]) : std::nullopt; if (!granted) return std::unexpected{malformed(true)}; return milliseconds{*granted}; } std::expected release_region_lease(Postgres& db, RegionKey key, const LeaseGrant& lease, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region), uuid_text(lease.holder), std::to_string(lease.epoch)}; auto rows = db.query("SELECT evolution.release_region_lease($1::evolution.u64, " "$2::evolution.u64, $3::uuid, $4::evolution.u64)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; if (rows->size() != 1) return std::unexpected{malformed(true)}; return {}; } std::expected load_region_head(Postgres& db, RegionKey key, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region)}; auto rows = db.query("SELECT * FROM evolution.load_region_head($1::evolution.u64, $2::evolution.u64)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; auto head = parse_head(*rows); if (!head) return std::unexpected{malformed(false)}; return *head; } std::expected load_region_checkpoint(Postgres& db, RegionKey key, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region)}; auto rows = db.query( "SELECT * FROM evolution.load_region_checkpoint($1::evolution.u64, $2::evolution.u64)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; auto head = parse_head(*rows, 6); const auto& manifest_text = head ? (*rows)[0][5] : std::optional{}; auto manifest = manifest_text ? unhex_bytes(*manifest_text) : std::nullopt; if (!head || !manifest) return std::unexpected{malformed(false)}; return CommittedCheckpoint{*head, std::move(*manifest)}; } std::expected load_region_commit(Postgres& db, RegionKey key, std::uint64_t sequence, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region), std::to_string(sequence)}; auto rows = db.query("SELECT * FROM evolution.load_region_commit($1::evolution.u64, " "$2::evolution.u64, $3::evolution.u64)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; auto head = parse_head(*rows, 6); if (!head || rows->size() != 1) return std::unexpected{malformed(false)}; const auto& manifest_text = (*rows)[0][5]; auto manifest = manifest_text ? unhex_bytes(*manifest_text) : std::nullopt; if (!manifest) return std::unexpected{malformed(false)}; return CommittedCheckpoint{*head, std::move(*manifest)}; } std::expected publish_region_checkpoint(Postgres& db, std::span manifest, std::span decisions, milliseconds timeout) { const std::array p{bytea(manifest), bytea(decisions)}; auto rows = db.query("SELECT * FROM evolution.publish_region_checkpoint($1::bytea, $2::bytea)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; auto head = parse_head(*rows); if (!head) return std::unexpected{malformed(true)}; return *head; } std::expected resolve_region_commit(Postgres& db, RegionKey key, const Uuid& commit, std::span manifest, std::span decisions, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region), uuid_text(commit), bytea(manifest), bytea(decisions)}; auto rows = db.query("SELECT * FROM evolution.resolve_region_commit($1::evolution.u64, " "$2::evolution.u64, $3::uuid, $4::bytea, $5::bytea)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; if (rows->size() != 1 || (*rows)[0].size() != 6) return std::unexpected{malformed(false)}; const auto& status_text = (*rows)[0][0]; if (!status_text) return std::unexpected{malformed(false)}; const auto status = *status_text; if (status == "absent") return ResolvedCommit{Resolution::absent, {}}; if (status == "conflict") return ResolvedCommit{Resolution::conflict, {}}; const PgRows receipt{ std::vector>((*rows)[0].begin() + 1, (*rows)[0].end())}; auto head = status == "committed" ? parse_head(receipt) : std::nullopt; if (!head) return std::unexpected{malformed(false)}; return ResolvedCommit{Resolution::committed, *head}; } namespace { std::expected, LeaseStoreFailure> decisions_from(const PgRows& rows) { std::vector out; out.reserve(rows.size()); for (const auto& r : rows) { if (r.size() != 5) return std::unexpected{malformed(false)}; const auto sequence = parse_integer(r[0]); const auto tick = parse_integer(r[1]); const auto actor = parse_integer(r[2]); const auto outcome = parse_integer(r[3]); const auto organism = parse_integer(r[4]); if (!sequence || !tick || !actor || !outcome || !organism || *actor > 1 || *outcome != 1) return std::unexpected{malformed(false)}; out.push_back({*sequence, {*tick, static_cast(*actor), Outcome::death, *organism}}); } return out; } } // namespace std::expected, LeaseStoreFailure> load_region_decisions(Postgres& db, RegionKey key, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region)}; auto rows = db.query( "SELECT * FROM evolution.load_region_decisions($1::evolution.u64, $2::evolution.u64)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; return decisions_from(*rows); } std::expected, LeaseStoreFailure> pending_region_outbox(Postgres& db, RegionKey key, std::uint32_t limit, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region), std::to_string(limit)}; auto rows = db.query("SELECT * FROM evolution.pending_region_outbox($1::evolution.u64, " "$2::evolution.u64, $3::integer)", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; return decisions_from(*rows); } std::expected acknowledge_region_outbox(Postgres& db, RegionKey key, const BatchDecision& d, milliseconds timeout) { const std::array p{std::to_string(key.world), std::to_string(key.region), std::to_string(static_cast(d.outcome)), std::to_string(static_cast(d.actor)), std::to_string(d.tick)}; auto rows = db.query("SELECT evolution.acknowledge_region_outbox($1::evolution.u64, " "$2::evolution.u64, $3::integer, $4::integer, $5::evolution.u64)::text", p, timeout); if (!rows) return std::unexpected{classify(rows.error())}; if (rows->size() != 1 || (*rows)[0].size() != 1) return std::unexpected{malformed(true)}; const auto& marked = (*rows)[0][0]; if (!marked) return std::unexpected{malformed(true)}; return *marked == "true"; } } // namespace evo::persistence