Spaces:
Sleeping
Sleeping
File size: 20,133 Bytes
7178525 42327ea 7178525 42327ea 7178525 34c3d12 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 ff014c8 7178525 34c3d12 7178525 42327ea 7178525 ff014c8 7178525 34c3d12 42327ea 34c3d12 42327ea 7178525 42327ea 34c3d12 42327ea 7178525 42327ea 34c3d12 42327ea 34c3d12 42327ea 34c3d12 42327ea 7178525 42327ea 7178525 42327ea 7178525 fe2a7bb 7178525 42327ea 7178525 42327ea 7178525 42327ea d654e03 42327ea 7178525 42327ea 7178525 ff014c8 42327ea ff014c8 42327ea ff014c8 7178525 42327ea 7178525 42327ea 91b8dcb 42327ea 8df4fc5 42327ea d654e03 42327ea 34c3d12 42327ea 34c3d12 42327ea 7178525 42327ea 7178525 42327ea 7178525 fe2a7bb 7178525 42327ea d654e03 42327ea 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 ff014c8 42327ea ff014c8 42327ea ff014c8 42327ea ff014c8 7178525 42327ea 7178525 42327ea 7178525 42327ea 7178525 42327ea 34c3d12 42327ea 7178525 42327ea 7178525 34c3d12 7178525 | 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | //! HTTP-роуты.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::{
body::Bytes,
extract::{DefaultBodyLimit, Path, RawQuery, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use serde_json::{json, Value};
use tracing::{info, warn};
use uuid::Uuid;
use crate::encoder;
use crate::loader::{self, LoaderConfig};
use crate::nbt;
use crate::store::{Schematic, Store};
/// Жёсткий срок на весь `/upload` (скачивание + разбор + кодирование).
/// Меньше клиентского таймаута в 3 с: клиент всегда получает ответ.
pub const UPLOAD_DEADLINE: Duration = Duration::from_millis(2500);
#[derive(Clone)]
pub struct AppState {
pub store: Store,
pub client: reqwest::Client,
pub loader: Arc<LoaderConfig>,
pub deadline: Duration,
}
impl AppState {
pub fn new(store: Store, client: reqwest::Client, loader: LoaderConfig) -> Self {
AppState {
store,
client,
loader: Arc::new(loader),
deadline: UPLOAD_DEADLINE,
}
}
}
#[derive(Debug)]
pub enum ApiError {
BadRequest(String),
NotFound(String),
Internal(String),
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, message) = match self {
ApiError::BadRequest(m) => (StatusCode::BAD_REQUEST, m),
ApiError::NotFound(m) => (StatusCode::NOT_FOUND, m),
ApiError::Internal(m) => (StatusCode::INTERNAL_SERVER_ERROR, m),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
pub fn router(state: AppState) -> Router {
Router::new()
.route("/", get(index))
.route("/upload", post(upload))
.route("/get/:uuid/blocks", get(blocks_info))
.route("/get/:uuid/blocks/:index", get(blocks_part))
.route("/get/:uuid/nbt", get(nbt_info))
.route("/get/:uuid/nbt/:index", get(nbt_part))
.route("/get/:uuid/parts", get(parts_info))
.route("/get/:uuid/parts/:index", get(parts_part))
.route("/:uuid/status", get(status))
.route("/get/:uuid/status", get(status))
// тело /upload — одна ссылка
.layer(DefaultBodyLimit::max(16 * 1024))
.with_state(state)
}
fn parse_uuid(s: &str) -> Result<Uuid, ApiError> {
Uuid::parse_str(s).map_err(|_| ApiError::BadRequest(format!("некорректный UUID: {s}")))
}
fn parse_index(s: &str) -> Result<usize, ApiError> {
s.parse::<usize>()
.map_err(|_| ApiError::BadRequest(format!("некорректный индекс: {s}")))
}
fn find(state: &AppState, uuid: &str) -> Result<Arc<Schematic>, ApiError> {
let id = parse_uuid(uuid)?;
state
.store
.get(&id)
.ok_or_else(|| ApiError::NotFound("схематика с таким UUID не найдена".into()))
}
fn out_of_range(index: usize) -> ApiError {
ApiError::NotFound(format!("индекс {index} вне диапазона"))
}
async fn index() -> Json<Value> {
Json(json!({
"service": "litematic-host",
"endpoints": [
"POST /upload?x=0&y=0&z=0",
"GET /get/{uuid}/blocks",
"GET /get/{uuid}/blocks/{index}",
"GET /get/{uuid}/nbt",
"GET /get/{uuid}/nbt/{index}",
"GET /get/{uuid}/parts",
"GET /get/{uuid}/parts/{index}",
"GET /{uuid}/status",
],
}))
}
/// Сдвиг из query-строки `/upload?x=..&y=..&z=..`. Нет параметра — 0.
/// Неизвестные параметры игнорируются. Повтор параметра — побеждает последний.
fn parse_offset(query: Option<&str>) -> Result<[i32; 3], ApiError> {
let mut offset = [0i32; 3];
let Some(q) = query else {
return Ok(offset);
};
for pair in q.split('&').filter(|p| !p.is_empty()) {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
let slot = match key {
"x" => 0,
"y" => 1,
"z" => 2,
_ => continue,
};
offset[slot] = value.parse::<i32>().map_err(|_| {
ApiError::BadRequest(format!(
"параметр {key} должен быть целым числом i32, получено: {value:?}"
))
})?;
}
Ok(offset)
}
/// Скачивание + разбор + кодирование. Без таймаута — его ставит вызывающий.
async fn process(
state: &AppState,
url: reqwest::Url,
offset: [i32; 3],
cancel: Arc<AtomicBool>,
) -> Result<Schematic, ApiError> {
let data = loader::download(&state.client, url, &state.loader)
.await
.map_err(|e| {
warn!(error = %e, "ошибка скачивания");
ApiError::BadRequest(e.to_string())
})?;
info!(bytes = data.len(), "файл скачан, разбор");
// CPU-работа уходит с async-потока. Поток нельзя отменить снаружи,
// поэтому он сам проверяет флаг `cancel` на каждом слое по y.
tokio::task::spawn_blocking(move || -> Result<Schematic, String> {
let groups = nbt::parse_litematic_gz(&data, &nbt::Limits::default(), offset, &cancel)
.map_err(|e| e.to_string())?;
Schematic::build(&groups).map_err(|e| e.to_string())
})
.await
.map_err(|e| ApiError::Internal(format!("внутренняя ошибка: {e}")))?
.map_err(|e| {
warn!(error = %e, "ошибка разбора");
ApiError::BadRequest(e)
})
}
async fn upload(
State(state): State<AppState>,
RawQuery(query): RawQuery,
body: Bytes,
) -> Result<Json<String>, ApiError> {
let offset = parse_offset(query.as_deref())?;
let text = std::str::from_utf8(&body)
.map_err(|_| ApiError::BadRequest("тело запроса должно быть текстом UTF-8 со ссылкой".into()))?;
let url = loader::parse_url(text).map_err(|e| ApiError::BadRequest(e.to_string()))?;
let host = url.host_str().unwrap_or("?").to_string();
info!(%host, ?offset, "загрузка");
let started = Instant::now();
let cancel = Arc::new(AtomicBool::new(false));
let schematic = match tokio::time::timeout(state.deadline, process(&state, url, offset, cancel.clone())).await {
Ok(result) => result?,
Err(_) => {
cancel.store(true, Ordering::Relaxed);
warn!(%host, "не уложились в срок");
return Err(ApiError::BadRequest(format!(
"обработка не уложилась в {} мс: файл слишком большой или источник слишком медленный",
state.deadline.as_millis()
)));
}
};
let unique = schematic.unique_blocks;
let parts = schematic.part_ends.len();
let id = state.store.insert(schematic);
info!(
%id,
unique_blocks = unique,
parts,
elapsed_ms = started.elapsed().as_millis() as u64,
"схематика сохранена"
);
Ok(Json(id.to_string()))
}
async fn blocks_info(
State(state): State<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<Value>, ApiError> {
let s = find(&state, &uuid)?;
Ok(Json(json!({
"unique_blocks": s.unique_blocks,
"parts": s.block_parts.len(),
})))
}
async fn blocks_part(
State(state): State<AppState>,
Path((uuid, index)): Path<(String, String)>,
) -> Result<Json<Value>, ApiError> {
let s = find(&state, &uuid)?;
let i = parse_index(&index)?;
let part = s.block_parts.get(i).ok_or_else(|| out_of_range(i))?;
Ok(Json(encoder::list_part_json(part)))
}
async fn nbt_info(
State(state): State<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<Value>, ApiError> {
let s = find(&state, &uuid)?;
Ok(Json(json!({
"unique_nbt": s.unique_nbt,
"parts": s.nbt_parts.len(),
})))
}
async fn nbt_part(
State(state): State<AppState>,
Path((uuid, index)): Path<(String, String)>,
) -> Result<Json<Value>, ApiError> {
let s = find(&state, &uuid)?;
let i = parse_index(&index)?;
let part = s.nbt_parts.get(i).ok_or_else(|| out_of_range(i))?;
Ok(Json(encoder::nbt_part_json(part)))
}
async fn parts_info(
State(state): State<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<Value>, ApiError> {
let s = find(&state, &uuid)?;
Ok(Json(json!({ "parts": s.part_ends.len() })))
}
async fn parts_part(
State(state): State<AppState>,
Path((uuid, index)): Path<(String, String)>,
) -> Result<Json<Value>, ApiError> {
let s = find(&state, &uuid)?;
let i = parse_index(&index)?;
let chunk = encoder::text_part(&s.text, &s.part_ends, i).ok_or_else(|| out_of_range(i))?;
Ok(Json(json!({ "index": i, "data": chunk })))
}
/// Схематика разбирается прямо в `/upload`, поэтому любая найденная — готова.
async fn status(
State(state): State<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<Value>, ApiError> {
let s = find(&state, &uuid)?;
Ok(Json(json!({
"status": "ready",
"unique_blocks": s.unique_blocks,
"unique_nbt": s.unique_nbt,
"blocks_parts": s.block_parts.len(),
"nbt_parts": s.nbt_parts.len(),
"parts": s.part_ends.len(),
"text_chars": s.text.len(),
})))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::encoder::Groups;
use axum::body::Body;
use axum::http::Request;
use http_body_util::BodyExt;
use tower::ServiceExt;
fn app() -> (Router, AppState) {
let cfg = LoaderConfig::default();
let client = loader::build_client(&cfg).unwrap();
let state = AppState::new(Store::default(), client, cfg);
(router(state.clone()), state)
}
async fn call(app: &Router, req: Request<Body>) -> (StatusCode, String) {
let resp = app.clone().oneshot(req).await.unwrap();
let status = resp.status();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
(status, String::from_utf8(bytes.to_vec()).unwrap())
}
async fn get_json(app: &Router, uri: &str) -> (StatusCode, Value) {
let req = Request::builder().uri(uri).body(Body::empty()).unwrap();
let (status, body) = call(app, req).await;
(status, serde_json::from_str(&body).unwrap())
}
fn cells(list: &[(i32, i32, i32)]) -> Vec<u8> {
let mut b = Vec::new();
for &(x, y, z) in list {
encoder::push_position(&mut b, x, y, z).unwrap();
}
b
}
fn header(k: usize, n: usize, l: usize) -> String {
format!("{k:08}{n:08}{l:08}0000")
}
fn pos(x: &str, y: &str, z: &str) -> String {
format!(r#"{{'x':{x},'y':{y},'z':{z}}}"#)
}
/// chest с NBT в (1,1,1); dirt в (5,5,5); stone в (0,0,0) и (-1,2,3).
fn sample_groups() -> Groups {
let mut g = Groups::new();
g.insert(
("chest".into(), r#"{"Lock":"key"}"#.into()),
cells(&[(1, 1, 1)]),
);
g.insert(("dirt".into(), String::new()), cells(&[(5, 5, 5)]));
g.insert(
("stone".into(), String::new()),
cells(&[(0, 0, 0), (-1, 2, 3)]),
);
g
}
fn sample_id(state: &AppState) -> Uuid {
state.store.insert(Schematic::build(&sample_groups()).unwrap())
}
#[tokio::test]
async fn full_read_cycle() {
let (app, state) = app();
let id = sample_id(&state);
let (st, v) = get_json(&app, &format!("/get/{id}/blocks")).await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v, json!({ "unique_blocks": 3, "parts": 1 }));
let (st, v) = get_json(&app, &format!("/get/{id}/blocks/0")).await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v, json!(["chest", "dirt", "stone"]));
let (st, v) = get_json(&app, &format!("/get/{id}/nbt")).await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v, json!({ "unique_nbt": 1, "parts": 1 }));
let (st, v) = get_json(&app, &format!("/get/{id}/nbt/0")).await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v, json!([{ "Lock": "key" }]));
let (st, v) = get_json(&app, &format!("/get/{id}/parts")).await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v, json!({ "parts": 1 }));
let (st, v) = get_json(&app, &format!("/get/{id}/parts/0")).await;
assert_eq!(st, StatusCode::OK);
let expected = [
header(0, 1, 1),
pos("0001", "0001", "0001"),
header(1, 0, 1),
pos("0005", "0005", "0005"),
header(2, 0, 2),
pos("0000", "0000", "0000"),
pos("-001", "0002", "0003"),
]
.concat();
assert_eq!(v["index"], 0);
assert_eq!(v["data"], json!(expected));
assert_eq!(expected.len(), 7 * 28);
}
#[tokio::test]
async fn index_out_of_range_is_404() {
let (app, state) = app();
let id = sample_id(&state);
for tail in ["blocks/1", "nbt/1", "parts/1"] {
let (st, v) = get_json(&app, &format!("/get/{id}/{tail}")).await;
assert_eq!(st, StatusCode::NOT_FOUND, "{tail}");
assert!(v["error"].is_string());
}
}
#[tokio::test]
async fn unknown_uuid_is_404() {
let (app, _) = app();
let id = Uuid::new_v4();
for tail in ["blocks", "blocks/0", "nbt", "nbt/0", "parts", "parts/0"] {
let (st, _) = get_json(&app, &format!("/get/{id}/{tail}")).await;
assert_eq!(st, StatusCode::NOT_FOUND, "{tail}");
}
}
#[tokio::test]
async fn bad_uuid_is_400() {
let (app, _) = app();
for tail in ["blocks", "blocks/0", "nbt", "nbt/0", "parts", "parts/0"] {
let (st, _) = get_json(&app, &format!("/get/not-a-uuid/{tail}")).await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{tail}");
}
}
#[tokio::test]
async fn status_endpoint() {
let (app, state) = app();
let id = sample_id(&state);
for uri in [format!("/{id}/status"), format!("/get/{id}/status")] {
let (st, v) = get_json(&app, &uri).await;
assert_eq!(st, StatusCode::OK, "{uri}");
assert_eq!(
v,
json!({
"status": "ready",
"unique_blocks": 3,
"unique_nbt": 1,
"blocks_parts": 1,
"nbt_parts": 1,
"parts": 1,
"text_chars": 196,
})
);
}
let (st, _) = get_json(&app, &format!("/{}/status", Uuid::new_v4())).await;
assert_eq!(st, StatusCode::NOT_FOUND);
let (st, _) = get_json(&app, "/not-a-uuid/status").await;
assert_eq!(st, StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn bad_index_is_400() {
let (app, state) = app();
let id = sample_id(&state);
let (st, _) = get_json(&app, &format!("/get/{id}/parts/abc")).await;
assert_eq!(st, StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn empty_schematic_has_zero_parts() {
let (app, state) = app();
let id = state.store.insert(Schematic::build(&Groups::new()).unwrap());
let (_, v) = get_json(&app, &format!("/get/{id}/blocks")).await;
assert_eq!(v, json!({ "unique_blocks": 0, "parts": 0 }));
let (_, v) = get_json(&app, &format!("/get/{id}/nbt")).await;
assert_eq!(v, json!({ "unique_nbt": 0, "parts": 0 }));
let (_, v) = get_json(&app, &format!("/get/{id}/parts")).await;
assert_eq!(v, json!({ "parts": 0 }));
let (st, _) = get_json(&app, &format!("/get/{id}/parts/0")).await;
assert_eq!(st, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn long_run_is_split_across_parts_with_new_headers() {
let (app, state) = app();
let mut g = Groups::new();
let list: Vec<(i32, i32, i32)> = (0..2000).map(|i| (i, 0, 0)).collect();
g.insert(("stone".into(), String::new()), cells(&list));
let id = state.store.insert(Schematic::build(&g).unwrap());
let (_, v) = get_json(&app, &format!("/get/{id}/parts")).await;
assert_eq!(v, json!({ "parts": 3 }));
// 856 + 856 + 288 позиций, перед каждой серией свой заголовок
let sizes = [857 * 28, 857 * 28, 289 * 28];
let counts = [856usize, 856, 288];
for i in 0..3 {
let (st, v) = get_json(&app, &format!("/get/{id}/parts/{i}")).await;
assert_eq!(st, StatusCode::OK);
let data = v["data"].as_str().unwrap();
assert_eq!(data.len(), sizes[i]);
assert_eq!(&data[..28], header(0, 0, counts[i]));
}
let (st, _) = get_json(&app, &format!("/get/{id}/parts/3")).await;
assert_eq!(st, StatusCode::NOT_FOUND);
}
#[test]
fn offset_parsing() {
assert_eq!(parse_offset(None).unwrap(), [0, 0, 0]);
assert_eq!(parse_offset(Some("")).unwrap(), [0, 0, 0]);
assert_eq!(parse_offset(Some("x=1&y=-2&z=3")).unwrap(), [1, -2, 3]);
assert_eq!(parse_offset(Some("y=5")).unwrap(), [0, 5, 0]);
assert_eq!(parse_offset(Some("foo=1&z=2")).unwrap(), [0, 0, 2]);
assert_eq!(parse_offset(Some("x=1&x=2")).unwrap(), [2, 0, 0]);
assert_eq!(parse_offset(Some("x=+7")).unwrap(), [7, 0, 0]);
for bad in ["x=abc", "x=", "y=1.5", "z=99999999999", "x"] {
assert!(
matches!(parse_offset(Some(bad)), Err(ApiError::BadRequest(_))),
"{bad}"
);
}
}
#[tokio::test]
async fn upload_rejects_bad_offset() {
let (app, _) = app();
for uri in ["/upload?x=abc", "/upload?y=1.5", "/upload?x=1&z=99999999999"] {
let req = Request::builder()
.method("POST")
.uri(uri)
.body(Body::from("https://example.com/a.litematic"))
.unwrap();
let (st, text) = call(&app, req).await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{uri}");
let v: Value = serde_json::from_str(&text).unwrap();
assert!(v["error"].as_str().unwrap().contains("параметр"));
}
}
#[tokio::test]
async fn upload_accepts_offset_in_query() {
// ссылка локальная — отклоняется по ссылке, а не по сдвигу
let (app, _) = app();
let req = Request::builder()
.method("POST")
.uri("/upload?x=100&y=64&z=-20")
.body(Body::from("http://127.0.0.1:1/a.litematic"))
.unwrap();
let (st, text) = call(&app, req).await;
assert_eq!(st, StatusCode::BAD_REQUEST);
let v: Value = serde_json::from_str(&text).unwrap();
assert!(!v["error"].as_str().unwrap().contains("параметр"));
}
#[tokio::test]
async fn upload_rejects_bad_links() {
let (app, _) = app();
for body in ["", "not a url", "ftp://example.com/a.litematic", "http://127.0.0.1:1/a.litematic"] {
let req = Request::builder()
.method("POST")
.uri("/upload")
.body(Body::from(body))
.unwrap();
let (st, text) = call(&app, req).await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{body:?}");
let v: Value = serde_json::from_str(&text).unwrap();
assert!(v["error"].as_str().unwrap().len() > 5);
}
}
}
|