Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-translate/blob/main/tests/protocol.rs # aien-translate aien-dev/aien-translate Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-translate / tests / protocol.rs` 370 lines ยท 16399 bytes Raw Blame History 1 //! End-to-end protocol tests against a fake engine (no GPU needed). 2 3 use aien_translate::{app, cache::Cache, engine::Engine, Admission, AppState, Limits}; 4 use axum::{extract::State, routing::{get, post}, Json, Router}; 5 use serde_json::{json, Value}; 6 use std::sync::atomic::{AtomicUsize, Ordering}; 7 use std::sync::Arc; 8 9 10 /// Fake engine: "translates" by prefixing "ZH:". Misbehaves on purpose for 11 /// strings containing DROPLINK (drops the URL) or BADCOUNT (wrong item count 12 /// when batched with others). 13 async fn fake_chat(State(calls): State>, Json(req): Json) -> Json { 14 calls.fetch_add(1, Ordering::SeqCst); 15 let user = req["messages"][1]["content"].as_str().unwrap(); 16 let items: Vec = serde_json::from_str(user).unwrap(); 17 let mut out: Vec = items 18 .iter() 19 .map(|s| { 20 if s.contains("DROPLINK") { 21 "ZH: link gone".to_string() 22 } else { 23 format!("ZH:{s}") 24 } 25 }) 26 .collect(); 27 if items.len() > 1 && items.iter().any(|s| s.contains("BADCOUNT")) { 28 out.pop(); 29 } 30 let content = format!("```json\n{}\n```", serde_json::to_string(&out).unwrap()); 31 Json(json!({"choices": [{"message": {"role": "assistant", "content": content}}]})) 32 } 33 34 async fn start() -> String { 35 start_counted().await.0 36 } 37 38 async fn start_counted() -> (String, Arc) { 39 let calls = Arc::new(AtomicUsize::new(0)); 40 let fake = Router::new() 41 .route("/v1/models", get(|| async { Json(json!({"data": [{"id": "fake-model"}]})) })) 42 .route("/v1/chat/completions", post(fake_chat)) 43 .with_state(calls.clone()); 44 (start_with(fake).await, calls) 45 } 46 47 /// Start aien-translate in front of the given fake engine. 48 async fn start_with(fake: Router) -> String { 49 let fl = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 50 let faddr = fl.local_addr().unwrap(); 51 tokio::spawn(async move { axum::serve(fl, fake).await.unwrap() }); 52 53 let state = Arc::new(AppState { 54 engine: Engine::new(&format!("http://{faddr}")), 55 cache: Cache::in_memory().unwrap(), 56 keep: vec!["AIEN".into()], 57 limits: Limits { max_texts: 40, max_chars: 3000 }, 58 admission: Admission::new(Some("test-token-`0123456789012345678901234567`".into())), 59 }); 60 let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 61 let addr = l.local_addr().unwrap(); 62 tokio::spawn(async move { axum::serve(l, app(state).into_make_service_with_connect_info::()).await.unwrap() }); 63 format!("http://{addr}") 64 } 65 66 /// Post exactly the way translate.js does: hand-joined form fields, with 67 /// `text` = encodeURIComponent(JSON.stringify(array)). 68 async fn post_like_translate_js(base: &str, texts: &[&str]) -> Value { 69 let json_text = serde_json::to_string(texts).unwrap(); 70 let encoded: String = form_urlencoded::byte_serialize(json_text.as_bytes()).collect::().replace('+', "%20"); 71 let body = format!("from=english&to=chinese_simplified&text={encoded}&browserDefaultLanguage=english"); 72 reqwest::Client::new() 73 .post(format!("{base}/translate.json?v=4.1.0.`20260526`")) 74 .header("content-type", "application/x-www-form-urlencoded") 75 .bearer_auth("test-token-`0123456789012345678901234567`") 76 .body(body) 77 .send() 78 .await 79 .unwrap() 80 .json() 81 .await 82 .unwrap() 83 } 84 85 #[tokio::test] 86 async fn anonymous_translation_cannot_use_inference() { 87 let (base, calls) = start_counted().await; 88 let response = reqwest::Client::new() 89 .post(format!("{base}/translate.json")) 90 .body("from=english&to=japanese&text=uncached") 91 .send().await.unwrap(); 92 assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED); 93 assert_eq!(calls.load(Ordering::SeqCst), 0); 94 } 95 96 #[tokio::test] 97 async fn bad_token_and_cross_origin_are_not_admitted() { 98 let (base, calls) = start_counted().await; 99 let client = reqwest::Client::new(); 100 let rejected = client.post(format!("{base}/translate.json")) 101 .bearer_auth("wrong-token").body("to=japanese&text=uncached") 102 .send().await.unwrap(); 103 assert_eq!(rejected.status(), reqwest::StatusCode::UNAUTHORIZED); 104 let preflight = client.request(reqwest::Method::OPTIONS, format!("{base}/translate.json")) 105 .header("origin", "https://untrusted.example") 106 .header("access-control-request-method", "POST") 107 .send().await.unwrap(); 108 assert!(preflight.headers().get("access-control-allow-origin").is_none()); 109 assert_eq!(calls.load(Ordering::SeqCst), 0); 110 let allowed = post_like_translate_js(&base, &["uncached"]).await; 111 assert_eq!(allowed["result"], 1, "{allowed}"); 112 assert_eq!(calls.load(Ordering::SeqCst), 1); 113 } 114 115 #[tokio::test] 116 async fn peer_rate_limit_refuses_uncached_work() { 117 let (base, calls) = start_counted().await; 118 for n in 0..6 { 119 let text = format!("uncached {n}"); 120 assert_eq!(post_like_translate_js(&base, &[&text]).await["result"], 1); 121 } 122 let response = reqwest::Client::new() 123 .post(format!("{base}/translate.json")) 124 .bearer_auth("test-token-`0123456789012345678901234567`") 125 .body("from=english&to=japanese&text=seventh") 126 .send().await.unwrap(); 127 assert_eq!(response.status(), reqwest::StatusCode::TOO_MANY_REQUESTS); 128 assert_eq!(calls.load(Ordering::SeqCst), 6); 129 } 130 131 #[test] 132 fn non_loopback_binding_is_refused() { 133 let output = std::process::Command::new(env!("CARGO_BIN_EXE_aien-translate")) 134 .args(["--listen", "0.0.0.0:0"]).output().unwrap(); 135 assert!(!output.status.success()); 136 assert!(String::from_utf8_lossy(&output.stderr).contains("--listen must be loopback")); 137 } 138 139 #[tokio::test] 140 async fn translate_js_protocol_round_trip() { 141 let (base, calls) = start_counted().await; 142 143 let r = post_like_translate_js(&base, &["Hello world", " Run AIEN + more ", "12,345", "Hello world"]).await; 144 assert_eq!(r["result"], 1, "{r}"); 145 let text: Vec = serde_json::from_value(r["text"].clone()).unwrap(); 146 assert_eq!(text, vec!["ZH:Hello world", " ZH:Run AIEN + more ", "12,345", "ZH:Hello world"]); 147 assert_eq!(r["aien"]["translated"], 3); 148 assert_eq!(r["aien"]["nothing_to_do"], 1); 149 150 // Second time: all from the saved translations, no engine call. 151 let before = calls.load(Ordering::SeqCst); 152 let r2 = post_like_translate_js(&base, &["Hello world"]).await; 153 assert_eq!(r2["text"][0], "ZH:Hello world"); 154 assert_eq!(r2["aien"]["from_cache"], 1); 155 assert_eq!(calls.load(Ordering::SeqCst), before); 156 } 157 158 #[tokio::test] 159 async fn broken_translation_keeps_original() { 160 let base = start().await; 161 let r = post_like_translate_js(&base, &["See https://aienos.com DROPLINK"]).await; 162 assert_eq!(r["text"][0], "See https://aienos.com DROPLINK"); 163 assert_eq!(r["aien"]["kept_original"], 1); 164 } 165 166 #[tokio::test] 167 async fn mismatched_batch_is_split_and_recovers() { 168 let base = start().await; 169 let r = post_like_translate_js(&base, &["one", "two BADCOUNT", "three"]).await; 170 let text: Vec = serde_json::from_value(r["text"].clone()).unwrap(); 171 assert_eq!(text, vec!["ZH:one", "ZH:two BADCOUNT", "ZH:three"]); 172 } 173 174 #[tokio::test] 175 async fn housekeeping_endpoints() { 176 let base = start().await; 177 let c = reqwest::Client::new(); 178 let lang: Value = c.post(format!("{base}/language.json")).send().await.unwrap().json().await.unwrap(); 179 assert_eq!(lang["result"], 1); 180 assert!(lang["list"].as_array().unwrap().iter().any(|l| l["id"] == "chinese_simplified")); 181 182 let ct: Value = c 183 .post(format!("{base}/connectTest.json")) 184 .header("content-type", "application/x-www-form-urlencoded") 185 .body("host=https://x/") 186 .send() 187 .await 188 .unwrap() 189 .json() 190 .await 191 .unwrap(); 192 assert_eq!(ct["info"], "https://x/"); 193 194 let bad: Value = c 195 .post(format!("{base}/translate.json")) 196 .header("content-type", "application/x-www-form-urlencoded") 197 .bearer_auth("test-token-`0123456789012345678901234567`") 198 .body("from=english&to=klingon&text=%5B%22hi%22%5D") 199 .send() 200 .await 201 .unwrap() 202 .json() 203 .await 204 .unwrap(); 205 assert_eq!(bad["result"], 0); 206 } 207 208 #[tokio::test] 209 async fn oversized_request_is_refused() { 210 let base = start().await; 211 let many: Vec<&str> = vec!["x y"; 60]; 212 let r = post_like_translate_js(&base, &many).await; 213 assert_eq!(r["result"], 0); 214 } 215 216 #[tokio::test] 217 async fn body_limit_rejects_before_inference() { 218 let (base, calls) = start_counted().await; 219 let response = reqwest::Client::new() 220 .post(format!("{base}/translate.json")) 221 .bearer_auth("test-token-`0123456789012345678901234567`") 222 .body(format!("to=japanese&text={}", "x".repeat(17_000))) 223 .send().await.unwrap(); 224 assert_eq!(response.status(), reqwest::StatusCode::PAYLOAD_TOO_LARGE); 225 assert_eq!(calls.load(Ordering::SeqCst), 0); 226 } 227 228 #[tokio::test] 229 async fn in_flight_request_does_not_queue_another() { 230 let entered = Arc::new(tokio::sync::Notify::new()); 231 let release = Arc::new(tokio::sync::Notify::new()); 232 let calls = Arc::new(AtomicUsize::new(0)); 233 let fake = Router::new() 234 .route("/v1/models", get(|| async { Json(json!({"data": [{"id": "fake-model"}]})) })) 235 .route("/v1/chat/completions", post({ 236 let entered = entered.clone(); 237 let release = release.clone(); 238 move |Json(req): Json| { 239 let entered = entered.clone(); 240 let release = release.clone(); 241 let calls = calls.clone(); 242 async move { 243 entered.notify_one(); 244 release.notified().await; 245 fake_chat(State(calls), Json(req)).await 246 } 247 } 248 })); 249 let base = start_with(fake).await; 250 let first_base = base.clone(); 251 let first = tokio::spawn(async move { post_like_translate_js(&first_base, &["first text"]).await }); 252 tokio::time::timeout(std::time::Duration::from_secs(3), entered.notified()).await.unwrap(); 253 let response = reqwest::Client::new() 254 .post(format!("{base}/translate.json")) 255 .bearer_auth("test-token-`0123456789012345678901234567`") 256 .body("from=english&to=japanese&text=second%20text") 257 .send().await.unwrap(); 258 assert_eq!(response.status(), reqwest::StatusCode::TOO_MANY_REQUESTS); 259 release.notify_one(); 260 assert_eq!(first.await.unwrap()["result"], 1); 261 } 262 263 fn sse(delta: &str) -> String { 264 format!("data: {}\n\n", json!({"choices": [{"index": 0, "delta": {"content": delta}}]})) 265 } 266 267 /// The model finishes the list, then keeps writing junk (as seen on the real 268 /// server). aien-translate must hang up once the list is complete instead of 269 /// waiting for the junk to end. 270 #[tokio::test] 271 async fn stops_reading_once_the_list_is_complete() { 272 let junk_sent = Arc::new(AtomicUsize::new(0)); 273 let js = junk_sent.clone(); 274 let fake = Router::new() 275 .route("/v1/models", get(|| async { Json(json!({"data": [{"id": "fake-model"}]})) })) 276 .route( 277 "/v1/chat/completions", 278 post(move |Json(req): Json| { 279 let js = js.clone(); 280 async move { 281 let items: Vec = 282 serde_json::from_str(req["messages"][1]["content"].as_str().unwrap()).unwrap(); 283 let list = serde_json::to_string(&items.iter().map(|s| format!("ZH:{s}")).collect::>()).unwrap(); 284 if req["stream"] != json!(true) { 285 // Not streaming: the whole reply, junk included, arrives only at the end. 286 tokio::time::sleep(std::time::Duration::from_secs(3)).await; 287 let content = format!("{list}\n\n[{{\"name\": \"junk\""); 288 return axum::response::Response::builder() 289 .header("content-type", "application/json") 290 .body(axum::body::Body::from( 291 json!({"choices": [{"message": {"role": "assistant", "content": content}}]}).to_string(), 292 )) 293 .unwrap(); 294 } 295 let (tx, rx) = tokio::sync::mpsc::channel::>(1); 296 tokio::spawn(async move { 297 for piece in list.as_bytes().chunks(4) { 298 if tx.send(Ok(sse(std::str::from_utf8(piece).unwrap()))).await.is_err() { 299 return; 300 } 301 } 302 for _ in 0..100 { 303 tokio::time::sleep(std::time::Duration::from_millis(30)).await; 304 if tx.send(Ok(sse("{\"name\": \"junk\"} "))).await.is_err() { 305 return; 306 } 307 js.fetch_add(1, Ordering::SeqCst); 308 } 309 let _ = tx.send(Ok("data: [DONE]\n\n".to_string())).await; 310 }); 311 axum::response::Response::builder() 312 .header("content-type", "text/event-stream") 313 .body(axum::body::Body::from_stream(tokio_stream::wrappers::ReceiverStream::new(rx))) 314 .unwrap() 315 } 316 }), 317 ); 318 let base = start_with(fake).await; 319 let t = std::time::Instant::now(); 320 let r = post_like_translate_js(&base, &["alpha", "beta"]).await; 321 let took = t.elapsed(); 322 assert_eq!(r["result"], 1, "{r}"); 323 assert_eq!(r["text"], json!(["ZH:alpha", "ZH:beta"])); 324 assert!(took < std::time::Duration::from_millis(1500), "took {took:?}: kept reading after the list closed"); 325 tokio::time::sleep(std::time::Duration::from_millis(200)).await; 326 assert!(junk_sent.load(Ordering::SeqCst) < 10, "fake engine kept streaming: {} junk chunks", junk_sent.load(Ordering::SeqCst)); 327 } 328 329 /// The model server answers 503 "busy, retry shortly" while it finishes a 330 /// cancelled reply or while another job holds the GPU. aien-translate must 331 /// wait and retry, not give up and show the original text. 332 #[tokio::test] 333 async fn busy_engine_is_retried() { 334 let calls = Arc::new(AtomicUsize::new(0)); 335 let c = calls.clone(); 336 let fake = Router::new() 337 .route("/v1/models", get(|| async { Json(json!({"data": [{"id": "fake-model"}]})) })) 338 .route( 339 "/v1/chat/completions", 340 post(move |Json(req): Json| { 341 let c = c.clone(); 342 async move { 343 if c.fetch_add(1, Ordering::SeqCst) < 2 { 344 return axum::response::Response::builder() 345 .status(503) 346 .header("content-type", "application/json") 347 .header("retry-after", "0") 348 .body(axum::body::Body::from( 349 json!({"error": {"message": "one generation at a time: the engine is busy with another request, retry shortly"}}).to_string(), 350 )) 351 .unwrap(); 352 } 353 let items: Vec = 354 serde_json::from_str(req["messages"][1]["content"].as_str().unwrap()).unwrap(); 355 let list = serde_json::to_string(&items.iter().map(|s| format!("ZH:{s}")).collect::>()).unwrap(); 356 axum::response::Response::builder() 357 .header("content-type", "application/json") 358 .body(axum::body::Body::from( 359 json!({"choices": [{"message": {"role": "assistant", "content": list}}]}).to_string(), 360 )) 361 .unwrap() 362 } 363 }), 364 ); 365 let base = start_with(fake).await; 366 let r = post_like_translate_js(&base, &["alpha", "beta"]).await; 367 assert_eq!(r["text"], json!(["ZH:alpha", "ZH:beta"]), "{r}"); 368 assert_eq!(r["aien"]["kept_original"], 0); 369 assert_eq!(calls.load(Ordering::SeqCst), 3, "one request, retried twice"); 370 }