Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,5 @@ MC_STATUS_ADDR=mc.internal.example:25565
# MAP_ASSETS_DATABASE=
# 入口のプロキシが /live/clients に送るときの合言葉 (秘密。空なら受け付けない)
# MAP_CLIENTS_TOKEN=
# /live/clients と /healthz (接続中の人数だけ) だけを受ける、追加の内部専用の待受。送り元が別のポートへ送るときに使う。無ければ起動しない (公開しない)
# MAP_CLIENTS_ADDR=0.0.0.0:3000
20 changes: 20 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ async fn main() {
});
}

// `/live/clients` だけを受ける追加の内部専用の待受 (Velocity の送り先が別のポートのとき用)。env が無ければ起動しない
if let Some(addr) = app.cfg.map3d.clients_addr.clone() {
let Some(map3d) = app.map3d.clone() else {
eprintln!(
"config error: MAP_CLIENTS_ADDR requires MAP_DB_HOST and MAP_BLUEMAP_DATABASE"
);
std::process::exit(2);
};
let extra = tokio::net::TcpListener::bind(&addr)
.await
.expect("bind MAP_CLIENTS_ADDR");
eprintln!("clients listener (/live/clients, /healthz) on {addr}");
tokio::spawn(async move {
axum::serve(extra, toro_api::map::live::clients_router(map3d))
.with_graceful_shutdown(shutdown_signal())
.await
.expect("clients server");
});
}

axum::serve(listener, toro_api::routes::router(app))
.with_graceful_shutdown(shutdown_signal())
.await
Expand Down
24 changes: 24 additions & 0 deletions src/map/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,30 @@ pub fn router_with(map: Arc<MapService>, map3d: Option<Arc<Map3d>>) -> Router {
.with_state(Internal { map, map3d })
}

/// `/live/clients` と `/healthz` だけを受ける追加の内部専用の待受のルーター (`MAP_CLIENTS_ADDR`)。
/// `/live/clients` の検証は、`router_with` の待受と同じ `clients` を使う。`/healthz` には人数だけを出す (IP は出さない)
pub fn clients_router(map3d: Arc<Map3d>) -> Router {
Router::new().fallback(dispatch_clients).with_state(map3d)
}

async fn dispatch_clients(State(map3d): State<Arc<Map3d>>, request: Request) -> Response {
match request.uri().path() {
"/healthz" => {
let body = json!({ "ok": true, "players": map3d.clients.online_count() });
let mut res = Response::new(body.to_string().into());
let headers = res.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
res
}
"/live/clients" => clients(map3d, request).await,
_ => text_response(StatusCode::NOT_FOUND, "Not Found"),
}
}

fn text_response(status: StatusCode, text: &'static str) -> Response {
let mut res = Response::new(text.into());
*res.status_mut() = status;
Expand Down
3 changes: 3 additions & 0 deletions src/map3d/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ pub struct Map3dConfig {
pub grace_minutes: u64,
/// 入口のプロキシが `/live/clients` に送るときの合言葉 (`MAP_CLIENTS_TOKEN`)。空なら受け付けない
pub clients_token: String,
/// /live/clients と /healthz だけを受ける追加の内部専用の待受 (host:port。MAP_CLIENTS_ADDR)。無ければ起動しない
pub clients_addr: Option<String>,
pub mcassets: mcassets::McAssetsConfig,
pub sign: sign::SignConfig,
}
Expand Down Expand Up @@ -104,6 +106,7 @@ impl Map3dConfig {
.parse()
.map_err(|_| "MAP_ASSETS_GRACE_MINUTES must be a number".to_string())?,
clients_token: std::env::var("MAP_CLIENTS_TOKEN").unwrap_or_default(),
clients_addr: optional("MAP_CLIENTS_ADDR"),
mcassets: mcassets::McAssetsConfig::from_env()?,
sign: sign::SignConfig::from_env()?,
})
Expand Down
165 changes: 165 additions & 0 deletions tests/clients_addr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
//! 追加の内部専用の待受 (`MAP_CLIENTS_ADDR`): `POST /live/clients` と `GET /healthz` だけを受ける

mod common;

use std::sync::Arc;

use common::fake_map::*;
use futures_util::future::BoxFuture;
use toro_api::map::MapService;
use toro_api::map::hub::Hub;
use toro_api::map::live::clients_router;
use toro_api::map3d::store::{BlueData, BluemapStore};
use toro_api::map3d::{Map3d, Map3dConfig};

const TOKEN: &str = "clients-secret";

struct EmptyBlue;

impl BluemapStore for EmptyBlue {
fn tile<'a>(
&'a self,
_: &'a str,
_: &'a str,
_: i64,
_: i64,
) -> BoxFuture<'a, toro_api::map::store::StoreResult<Option<BlueData>>> {
Box::pin(async { Ok(None) })
}
fn item<'a>(
&'a self,
_: &'a str,
_: &'a str,
) -> BoxFuture<'a, toro_api::map::store::StoreResult<Option<BlueData>>> {
Box::pin(async { Ok(None) })
}
fn map_exists<'a>(
&'a self,
_: &'a str,
) -> BoxFuture<'a, toro_api::map::store::StoreResult<bool>> {
Box::pin(async { Ok(false) })
}
fn map_ids<'a>(&'a self) -> BoxFuture<'a, toro_api::map::store::StoreResult<Vec<String>>> {
Box::pin(async { Ok(vec![]) })
}
}

struct Extra {
base: String,
map3d: Arc<Map3d>,
client: reqwest::Client,
}

async fn start() -> Extra {
let store = Arc::new(FakeStore::default());
let map = MapService::with_limits(store.clone(), Hub::manual(store), "live".to_string(), 16, 4);
let cfg = Map3dConfig {
clients_token: TOKEN.to_string(),
grace_minutes: 10,
..Default::default()
};
let map3d = Map3d::with_parts(cfg, map, Arc::new(EmptyBlue), reqwest::Client::new(), None);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let router = clients_router(map3d.clone());
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
Extra {
base,
map3d,
client: reqwest::Client::new(),
}
}

impl Extra {
async fn post(&self, token: Option<&str>, body: &str) -> reqwest::Response {
let mut req = self
.client
.post(format!("{}/live/clients", self.base))
.body(body.to_string());
if let Some(token) = token {
req = req.header("x-toro-token", token);
}
req.send().await.unwrap()
}

async fn players(&self) -> u64 {
let res = self
.client
.get(format!("{}/healthz", self.base))
.send()
.await
.unwrap();
assert_eq!(res.status(), 200);
let body: serde_json::Value = res.json().await.unwrap();
assert_eq!(body["ok"], true);
body["players"].as_u64().unwrap()
}
}

#[tokio::test]
async fn missing_or_wrong_token_is_403() {
let s = start().await;
assert_eq!(
s.post(None, r#"{"ips":["203.0.113.7"]}"#).await.status(),
403
);
assert_eq!(
s.post(Some("wrong"), r#"{"ips":["203.0.113.7"]}"#)
.await
.status(),
403
);
assert_eq!(s.players().await, 0);
}

#[tokio::test]
async fn correct_token_is_204_and_healthz_counts_players_only() {
let s = start().await;
let res = s
.post(Some(TOKEN), r#"{"ips":["203.0.113.7","203.0.113.8"]}"#)
.await;
assert_eq!(res.status(), 204);
assert!(s.map3d.clients.is_player("203.0.113.7"));
assert_eq!(s.players().await, 2);
// 人数だけで、IP は出さない
let text = s
.client
.get(format!("{}/healthz", s.base))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert!(!text.contains("203.0.113"));
}

#[tokio::test]
async fn empty_array_is_204_and_keeps_the_grace() {
let s = start().await;
s.post(Some(TOKEN), r#"{"ips":["203.0.113.7"]}"#).await;
assert_eq!(s.post(Some(TOKEN), r#"{"ips":[]}"#).await.status(), 204);
assert_eq!(s.players().await, 0);
// 猶予の間は、まだ読める
assert!(s.map3d.clients.is_player("203.0.113.7"));
}

#[tokio::test]
async fn other_paths_are_404() {
let s = start().await;
for path in [
"/",
"/live/plugin",
"/map/v1/configuration",
"/_assets/abc.png",
"/live/",
] {
let res = s
.client
.get(format!("{}{path}", s.base))
.send()
.await
.unwrap();
assert_eq!(res.status(), 404, "{path}");
}
}
Loading