Phase 10: central realm Registry, Host publishing lifecycle, deployment

crates/coa-registry-proto (protocol 1: types, limits, signed-request canonicalisation, test vectors),
services/coa-registry (axum + PostgreSQL, migrations, rate limits, Dockerfile, deploy files),
services/coa-registry-e2e (Host lifecycle against the real service, live VPS gate),
coa-core realm_registry (identity keys, client, publishing loop on its own thread),
Settings -> Public listing card, docs REGISTRY_PROTOCOL.md and REGISTRY_DEPLOYMENT.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Sonnet 5.5 committed 2026-10-07 20:23:13 +05:00
1 parent ec40f146aa
commit 1267bcc41e
56 files changed
+10198 -13

No files matched your search

+380
View File
@@ -0,0 +1,380 @@
//! The HTTP surface of Registry protocol 1.
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use axum::body::Body;
use axum::extract::{ConnectInfo, Path, State};
use axum::http::{HeaderMap, Method, Request, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use coa_registry_proto::sign::{self, SignedHeaders};
use coa_registry_proto::*;
use std::result::Result;
use serde::Serialize;
use crate::limits::{Limiter, Rate};
use crate::listener::Peer;
use crate::store::{RealmRow, Store, StoreError};
pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
#[derive(Clone, Debug)]
pub struct ApiConfig {
pub online_ttl_secs: u64,
/// Behind a reverse proxy the client address is the last entry of `X-Forwarded-For` (the one the proxy itself appended).
pub trust_proxy: bool,
pub general: Rate,
pub register: Rate,
pub heartbeat: Rate,
}
impl Default for ApiConfig {
fn default() -> Self {
Self {
online_ttl_secs: ONLINE_TTL_SECS,
trust_proxy: false,
general: Rate::per_minute(120, 120.0),
register: Rate::per_hour(10, 10.0),
heartbeat: Rate { burst: 4.0, refill: 1.0 / 10.0 },
}
}
}
pub struct AppState<S: Store> {
pub store: S,
pub clock: Clock,
pub cfg: ApiConfig,
ip_general: Limiter<IpAddr>,
ip_register: Limiter<IpAddr>,
realm_heartbeat: Limiter<RealmId>,
started: Instant,
}
impl<S: Store> AppState<S> {
pub fn new(store: S, clock: Clock, cfg: ApiConfig) -> Self {
Self {
ip_general: Limiter::new(cfg.general, 100_000),
ip_register: Limiter::new(cfg.register, 100_000),
realm_heartbeat: Limiter::new(cfg.heartbeat, 100_000),
store,
clock,
cfg,
started: Instant::now(),
}
}
fn now(&self) -> i64 {
(self.clock)()
}
fn mono(&self) -> f64 {
self.started.elapsed().as_secs_f64()
}
}
pub struct ApiError {
status: StatusCode,
code: ErrorCode,
message: String,
}
impl ApiError {
fn new(status: StatusCode, code: ErrorCode, message: impl Into<String>) -> Self {
Self { status, code, message: message.into() }
}
fn malformed(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, ErrorCode::MalformedRequest, message)
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(self.status, Json(ErrorBody { error: ErrorDetail { code: self.code, message: self.message } })).into_response()
}
}
impl From<StoreError> for ApiError {
fn from(e: StoreError) -> Self {
match e {
StoreError::Unknown => Self::new(StatusCode::NOT_FOUND, ErrorCode::UnknownRealm, "this realm is not registered"),
StoreError::KeyMismatch => Self::new(StatusCode::FORBIDDEN, ErrorCode::RealmKeyMismatch, "this realm id belongs to another key"),
StoreError::Stale => Self::new(StatusCode::UNAUTHORIZED, ErrorCode::TimestampNotMonotonic, "the timestamp is not later than the last request of this realm"),
StoreError::NotPublished => Self::new(StatusCode::CONFLICT, ErrorCode::NotPublished, "the realm is not published; register it again"),
StoreError::Backend(m) => {
tracing::error!(error = %m, "storage failure");
Self::new(StatusCode::SERVICE_UNAVAILABLE, ErrorCode::Unavailable, "storage is unavailable")
}
}
}
}
pub fn router<S: Store>(state: Arc<AppState<S>>) -> Router {
Router::new()
.route("/registry/v1/healthz", get(healthz::<S>))
.route("/registry/v1/realms/register", post(register::<S>))
.route("/registry/v1/realms/{realm_id}/heartbeat", post(heartbeat::<S>))
.route("/registry/v1/realms/{realm_id}/unpublish", post(unpublish::<S>))
.route("/registry/v1/realms/{realm_id}", get(self_info::<S>))
.fallback(|| async { ApiError::new(StatusCode::NOT_FOUND, ErrorCode::MalformedRequest, "no such endpoint") })
.with_state(state)
}
fn client_ip(headers: &HeaderMap, peer: SocketAddr, trust_proxy: bool) -> IpAddr {
if trust_proxy {
if let Some(last) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()).and_then(|v| v.rsplit(',').next()) {
if let Ok(ip) = last.trim().parse::<IpAddr>() {
return ip;
}
}
}
peer.ip()
}
fn short(hash: &str) -> &str {
hash.get(..8).unwrap_or("")
}
fn log(endpoint: &str, realm: Option<&RealmId>, started: Instant, result: &Result<(StatusCode, String), ApiError>) {
let (status, caps) = match result {
Ok((s, c)) => (s.as_u16(), c.as_str()),
Err(e) => (e.status.as_u16(), ""),
};
let code = result.as_ref().err().map(|e| format!("{:?}", e.code)).unwrap_or_default();
tracing::info!(endpoint, realm = realm.map(|r| r.to_string()).unwrap_or_default(), status, error = %code, latency_ms = started.elapsed().as_millis() as u64, caps = caps, "request");
}
/// The IP-level admission every request passes before anything is parsed.
fn admit<S: Store>(st: &AppState<S>, ip: IpAddr, cost: f64) -> Result<(), ApiError> {
if st.ip_general.take(&ip, cost, st.mono()) {
Ok(())
} else {
Err(ApiError::new(StatusCode::TOO_MANY_REQUESTS, ErrorCode::RateLimited, "too many requests"))
}
}
async fn read_body(body: Body) -> Result<Vec<u8>, ApiError> {
match axum::body::to_bytes(body, MAX_REQUEST_BYTES).await {
Ok(b) => Ok(b.to_vec()),
Err(_) => Err(ApiError::new(StatusCode::PAYLOAD_TOO_LARGE, ErrorCode::RequestTooLarge, format!("a request is limited to {MAX_REQUEST_BYTES} bytes"))),
}
}
/// Headers, id and timestamp: everything that can be checked before the key is known.
fn prelude<S: Store>(st: &AppState<S>, headers: &HeaderMap, uri: &Uri, path_realm: Option<&str>) -> Result<(SignedHeaders, RealmId), ApiError> {
if uri.query().is_some() {
return Err(ApiError::malformed("a signed endpoint takes no query string"));
}
let h = SignedHeaders::parse(|n| headers.get(n).and_then(|v| v.to_str().ok())).map_err(|e| ApiError::malformed(e.to_string()))?;
if h.version != REGISTRY_PROTOCOL_VERSION {
return Err(ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::UnsupportedProtocolVersion, format!("protocol version {} is not supported; this Registry speaks {REGISTRY_PROTOCOL_VERSION}", h.version)));
}
let realm = match path_realm {
Some(text) => RealmId::parse(text).map_err(|_| ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::InvalidRealmId, "the realm id in the path is not a canonical UUIDv7"))?,
None => h.realm,
};
if h.realm != realm {
return Err(ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::InvalidRealmId, "the realm header and the realm id disagree"));
}
if (h.timestamp - st.now()).abs() > MAX_CLOCK_SKEW_SECS {
return Err(ApiError::new(StatusCode::UNAUTHORIZED, ErrorCode::BadTimestamp, format!("the timestamp is more than {MAX_CLOCK_SKEW_SECS} seconds from the Registry's clock")));
}
Ok((h, realm))
}
fn check_signature<S: Store>(st: &AppState<S>, ip: IpAddr, key: &[u8; 32], h: &SignedHeaders, method: &Method, path: &str, body: &[u8]) -> Result<(), ApiError> {
let ok = ed25519_dalek::VerifyingKey::from_bytes(key).map(|k| sign::verify_request(&k, h, method.as_str(), path, body)).unwrap_or(false);
if ok {
return Ok(());
}
// a forged request costs its sender more than an honest one
st.ip_general.take(&ip, 4.0, st.mono());
Err(ApiError::new(StatusCode::UNAUTHORIZED, ErrorCode::InvalidSignature, "the signature does not match"))
}
fn realm_admit<S: Store>(st: &AppState<S>, realm: &RealmId) -> Result<(), ApiError> {
if st.realm_heartbeat.take(realm, 1.0, st.mono()) {
Ok(())
} else {
Err(ApiError::new(StatusCode::TOO_MANY_REQUESTS, ErrorCode::RateLimited, "this realm sends requests too fast"))
}
}
async fn healthz<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Peer(peer)): ConnectInfo<Peer>, req: Request<Body>) -> Response {
let ip = client_ip(req.headers(), peer, st.cfg.trust_proxy);
if let Err(e) = admit(&st, ip, 1.0) {
return e.into_response();
}
if st.store.ping().await {
Json(Health { status: "ok".into(), protocol_version: REGISTRY_PROTOCOL_VERSION }).into_response()
} else {
(StatusCode::SERVICE_UNAVAILABLE, Json(Health { status: "degraded".into(), protocol_version: REGISTRY_PROTOCOL_VERSION })).into_response()
}
}
fn json<T: Serialize>(value: &T) -> (StatusCode, Response) {
(StatusCode::OK, Json(value).into_response())
}
async fn register<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Peer(peer)): ConnectInfo<Peer>, req: Request<Body>) -> Response {
let started = Instant::now();
let (parts, body) = req.into_parts();
let ip = client_ip(&parts.headers, peer, st.cfg.trust_proxy);
let mut realm_for_log = None;
let result: Result<(StatusCode, Response, String), ApiError> = async {
admit(&st, ip, 1.0)?;
if !st.ip_register.take(&ip, 1.0, st.mono()) {
return Err(ApiError::new(StatusCode::TOO_MANY_REQUESTS, ErrorCode::RateLimited, "too many registrations from this address"));
}
let bytes = read_body(body).await?;
let (h, realm) = prelude(&st, &parts.headers, &parts.uri, None)?;
realm_for_log = Some(realm);
let req: RegisterRequest = serde_json::from_slice(&bytes).map_err(|_| ApiError::malformed("the body is not a registration"))?;
if req.protocol_version != REGISTRY_PROTOCOL_VERSION {
return Err(ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::UnsupportedProtocolVersion, format!("protocol version {} is not supported", req.protocol_version)));
}
if req.realm_id != realm {
return Err(ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::InvalidRealmId, "the realm header and the body disagree"));
}
req.validate().map_err(|e| ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::InvalidMetadata, e.to_string()))?;
let public = sign::decode_public_key(&req.public_key).map_err(|e| ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::InvalidMetadata, e.to_string()))?;
check_signature(&st, ip, public.as_bytes(), &h, &parts.method, parts.uri.path(), &bytes)?;
let now = st.now();
let (row, created) = st.store.register(&req, *public.as_bytes(), now, h.timestamp).await?;
let resp = RegisterResponse {
protocol_version: REGISTRY_PROTOCOL_VERSION,
realm_id: realm,
created,
metadata_revision: row.metadata_revision,
published: row.published,
capabilities_hash: row.capabilities_hash.clone(),
server_time: now,
heartbeat_interval_secs: HEARTBEAT_INTERVAL_SECS,
online_ttl_secs: st.cfg.online_ttl_secs,
};
let (status, response) = json(&resp);
Ok((status, response, row.capabilities_hash))
}
.await;
finish("register", realm_for_log.as_ref(), started, result)
}
fn finish(endpoint: &str, realm: Option<&RealmId>, started: Instant, result: Result<(StatusCode, Response, String), ApiError>) -> Response {
match result {
Ok((status, response, caps)) => {
log(endpoint, realm, started, &Ok((status, short(&caps).to_string())));
response
}
Err(e) => {
log(endpoint, realm, started, &Err(ApiError { status: e.status, code: e.code, message: String::new() }));
e.into_response()
}
}
}
/// Shared by heartbeat, unpublish and the self endpoint: an existing realm, a valid signature, and (for writes) the per-realm rate.
async fn authenticate<S: Store>(st: &AppState<S>, ip: IpAddr, parts: &axum::http::request::Parts, path_realm: &str, bytes: &[u8], limited: bool) -> Result<(RealmId, i64), ApiError> {
let (h, realm) = prelude(st, &parts.headers, &parts.uri, Some(path_realm))?;
let key = st.store.key_of(&realm).await?.ok_or(StoreError::Unknown)?;
check_signature(st, ip, &key, &h, &parts.method, parts.uri.path(), bytes)?;
if limited {
realm_admit(st, &realm)?;
}
Ok((realm, h.timestamp))
}
async fn heartbeat<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Peer(peer)): ConnectInfo<Peer>, Path(realm_text): Path<String>, req: Request<Body>) -> Response {
let started = Instant::now();
let (parts, body) = req.into_parts();
let ip = client_ip(&parts.headers, peer, st.cfg.trust_proxy);
let mut realm_for_log = None;
let result: Result<(StatusCode, Response, String), ApiError> = async {
admit(&st, ip, 1.0)?;
let bytes = read_body(body).await?;
let (realm, ts) = authenticate(&st, ip, &parts, &realm_text, &bytes, true).await?;
realm_for_log = Some(realm);
let hb: HeartbeatRequest = serde_json::from_slice(&bytes).map_err(|_| ApiError::malformed("the body is not a heartbeat"))?;
if hb.protocol_version != REGISTRY_PROTOCOL_VERSION {
return Err(ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::UnsupportedProtocolVersion, format!("protocol version {} is not supported", hb.protocol_version)));
}
hb.validate().map_err(|e| ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::InvalidMetadata, e.to_string()))?;
let now = st.now();
let out = st.store.heartbeat(&realm, &hb, now, ts).await?;
let resp = HeartbeatResponse { protocol_version: REGISTRY_PROTOCOL_VERSION, metadata_revision: out.metadata_revision, published: true, capabilities_hash: out.capabilities_hash.clone(), resend_capabilities: out.resend_capabilities, server_time: now };
let (status, response) = json(&resp);
Ok((status, response, out.capabilities_hash))
}
.await;
finish("heartbeat", realm_for_log.as_ref(), started, result)
}
async fn unpublish<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Peer(peer)): ConnectInfo<Peer>, Path(realm_text): Path<String>, req: Request<Body>) -> Response {
let started = Instant::now();
let (parts, body) = req.into_parts();
let ip = client_ip(&parts.headers, peer, st.cfg.trust_proxy);
let mut realm_for_log = None;
let result: Result<(StatusCode, Response, String), ApiError> = async {
admit(&st, ip, 1.0)?;
let bytes = read_body(body).await?;
let (realm, ts) = authenticate(&st, ip, &parts, &realm_text, &bytes, true).await?;
realm_for_log = Some(realm);
let un: UnpublishRequest = serde_json::from_slice(&bytes).map_err(|_| ApiError::malformed("the body is not an unpublish request"))?;
if un.protocol_version != REGISTRY_PROTOCOL_VERSION {
return Err(ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::UnsupportedProtocolVersion, format!("protocol version {} is not supported", un.protocol_version)));
}
let now = st.now();
let revision = st.store.unpublish(&realm, now, ts).await?;
let (status, response) = json(&UnpublishResponse { protocol_version: REGISTRY_PROTOCOL_VERSION, published: false, metadata_revision: revision, server_time: now });
Ok((status, response, String::new()))
}
.await;
finish("unpublish", realm_for_log.as_ref(), started, result)
}
fn self_response(row: RealmRow, now: i64, ttl: u64) -> SelfResponse {
let online = row.published && now - row.last_seen_at <= ttl as i64;
SelfResponse {
protocol_version: REGISTRY_PROTOCOL_VERSION,
realm_id: row.realm_id,
public_key: sign::encode_public_key(&ed25519_dalek::VerifyingKey::from_bytes(&row.public_key).expect("a stored key was validated on the way in")),
display_name: row.display_name,
description: row.description,
language: row.language,
ruleset: row.ruleset,
manager_version: row.manager_version,
capabilities: row.capabilities,
capabilities_hash: row.capabilities_hash,
metadata_revision: row.metadata_revision,
published: row.published,
online,
created_at: row.created_at,
updated_at: row.updated_at,
last_seen_at: row.last_seen_at,
player_count: row.player_count,
player_capacity: row.player_capacity,
server_time: now,
}
}
/// The authenticated read of a realm's own record. It does not advance the replay counter (a read changes nothing), so it is accepted with any timestamp inside the window.
async fn self_info<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Peer(peer)): ConnectInfo<Peer>, Path(realm_text): Path<String>, req: Request<Body>) -> Response {
let started = Instant::now();
let (parts, body) = req.into_parts();
let ip = client_ip(&parts.headers, peer, st.cfg.trust_proxy);
let mut realm_for_log = None;
let result: Result<(StatusCode, Response, String), ApiError> = async {
admit(&st, ip, 1.0)?;
let bytes = read_body(body).await?;
if !bytes.is_empty() {
return Err(ApiError::malformed("a read has no body"));
}
let (realm, _) = authenticate(&st, ip, &parts, &realm_text, &bytes, false).await?;
realm_for_log = Some(realm);
let row = st.store.get(&realm).await?.ok_or(StoreError::Unknown)?;
let caps = row.capabilities_hash.clone();
let (status, response) = json(&self_response(row, st.now(), st.cfg.online_ttl_secs));
Ok((status, response, caps))
}
.await;
finish("self", realm_for_log.as_ref(), started, result)
}
+57
View File
@@ -0,0 +1,57 @@
//! Configuration from the environment. The database password is read from a file (a Docker secret), never from the environment or the image.
use std::env;
use crate::api::ApiConfig;
use crate::limits::Rate;
use crate::pg::PgConfig;
pub struct Config {
pub listen: String,
pub max_connections: usize,
pub request_timeout_secs: u64,
pub max_in_flight: usize,
pub api: ApiConfig,
pub pg: PgConfig,
}
fn var(name: &str, default: &str) -> String {
env::var(name).ok().filter(|v| !v.is_empty()).unwrap_or_else(|| default.to_string())
}
fn num<T: std::str::FromStr>(name: &str, default: T) -> Result<T, String> {
match env::var(name).ok().filter(|v| !v.is_empty()) {
Some(v) => v.parse().map_err(|_| format!("{name} is not a valid number")),
None => Ok(default),
}
}
impl Config {
pub fn from_env() -> Result<Self, String> {
let password_file = env::var("REGISTRY_DB_PASSWORD_FILE").map_err(|_| "REGISTRY_DB_PASSWORD_FILE is required".to_string())?;
let password = std::fs::read_to_string(&password_file).map_err(|e| format!("cannot read the database password file: {e}"))?.trim().to_string();
if password.is_empty() {
return Err("the database password file is empty".into());
}
let mut api = ApiConfig { trust_proxy: var("REGISTRY_TRUST_PROXY", "0") == "1", ..ApiConfig::default() };
api.online_ttl_secs = num("REGISTRY_ONLINE_TTL_SECS", api.online_ttl_secs)?;
api.register = Rate::per_hour(num("REGISTRY_REGISTER_BURST", 10)?, num("REGISTRY_REGISTER_PER_HOUR", 10.0)?);
api.general = Rate::per_minute(num("REGISTRY_GENERAL_BURST", 120)?, num("REGISTRY_GENERAL_PER_MINUTE", 120.0)?);
Ok(Self {
listen: var("REGISTRY_LISTEN", "0.0.0.0:8080"),
max_connections: num("REGISTRY_MAX_CONNECTIONS", 256)?,
request_timeout_secs: num("REGISTRY_REQUEST_TIMEOUT_SECS", 10)?,
max_in_flight: num("REGISTRY_MAX_IN_FLIGHT", 64)?,
api,
pg: PgConfig {
host: var("REGISTRY_DB_HOST", "postgres"),
port: num("REGISTRY_DB_PORT", 5432)?,
dbname: var("REGISTRY_DB_NAME", "coa"),
user: var("REGISTRY_DB_USER", "coa"),
password,
pool_size: num("REGISTRY_DB_POOL", 8)?,
statement_timeout_ms: num("REGISTRY_DB_STATEMENT_TIMEOUT_MS", 5000)?,
},
})
}
}
+11
View File
@@ -0,0 +1,11 @@
//! The CoA realm Registry (Phase 10): who publishes a realm and whether it is alive. Nothing else.
//!
//! The Registry never receives or stores database or RA credentials, game account passwords, character snapshots, canonical revisions,
//! inventories, session payloads or player character ids. Every mutating request is signed by the realm's own Ed25519 key.
pub mod api;
pub mod config;
pub mod limits;
pub mod listener;
pub mod pg;
pub mod store;
+88
View File
@@ -0,0 +1,88 @@
//! In-memory token buckets for abuse control. One process, one node: no shared store is needed.
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Mutex;
#[derive(Clone, Copy, Debug)]
pub struct Rate {
pub burst: f64,
/// Tokens per second.
pub refill: f64,
}
impl Rate {
pub fn per_minute(burst: u32, per_minute: f64) -> Self {
Self { burst: burst as f64, refill: per_minute / 60.0 }
}
pub fn per_hour(burst: u32, per_hour: f64) -> Self {
Self { burst: burst as f64, refill: per_hour / 3600.0 }
}
}
struct Bucket {
tokens: f64,
at: f64,
}
pub struct Limiter<K: Eq + Hash + Clone> {
rate: Rate,
max_keys: usize,
buckets: Mutex<HashMap<K, Bucket>>,
}
impl<K: Eq + Hash + Clone> Limiter<K> {
pub fn new(rate: Rate, max_keys: usize) -> Self {
Self { rate, max_keys, buckets: Mutex::new(HashMap::new()) }
}
/// Take `cost` tokens at time `now` (seconds, any monotonic origin). `false`: refused, nothing taken.
pub fn take(&self, key: &K, cost: f64, now: f64) -> bool {
let mut map = self.buckets.lock().unwrap();
if map.len() >= self.max_keys && !map.contains_key(key) {
// a full table is cleaned of buckets that have refilled completely (they carry no information)
let full = self.rate.burst;
let refill = self.rate.refill;
map.retain(|_, b| b.tokens + (now - b.at).max(0.0) * refill < full);
if map.len() >= self.max_keys {
return false;
}
}
let b = map.entry(key.clone()).or_insert(Bucket { tokens: self.rate.burst, at: now });
b.tokens = (b.tokens + (now - b.at).max(0.0) * self.rate.refill).min(self.rate.burst);
b.at = now;
if b.tokens >= cost {
b.tokens -= cost;
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bucket_allows_a_burst_then_refills() {
let l: Limiter<&str> = Limiter::new(Rate { burst: 3.0, refill: 0.5 }, 100);
assert!(l.take(&"a", 1.0, 0.0) && l.take(&"a", 1.0, 0.0) && l.take(&"a", 1.0, 0.0));
assert!(!l.take(&"a", 1.0, 0.0), "the burst is used up");
assert!(l.take(&"b", 1.0, 0.0), "another key is unaffected");
assert!(!l.take(&"a", 1.0, 1.0), "half a token is not enough");
assert!(l.take(&"a", 1.0, 2.0), "one token after two seconds");
assert!(l.take(&"a", 3.0, 1000.0), "a long pause refills to the burst");
assert!(!l.take(&"a", 1.0, 1000.0), "and never beyond it");
}
#[test]
fn the_table_is_bounded() {
let l: Limiter<u32> = Limiter::new(Rate { burst: 1.0, refill: 0.0 }, 4);
for k in 0..4 {
assert!(l.take(&k, 1.0, 0.0));
}
assert!(!l.take(&99, 1.0, 0.0), "a new key is refused when the table is full of live buckets");
assert!(!l.take(&0, 1.0, 0.0), "an existing one keeps its state");
}
}
+87
View File
@@ -0,0 +1,87 @@
//! A TCP listener that never has more than a fixed number of connections open: a new one waits in the kernel backlog until a slot is free.
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use pin_project_lite::pin_project;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
pub struct LimitedListener {
inner: TcpListener,
slots: Arc<Semaphore>,
}
impl LimitedListener {
pub fn new(inner: TcpListener, max_connections: usize) -> Self {
Self { inner, slots: Arc::new(Semaphore::new(max_connections)) }
}
}
pin_project! {
pub struct LimitedIo {
#[pin]
stream: TcpStream,
_slot: OwnedSemaphorePermit,
}
}
impl AsyncRead for LimitedIo {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
self.project().stream.poll_read(cx, buf)
}
}
impl AsyncWrite for LimitedIo {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
self.project().stream.poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().stream.poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().stream.poll_shutdown(cx)
}
}
impl axum::serve::Listener for LimitedListener {
type Io = LimitedIo;
type Addr = SocketAddr;
async fn accept(&mut self) -> (Self::Io, Self::Addr) {
loop {
let slot = self.slots.clone().acquire_owned().await.expect("the semaphore is never closed");
match self.inner.accept().await {
Ok((stream, addr)) => return (LimitedIo { stream, _slot: slot }, addr),
Err(e) => {
tracing::warn!(error = %e, "accept failed");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
}
fn local_addr(&self) -> io::Result<Self::Addr> {
self.inner.local_addr()
}
}
/// The address of the other end of a connection, whichever listener accepted it.
#[derive(Clone, Copy, Debug)]
pub struct Peer(pub SocketAddr);
impl axum::extract::connect_info::Connected<axum::serve::IncomingStream<'_, LimitedListener>> for Peer {
fn connect_info(stream: axum::serve::IncomingStream<'_, LimitedListener>) -> Self {
Peer(*stream.remote_addr())
}
}
impl axum::extract::connect_info::Connected<axum::serve::IncomingStream<'_, TcpListener>> for Peer {
fn connect_info(stream: axum::serve::IncomingStream<'_, TcpListener>) -> Self {
Peer(*stream.remote_addr())
}
}
+100
View File
@@ -0,0 +1,100 @@
use std::sync::Arc;
use std::time::Duration;
use coa_registry::api::{router, AppState, Clock};
use coa_registry::config::Config;
use coa_registry::listener::LimitedListener;
use coa_registry::pg::PgStore;
use tower::limit::ConcurrencyLimitLayer;
use tower_http::timeout::TimeoutLayer;
fn clock() -> Clock {
Arc::new(|| std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0))
}
async fn shutdown() {
let ctrl_c = tokio::signal::ctrl_c();
#[cfg(unix)]
{
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("a SIGTERM handler");
tokio::select! { _ = ctrl_c => {}, _ = term.recv() => {} }
}
#[cfg(not(unix))]
{
let _ = ctrl_c.await;
}
}
/// `coa-registry --healthcheck`: ask the local server for its health and exit 0 or 1 (the image has no curl).
fn healthcheck() -> i32 {
use std::io::{Read, Write};
let addr = std::env::var("REGISTRY_LISTEN").unwrap_or_else(|_| "0.0.0.0:8080".into());
let port = addr.rsplit(':').next().unwrap_or("8080");
let Ok(mut s) = std::net::TcpStream::connect(format!("127.0.0.1:{port}")) else { return 1 };
let _ = s.set_read_timeout(Some(Duration::from_secs(3)));
if s.write_all(b"GET /registry/v1/healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").is_err() {
return 1;
}
let mut out = String::new();
let _ = s.read_to_string(&mut out);
i32::from(!out.starts_with("HTTP/1.1 200"))
}
#[tokio::main]
async fn main() {
if std::env::args().nth(1).as_deref() == Some("--healthcheck") {
std::process::exit(healthcheck());
}
tracing_subscriber::fmt().json().with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())).with_current_span(false).init();
let cfg = match Config::from_env() {
Ok(c) => c,
Err(e) => {
tracing::error!(error = %e, "configuration");
std::process::exit(2);
}
};
let store = match PgStore::connect(&cfg.pg).await {
Ok(s) => s,
Err(e) => {
tracing::error!(error = %e, "database pool");
std::process::exit(2);
}
};
// the database may still be starting: wait for it instead of crashing in a loop
let mut waited = 0;
loop {
match store.migrate().await {
Ok(()) => break,
Err(e) if e.contains("refusing to start") || e.starts_with("migration ") => {
tracing::error!(error = %e, "migration");
std::process::exit(3);
}
Err(e) => {
waited += 1;
if waited > 60 {
tracing::error!(error = %e, "the database never became ready");
std::process::exit(3);
}
tracing::warn!(error = %e, "waiting for the database");
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
}
let state = Arc::new(AppState::new(store, clock(), cfg.api.clone()));
let app = router(state).layer(ConcurrencyLimitLayer::new(cfg.max_in_flight)).layer(TimeoutLayer::with_status_code(axum::http::StatusCode::REQUEST_TIMEOUT, Duration::from_secs(cfg.request_timeout_secs)));
let tcp = match tokio::net::TcpListener::bind(&cfg.listen).await {
Ok(l) => l,
Err(e) => {
tracing::error!(error = %e, listen = %cfg.listen, "bind");
std::process::exit(2);
}
};
tracing::info!(listen = %cfg.listen, "registry started");
let listener = LimitedListener::new(tcp, cfg.max_connections);
let serve = axum::serve(listener, app.into_make_service_with_connect_info::<coa_registry::listener::Peer>()).with_graceful_shutdown(shutdown());
if let Err(e) = serve.await {
tracing::error!(error = %e, "server");
std::process::exit(1);
}
tracing::info!("registry stopped");
}
+227
View File
@@ -0,0 +1,227 @@
//! PostgreSQL storage and forward-only migrations.
use std::time::Duration;
use coa_registry_proto::caps::{AdvertisedCapabilities, Ruleset};
use coa_registry_proto::{HeartbeatRequest, RealmId, RegisterRequest};
use deadpool_postgres::{Manager, ManagerConfig, Object, Pool, RecyclingMethod, Runtime};
use tokio_postgres::{NoTls, Row};
use crate::store::*;
const MIGRATIONS: &[(i32, &str, &str)] = &[(1, "realms", include_str!("../migrations/0001_realms.sql"))];
pub struct PgConfig {
pub host: String,
pub port: u16,
pub dbname: String,
pub user: String,
pub password: String,
pub pool_size: usize,
pub statement_timeout_ms: u64,
}
pub struct PgStore {
pool: Pool,
}
fn backend(e: impl std::fmt::Display) -> StoreError {
StoreError::Backend(e.to_string())
}
impl PgStore {
pub async fn connect(cfg: &PgConfig) -> Result<Self, String> {
let mut pg = tokio_postgres::Config::new();
pg.host(&cfg.host).port(cfg.port).dbname(&cfg.dbname).user(&cfg.user).password(&cfg.password);
pg.connect_timeout(Duration::from_secs(5));
pg.application_name("coa-registry");
pg.options(&format!("-c statement_timeout={} -c idle_in_transaction_session_timeout=10000 -c lock_timeout=3000", cfg.statement_timeout_ms));
let manager = Manager::from_config(pg, NoTls, ManagerConfig { recycling_method: RecyclingMethod::Fast });
let pool = Pool::builder(manager)
.max_size(cfg.pool_size)
.wait_timeout(Some(Duration::from_secs(5)))
.create_timeout(Some(Duration::from_secs(5)))
.runtime(Runtime::Tokio1)
.build()
.map_err(|e| e.to_string())?;
Ok(Self { pool })
}
async fn conn(&self) -> StoreResult<Object> {
self.pool.get().await.map_err(backend)
}
/// Apply every migration the database has not seen. A database that is ahead of this binary is refused: migrations only go forward.
pub async fn migrate(&self) -> Result<(), String> {
let mut c = self.pool.get().await.map_err(|e| e.to_string())?;
c.batch_execute("SELECT pg_advisory_lock(7300100)").await.map_err(|e| e.to_string())?;
let result = Self::migrate_locked(&mut c).await;
let _ = c.batch_execute("SELECT pg_advisory_unlock(7300100)").await;
result
}
async fn migrate_locked(c: &mut Object) -> Result<(), String> {
c.batch_execute("CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY, name text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())").await.map_err(|e| e.to_string())?;
let applied: Vec<i32> = c.query("SELECT version FROM schema_migrations ORDER BY version", &[]).await.map_err(|e| e.to_string())?.iter().map(|r| r.get(0)).collect();
let newest = MIGRATIONS.last().map(|m| m.0).unwrap_or(0);
if let Some(ahead) = applied.iter().find(|v| **v > newest) {
return Err(format!("the database is at migration {ahead}, this binary knows up to {newest}: refusing to start"));
}
for (version, name, sql) in MIGRATIONS {
if applied.contains(version) {
continue;
}
let tx = c.transaction().await.map_err(|e| e.to_string())?;
tx.batch_execute(sql).await.map_err(|e| format!("migration {version} {name}: {e}"))?;
tx.execute("INSERT INTO schema_migrations(version, name) VALUES ($1, $2)", &[version, name]).await.map_err(|e| e.to_string())?;
tx.commit().await.map_err(|e| e.to_string())?;
tracing::info!(version, name, "migration applied");
}
Ok(())
}
}
const COLUMNS: &str = "realm_id::text, public_key, EXTRACT(EPOCH FROM created_at)::bigint, EXTRACT(EPOCH FROM updated_at)::bigint, EXTRACT(EPOCH FROM last_seen_at)::bigint, published, display_name, description, language, ruleset, manager_version, capabilities, capabilities_hash, metadata_revision, last_request_ts, player_count, player_capacity";
fn to_row(r: &Row) -> StoreResult<RealmRow> {
let id: String = r.get(0);
let key: Vec<u8> = r.get(1);
let ruleset: String = r.get(9);
let caps: serde_json::Value = r.get(11);
let revision: i64 = r.get(13);
let count: Option<i32> = r.get(15);
let capacity: Option<i32> = r.get(16);
Ok(RealmRow {
realm_id: RealmId::parse(&id).map_err(backend)?,
public_key: key.try_into().map_err(|_| StoreError::Backend("a stored key is not 32 bytes".into()))?,
created_at: r.get(2),
updated_at: r.get(3),
last_seen_at: r.get(4),
published: r.get(5),
display_name: r.get(6),
description: r.get(7),
language: r.get(8),
ruleset: match ruleset.as_str() {
"coa" => Ruleset::Coa,
"wildcard" => Ruleset::Wildcard,
other => return Err(StoreError::Backend(format!("a stored ruleset is unknown: {other}"))),
},
manager_version: r.get(10),
capabilities: serde_json::from_value::<AdvertisedCapabilities>(caps).map_err(backend)?,
capabilities_hash: r.get(12),
metadata_revision: revision as u64,
last_request_ts: r.get(14),
player_count: count.map(|n| n as u32),
player_capacity: capacity.map(|n| n as u32),
})
}
fn caps_json(c: &AdvertisedCapabilities) -> StoreResult<serde_json::Value> {
serde_json::to_value(c).map_err(backend)
}
impl Store for PgStore {
async fn ping(&self) -> bool {
match self.pool.get().await {
Ok(c) => c.query_one("SELECT 1", &[]).await.is_ok(),
Err(_) => false,
}
}
async fn key_of(&self, id: &RealmId) -> StoreResult<Option<[u8; 32]>> {
let c = self.conn().await?;
let row = c.query_opt("SELECT public_key FROM realms WHERE realm_id = $1::text::uuid", &[&id.to_string()]).await.map_err(backend)?;
row.map(|r| r.get::<_, Vec<u8>>(0).try_into().map_err(|_| StoreError::Backend("a stored key is not 32 bytes".into()))).transpose()
}
async fn get(&self, id: &RealmId) -> StoreResult<Option<RealmRow>> {
let c = self.conn().await?;
let row = c.query_opt(&format!("SELECT {COLUMNS} FROM realms WHERE realm_id = $1::text::uuid"), &[&id.to_string()]).await.map_err(backend)?;
row.as_ref().map(to_row).transpose()
}
async fn register(&self, req: &RegisterRequest, key: [u8; 32], now: i64, ts: i64) -> StoreResult<(RealmRow, bool)> {
let mut c = self.conn().await?;
let id = req.realm_id.to_string();
for _ in 0..3 {
let tx = c.transaction().await.map_err(backend)?;
let existing = tx.query_opt(&format!("SELECT {COLUMNS} FROM realms WHERE realm_id = $1::text::uuid FOR UPDATE"), &[&id]).await.map_err(backend)?;
let existing = existing.as_ref().map(to_row).transpose()?;
let (row, created) = plan_register(existing.as_ref(), req, key, now, ts)?;
let caps = caps_json(&row.capabilities)?;
let ruleset = row.ruleset.as_str();
let players = (row.player_count.map(|n| n as i32), row.player_capacity.map(|n| n as i32));
if created {
let n = tx
.execute(
"INSERT INTO realms (realm_id, public_key, created_at, updated_at, last_seen_at, published, display_name, description, language, ruleset, manager_version, capabilities, capabilities_hash, metadata_revision, last_request_ts, player_count, player_capacity) \
VALUES ($1::text::uuid, $2, to_timestamp($3::bigint), to_timestamp($3::bigint), to_timestamp($3::bigint), true, $4, $5, $6, $7, $8, $9, $10, 1, $11, $12, $13) ON CONFLICT (realm_id) DO NOTHING",
&[&id, &row.public_key.as_slice(), &now, &row.display_name, &row.description, &row.language, &ruleset, &row.manager_version, &caps, &row.capabilities_hash, &ts, &players.0, &players.1],
)
.await
.map_err(backend)?;
if n == 0 {
tx.rollback().await.map_err(backend)?;
continue;
}
} else {
tx.execute(
"UPDATE realms SET updated_at = to_timestamp($2::bigint), last_seen_at = to_timestamp($3::bigint), published = true, display_name = $4, description = $5, language = $6, ruleset = $7, manager_version = $8, capabilities = $9, capabilities_hash = $10, metadata_revision = $11, last_request_ts = $12, player_count = $13, player_capacity = $14 WHERE realm_id = $1::text::uuid",
&[&id, &row.updated_at, &now, &row.display_name, &row.description, &row.language, &ruleset, &row.manager_version, &caps, &row.capabilities_hash, &(row.metadata_revision as i64), &ts, &players.0, &players.1],
)
.await
.map_err(backend)?;
}
tx.commit().await.map_err(backend)?;
return Ok((row, created));
}
Err(StoreError::Backend("the registration kept racing another one".into()))
}
async fn heartbeat(&self, id: &RealmId, hb: &HeartbeatRequest, now: i64, ts: i64) -> StoreResult<HeartbeatOutcome> {
let mut c = self.conn().await?;
let text = id.to_string();
let tx = c.transaction().await.map_err(backend)?;
let r = tx
.query_opt("SELECT published, last_request_ts, capabilities_hash, display_name, description, language, manager_version, metadata_revision FROM realms WHERE realm_id = $1::text::uuid FOR UPDATE", &[&text])
.await
.map_err(backend)?
.ok_or(StoreError::Unknown)?;
let revision: i64 = r.get(7);
let view = HeartbeatView { published: r.get(0), last_request_ts: r.get(1), capabilities_hash: r.get(2), display_name: r.get(3), description: r.get(4), language: r.get(5), manager_version: r.get(6), metadata_revision: revision as u64 };
let plan = plan_heartbeat(&view, hb, ts)?;
let players = (hb.player_count.map(|n| n as i32), hb.player_capacity.map(|n| n as i32));
tx.execute(
"UPDATE realms SET last_seen_at = to_timestamp($2::bigint), last_request_ts = $3, player_count = $4, player_capacity = $5, display_name = $6, description = $7, language = $8, manager_version = $9, capabilities_hash = $10, metadata_revision = $11, updated_at = CASE WHEN $12 THEN to_timestamp($2::bigint) ELSE updated_at END WHERE realm_id = $1::text::uuid",
&[&text, &now, &ts, &players.0, &players.1, &plan.display_name, &plan.description, &plan.language, &plan.manager_version, &plan.capabilities_hash, &(plan.metadata_revision as i64), &plan.metadata_changed],
)
.await
.map_err(backend)?;
if let Some(caps) = &plan.capabilities {
let json = caps_json(caps)?;
tx.execute("UPDATE realms SET capabilities = $2, ruleset = $3 WHERE realm_id = $1::text::uuid", &[&text, &json, &caps.content.ruleset.as_str()]).await.map_err(backend)?;
}
tx.commit().await.map_err(backend)?;
Ok(HeartbeatOutcome { metadata_revision: plan.metadata_revision, capabilities_hash: plan.capabilities_hash, resend_capabilities: plan.resend_capabilities })
}
async fn unpublish(&self, id: &RealmId, now: i64, ts: i64) -> StoreResult<u64> {
let mut c = self.conn().await?;
let text = id.to_string();
let tx = c.transaction().await.map_err(backend)?;
let r = tx.query_opt("SELECT published, last_request_ts, metadata_revision FROM realms WHERE realm_id = $1::text::uuid FOR UPDATE", &[&text]).await.map_err(backend)?.ok_or(StoreError::Unknown)?;
let (published, last, revision): (bool, i64, i64) = (r.get(0), r.get(1), r.get(2));
if ts <= last {
return Err(StoreError::Stale);
}
let revision = revision as u64 + u64::from(published);
tx.execute(
"UPDATE realms SET published = false, metadata_revision = $2, last_request_ts = $3, updated_at = CASE WHEN $4 THEN to_timestamp($5::bigint) ELSE updated_at END WHERE realm_id = $1::text::uuid",
&[&text, &(revision as i64), &ts, &published, &now],
)
.await
.map_err(backend)?;
tx.commit().await.map_err(backend)?;
Ok(revision)
}
}
+286
View File
@@ -0,0 +1,286 @@
//! What the Registry keeps, and the rules for changing it. The rules are pure functions shared by the in-memory store (tests) and PostgreSQL,
//! so both behave identically; the stores only load and save.
use std::collections::HashMap;
use std::future::Future;
use std::sync::Mutex;
use coa_registry_proto::caps::{AdvertisedCapabilities, Ruleset};
use coa_registry_proto::{HeartbeatRequest, RealmId, RegisterRequest};
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum StoreError {
#[error("the realm is not known")]
Unknown,
#[error("another key owns this realm id")]
KeyMismatch,
#[error("the request is not newer than the last one applied")]
Stale,
#[error("the realm is not published")]
NotPublished,
#[error("{0}")]
Backend(String),
}
pub type StoreResult<T> = Result<T, StoreError>;
#[derive(Clone, Debug, PartialEq)]
pub struct RealmRow {
pub realm_id: RealmId,
pub public_key: [u8; 32],
pub created_at: i64,
pub updated_at: i64,
pub last_seen_at: i64,
pub published: bool,
pub display_name: String,
pub description: String,
pub language: String,
pub ruleset: Ruleset,
pub manager_version: String,
pub capabilities: AdvertisedCapabilities,
pub capabilities_hash: String,
pub metadata_revision: u64,
pub last_request_ts: i64,
pub player_count: Option<u32>,
pub player_capacity: Option<u32>,
}
/// The light part of a row a heartbeat decides on (the capabilities JSON stays in the database unless it changes).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HeartbeatView {
pub published: bool,
pub last_request_ts: i64,
pub capabilities_hash: String,
pub display_name: String,
pub description: String,
pub language: String,
pub manager_version: String,
pub metadata_revision: u64,
}
impl From<&RealmRow> for HeartbeatView {
fn from(r: &RealmRow) -> Self {
Self {
published: r.published,
last_request_ts: r.last_request_ts,
capabilities_hash: r.capabilities_hash.clone(),
display_name: r.display_name.clone(),
description: r.description.clone(),
language: r.language.clone(),
manager_version: r.manager_version.clone(),
metadata_revision: r.metadata_revision,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct HeartbeatPlan {
pub display_name: String,
pub description: String,
pub language: String,
pub manager_version: String,
/// Set only when the hash changed: the only case in which the large JSON is written.
pub capabilities: Option<AdvertisedCapabilities>,
pub capabilities_hash: String,
pub metadata_revision: u64,
pub metadata_changed: bool,
pub resend_capabilities: bool,
}
pub fn plan_heartbeat(view: &HeartbeatView, hb: &HeartbeatRequest, ts: i64) -> StoreResult<HeartbeatPlan> {
if ts <= view.last_request_ts {
return Err(StoreError::Stale);
}
if !view.published {
return Err(StoreError::NotPublished);
}
let mut plan = HeartbeatPlan {
display_name: hb.display_name.clone().unwrap_or_else(|| view.display_name.clone()),
description: hb.description.clone().unwrap_or_else(|| view.description.clone()),
language: hb.language.clone().unwrap_or_else(|| view.language.clone()),
manager_version: hb.manager_version.clone().unwrap_or_else(|| view.manager_version.clone()),
capabilities: None,
capabilities_hash: view.capabilities_hash.clone(),
metadata_revision: view.metadata_revision,
metadata_changed: false,
resend_capabilities: false,
};
plan.metadata_changed = plan.display_name != view.display_name || plan.description != view.description || plan.language != view.language || plan.manager_version != view.manager_version;
match &hb.capabilities {
Some(c) if hb.capabilities_hash != view.capabilities_hash => {
plan.capabilities = Some(c.clone());
plan.capabilities_hash = hb.capabilities_hash.clone();
plan.metadata_changed = true;
}
None if hb.capabilities_hash != view.capabilities_hash => plan.resend_capabilities = true,
_ => {}
}
if plan.metadata_changed {
plan.metadata_revision += 1;
}
Ok(plan)
}
/// The new row for a registration: a first one, or the same key announcing itself again (a restart, a changed name, a republication).
pub fn plan_register(existing: Option<&RealmRow>, req: &RegisterRequest, key: [u8; 32], now: i64, ts: i64) -> StoreResult<(RealmRow, bool)> {
let mut row = RealmRow {
realm_id: req.realm_id,
public_key: key,
created_at: now,
updated_at: now,
last_seen_at: now,
published: true,
display_name: req.display_name.clone(),
description: req.description.clone(),
language: req.language.clone(),
ruleset: req.ruleset,
manager_version: req.manager_version.clone(),
capabilities: req.capabilities.clone(),
capabilities_hash: req.capabilities_hash.clone(),
metadata_revision: 1,
last_request_ts: ts,
player_count: req.player_count,
player_capacity: req.player_capacity,
};
let Some(old) = existing else { return Ok((row, true)) };
if old.public_key != key {
return Err(StoreError::KeyMismatch);
}
if ts <= old.last_request_ts {
return Err(StoreError::Stale);
}
row.created_at = old.created_at;
let changed = !old.published
|| old.display_name != row.display_name
|| old.description != row.description
|| old.language != row.language
|| old.ruleset != row.ruleset
|| old.manager_version != row.manager_version
|| old.capabilities_hash != row.capabilities_hash;
row.metadata_revision = old.metadata_revision + u64::from(changed);
row.updated_at = if changed { now } else { old.updated_at };
Ok((row, false))
}
pub trait Store: Send + Sync + 'static {
fn ping(&self) -> impl Future<Output = bool> + Send;
/// The key a realm id is bound to, if it is registered.
fn key_of(&self, id: &RealmId) -> impl Future<Output = StoreResult<Option<[u8; 32]>>> + Send;
fn get(&self, id: &RealmId) -> impl Future<Output = StoreResult<Option<RealmRow>>> + Send;
/// `Ok((row, created))`
fn register(&self, req: &RegisterRequest, key: [u8; 32], now: i64, ts: i64) -> impl Future<Output = StoreResult<(RealmRow, bool)>> + Send;
fn heartbeat(&self, id: &RealmId, hb: &HeartbeatRequest, now: i64, ts: i64) -> impl Future<Output = StoreResult<HeartbeatOutcome>> + Send;
/// The metadata revision after the change.
fn unpublish(&self, id: &RealmId, now: i64, ts: i64) -> impl Future<Output = StoreResult<u64>> + Send;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HeartbeatOutcome {
pub metadata_revision: u64,
pub capabilities_hash: String,
pub resend_capabilities: bool,
}
#[derive(Default)]
pub struct MemoryStore {
rows: Mutex<HashMap<RealmId, RealmRow>>,
}
impl MemoryStore {
pub fn new() -> Self {
Self::default()
}
#[doc(hidden)]
pub fn get_for_test(&self, id: &RealmId) -> Option<RealmRow> {
self.rows.lock().unwrap().get(id).cloned()
}
/// Forget everything (tests: a Registry that lost its data).
#[doc(hidden)]
pub fn forget_all(&self) {
self.rows.lock().unwrap().clear();
}
}
/// A store shared between a test and the server it runs.
impl<T: Store> Store for std::sync::Arc<T> {
fn ping(&self) -> impl Future<Output = bool> + Send {
(**self).ping()
}
fn key_of(&self, id: &RealmId) -> impl Future<Output = StoreResult<Option<[u8; 32]>>> + Send {
(**self).key_of(id)
}
fn get(&self, id: &RealmId) -> impl Future<Output = StoreResult<Option<RealmRow>>> + Send {
(**self).get(id)
}
fn register(&self, req: &RegisterRequest, key: [u8; 32], now: i64, ts: i64) -> impl Future<Output = StoreResult<(RealmRow, bool)>> + Send {
(**self).register(req, key, now, ts)
}
fn heartbeat(&self, id: &RealmId, hb: &HeartbeatRequest, now: i64, ts: i64) -> impl Future<Output = StoreResult<HeartbeatOutcome>> + Send {
(**self).heartbeat(id, hb, now, ts)
}
fn unpublish(&self, id: &RealmId, now: i64, ts: i64) -> impl Future<Output = StoreResult<u64>> + Send {
(**self).unpublish(id, now, ts)
}
}
impl Store for MemoryStore {
async fn ping(&self) -> bool {
true
}
async fn key_of(&self, id: &RealmId) -> StoreResult<Option<[u8; 32]>> {
Ok(self.rows.lock().unwrap().get(id).map(|r| r.public_key))
}
async fn get(&self, id: &RealmId) -> StoreResult<Option<RealmRow>> {
Ok(self.rows.lock().unwrap().get(id).cloned())
}
async fn register(&self, req: &RegisterRequest, key: [u8; 32], now: i64, ts: i64) -> StoreResult<(RealmRow, bool)> {
let mut rows = self.rows.lock().unwrap();
let (row, created) = plan_register(rows.get(&req.realm_id), req, key, now, ts)?;
rows.insert(req.realm_id, row.clone());
Ok((row, created))
}
async fn heartbeat(&self, id: &RealmId, hb: &HeartbeatRequest, now: i64, ts: i64) -> StoreResult<HeartbeatOutcome> {
let mut rows = self.rows.lock().unwrap();
let row = rows.get_mut(id).ok_or(StoreError::Unknown)?;
let plan = plan_heartbeat(&HeartbeatView::from(&*row), hb, ts)?;
row.display_name = plan.display_name;
row.description = plan.description;
row.language = plan.language;
row.manager_version = plan.manager_version;
if let Some(c) = plan.capabilities {
row.ruleset = c.content.ruleset;
row.capabilities = c;
}
row.capabilities_hash = plan.capabilities_hash.clone();
if plan.metadata_changed {
row.updated_at = now;
}
row.metadata_revision = plan.metadata_revision;
row.last_seen_at = now;
row.last_request_ts = ts;
row.player_count = hb.player_count;
row.player_capacity = hb.player_capacity;
Ok(HeartbeatOutcome { metadata_revision: plan.metadata_revision, capabilities_hash: plan.capabilities_hash, resend_capabilities: plan.resend_capabilities })
}
async fn unpublish(&self, id: &RealmId, now: i64, ts: i64) -> StoreResult<u64> {
let mut rows = self.rows.lock().unwrap();
let row = rows.get_mut(id).ok_or(StoreError::Unknown)?;
if ts <= row.last_request_ts {
return Err(StoreError::Stale);
}
if row.published {
row.published = false;
row.metadata_revision += 1;
row.updated_at = now;
}
row.last_request_ts = ts;
Ok(row.metadata_revision)
}
}