1 //! The request path against a real plugin, a real blob store, and one token.2 //!3 //! The handler is a function of a request, so every test here builds the4 //! request bytes that a client would send and reads the response that the5 //! client would read. The socket is not in the way except in the one test that6 //! speaks HTTP to prove the framing.7 8 use std::collections::BTreeMap;9 use std::io::{Read, Write};10 use std::net::TcpListener;11 use std::os::unix::net::UnixStream;12 use std::sync::Arc;13 use std::sync::atomic::{AtomicU64, Ordering};14 use std::thread;15 use std::time::Duration;16 17 use inf3r_blobs::Blobs;18 use inf3r_core::{Core, Served};19 use inf3r_json::{Value, parse};20 use inf3r_plugin_sdk::capability::{Artifact, Failure, Report, Request as PluginRequest};21 use inf3r_plugin_sdk::emitter::Emitter;22 use inf3r_plugin_sdk::serve::{Plugin, serve};23 use inf3r_proto::body::{24 self, Cancel, Capability, Catalogue, Grant, Model, PartKind, Queue, Ready, Stops, Target,25 };26 use inf3r_proto::mirror;27 use inf3r_server::app::App;28 use inf3r_server::auth::Auth;29 use inf3r_server::{Body, Headers, Limits, Method, Request, Response, Status, Upload};30 31 const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";32 const WAIT: Duration = Duration::from_secs(5);33 const CONNECTIONS: usize = 64;34 35 fn capability(name: &str, parts: &[PartKind], channels: &[&str]) -> Capability {36 Capability {37 vocab: format!("{name}.v1"),38 parts: parts.to_vec(),39 channels: channels.iter().map(|name| (*name).to_string()).collect(),40 limits: BTreeMap::new(),41 cancel: Cancel::Token,42 stops: Stops::Plugin,43 queue: Queue::None,44 }45 }46 47 struct Echo;48 49 impl Plugin for Echo {50 fn max_inflight(&self) -> u16 {51 252 }53 54 fn catalogue(&self) -> Catalogue {55 Catalogue {56 runtime: None,57 target: Target {58 id: "cpu".into(),59 backend: "mock".into(),60 arch: vec![std::env::consts::ARCH.into()],61 devices: 0,62 vram_mb: Vec::new(),63 },64 models: vec![Model {65 serve: "echo".into(),66 alias_of: None,67 weights_bytes: 0,68 load_ms: 0,69 capabilities: BTreeMap::from([70 (71 "chat".to_string(),72 capability(73 "chat",74 &[PartKind::Text, PartKind::Image, PartKind::Json],75 &["text", "image", "progress"],76 ),77 ),78 (79 "embed".to_string(),80 capability("embed", &[PartKind::Text], &["embedding"]),81 ),82 (83 "tts".to_string(),84 capability("tts", &[PartKind::Text], &["pcm", "progress"]),85 ),86 (87 "stt".to_string(),88 capability(89 "stt",90 &[PartKind::Audio, PartKind::Text],91 &["text", "progress"],92 ),93 ),94 (95 "image-gen".to_string(),96 capability(97 "image-gen",98 &[PartKind::Text, PartKind::Image],99 &["image", "progress"],100 ),101 ),102 (103 "image-edit".to_string(),104 capability(105 "image-edit",106 &[PartKind::Image, PartKind::Text],107 &["image", "progress"],108 ),109 ),110 ]),111 }],112 cache: None,113 }114 }115 116 fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {117 Ok(Ready {118 load_ms: 1,119 cache_fingerprint: None,120 })121 }122 123 fn run(124 &self,125 capability: &str,126 req: PluginRequest<'_>,127 out: &mut dyn Emitter,128 ) -> Result<Report, Failure> {129 let fail = |why: inf3r_plugin_sdk::emitter::EmitError| {130 Failure::new(body::ErrorCode::Internal, why.to_string())131 };132 match capability {133 "embed" => {134 let count = req135 .parts136 .iter()137 .filter(|part| part.text().is_some())138 .count();139 if count == 0 {140 return Err(Failure::new(141 body::ErrorCode::Part,142 "embed needs one text part",143 ));144 }145 let vectors: Vec<inf3r_proto::cbor::Value> = (0..count)146 .map(|_| {147 inf3r_proto::cbor::Value::Array(vec![148 inf3r_proto::cbor::Value::Float(1.0),149 inf3r_proto::cbor::Value::Float(2.0),150 ])151 })152 .collect();153 let mut bytes = Vec::new();154 inf3r_proto::cbor::encode(&inf3r_proto::cbor::Value::Array(vectors), &mut bytes);155 out.artifact("embedding", "application/cbor", Artifact::Bytes(bytes))156 .map_err(fail)?;157 let mut usage = BTreeMap::new();158 usage.insert("tokens_in".to_string(), count as u64);159 return Ok(Report {160 usage,161 meta: BTreeMap::new(),162 });163 }164 "tts" => {165 if !req.parts.iter().any(|part| part.text().is_some()) {166 return Err(Failure::new(167 body::ErrorCode::Part,168 "tts needs one text part",169 ));170 }171 out.emit(172 "pcm",173 "audio/pcm; enc=s16le; rate=24000; channels=1",174 b"pcm-audio",175 )176 .map_err(fail)?;177 out.emit(178 "progress",179 "application/json",180 br#"{"stage":"synth","pct":1.0}"#,181 )182 .map_err(fail)?;183 let mut usage = BTreeMap::new();184 usage.insert("tokens_in".to_string(), 2);185 return Ok(Report {186 usage,187 meta: BTreeMap::from([188 (189 "model".to_string(),190 inf3r_proto::Value::Text("echo".to_string()),191 ),192 ("rate".to_string(), inf3r_proto::Value::Uint(24_000)),193 ("channels".to_string(), inf3r_proto::Value::Uint(1)),194 (195 "format".to_string(),196 inf3r_proto::Value::Text("pcm".to_string()),197 ),198 ]),199 });200 }201 "stt" => {202 if !req203 .parts204 .iter()205 .any(|part| part.kind == PartKind::Audio && part.file().is_some())206 {207 return Err(Failure::new(208 body::ErrorCode::Part,209 "stt needs one audio file",210 ));211 }212 out.emit("text", "text/plain; charset=utf-8", b"heard")213 .map_err(fail)?;214 let mut usage = BTreeMap::new();215 usage.insert("tokens_out".to_string(), 2);216 return Ok(Report {217 usage,218 meta: BTreeMap::from([219 (220 "model".to_string(),221 inf3r_proto::Value::Text("echo".to_string()),222 ),223 (224 "language".to_string(),225 inf3r_proto::Value::Text("en".to_string()),226 ),227 ("duration_ms".to_string(), inf3r_proto::Value::Uint(1000)),228 ("segments".to_string(), inf3r_proto::Value::Array(vec![])),229 ]),230 });231 }232 "image-gen" => {233 if !req234 .parts235 .iter()236 .any(|part| part.role == Some("prompt") && part.text().is_some())237 {238 return Err(Failure::new(239 body::ErrorCode::Part,240 "image-gen needs a prompt",241 ));242 }243 return image_report(out).map_err(fail);244 }245 "image-edit" => {246 let source = req.parts.iter().any(|part| {247 part.kind == PartKind::Image248 && part.role == Some("source")249 && part.file().is_some()250 });251 let instruction = req252 .parts253 .iter()254 .any(|part| part.role == Some("instruction") && part.text().is_some());255 if !source || !instruction {256 return Err(Failure::new(257 body::ErrorCode::Part,258 "image-edit needs a source file and an instruction",259 ));260 }261 return image_report(out).map_err(fail);262 }263 _ => {}264 }265 266 if capability == "chat" {267 out.emit("progress", "text/plain; charset=utf-8", b"think")268 .map_err(fail)?;269 }270 for part in req.parts {271 if let Some(text) = part.text() {272 out.emit("text", "text/plain; charset=utf-8", text.as_bytes())273 .map_err(fail)?;274 continue;275 }276 if part.file().is_some() {277 // Copy the descriptor to an artifact without holding it in278 // memory. The test uses this to prove that both directions are279 // descriptors, not inline copies.280 static NEXT: AtomicU64 = AtomicU64::new(1);281 let path = std::env::temp_dir().join(format!(282 "inf3r-artifact-{}-{}",283 std::process::id(),284 NEXT.fetch_add(1, Ordering::Relaxed)285 ));286 let mut file = std::fs::OpenOptions::new()287 .create_new(true)288 .read(true)289 .write(true)290 .open(&path)291 .unwrap();292 let _ = std::fs::remove_file(&path);293 std::io::copy(&mut part.reader(), &mut file).unwrap();294 out.artifact(295 "image",296 "application/octet-stream",297 Artifact::File(file.into()),298 )299 .map_err(fail)?;300 }301 }302 // A non-text channel makes every test job prove that a JSON event303 // survives both the stream and the collected reply. It also carries304 // the params, so a test can see the output spec that the web added.305 let params = inf3r_json::to_string(&mirror::to_json(req.params));306 out.emit("params", "application/json", params.as_bytes())307 .map_err(fail)?;308 let mut usage = BTreeMap::new();309 usage.insert("tokens_out".to_string(), 7);310 usage.insert("first_token_ms".to_string(), 12);311 usage.insert("tokens_per_s".to_string(), 345);312 Ok(Report {313 usage,314 meta: BTreeMap::new(),315 })316 }317 }318 319 /// One image artifact and its usage, shared by the two image capabilities.320 fn image_report(out: &mut dyn Emitter) -> Result<Report, inf3r_plugin_sdk::emitter::EmitError> {321 out.artifact("image", "image/png", Artifact::Bytes(b"png-image".to_vec()))?;322 let mut usage = BTreeMap::new();323 usage.insert("images".to_string(), 1);324 usage.insert("pixels".to_string(), 4);325 Ok(Report {326 usage,327 meta: BTreeMap::from([328 (329 "model".to_string(),330 inf3r_proto::Value::Text("echo".to_string()),331 ),332 ("width".to_string(), inf3r_proto::Value::Uint(2)),333 ("height".to_string(), inf3r_proto::Value::Uint(2)),334 ]),335 })336 }337 338 /// The same plugin, with one capability that stops only at a frame boundary.339 ///340 /// A background job may not use that degradation, so the core must refuse it341 /// before the plugin ever sees it.342 struct Degraded;343 344 impl Plugin for Degraded {345 fn max_inflight(&self) -> u16 {346 2347 }348 349 fn catalogue(&self) -> Catalogue {350 let mut catalogue = Echo.catalogue();351 catalogue.models[0].serve = "degraded".to_string();352 if let Some(capability) = catalogue.models[0].capabilities.get_mut("chat") {353 capability.cancel = Cancel::Frame;354 }355 catalogue356 }357 358 fn load(&self, grant: &Grant) -> Result<Ready, Failure> {359 Echo.load(grant)360 }361 362 fn run(363 &self,364 capability: &str,365 req: PluginRequest<'_>,366 out: &mut dyn Emitter,367 ) -> Result<Report, Failure> {368 Echo.run(capability, req, out)369 }370 }371 372 /// An app over an echo plugin, a blob store in a temporary directory, and one373 /// token.374 fn app() -> (App, std::path::PathBuf) {375 app_with(Echo)376 }377 378 /// An app over any test plugin, a blob store in a temporary directory, and one379 /// token. The plugin id stays `echo`; the model names come from its catalogue.380 fn app_with<P: Plugin + 'static>(plugin: P) -> (App, std::path::PathBuf) {381 let (caller, serving) = UnixStream::pair().unwrap();382 thread::spawn(move || serve(serving, Arc::new(plugin)));383 let peer = Served::connect("echo", caller, "web-test", &[], WAIT).expect("connect");384 let core = Arc::new(Core::new());385 core.register(peer).expect("register");386 387 static NEXT: AtomicU64 = AtomicU64::new(1);388 let dir = std::env::temp_dir().join(format!(389 "inf3r-web-{}-{}",390 std::process::id(),391 NEXT.fetch_add(1, Ordering::Relaxed)392 ));393 let _ = std::fs::remove_dir_all(&dir);394 std::fs::create_dir_all(&dir).unwrap();395 let blobs = Blobs::open(&dir, 8 << 20).unwrap();396 let auth = Auth::from_token(TOKEN).unwrap();397 (App::new(core, blobs, auth), dir)398 }399 400 /// An app with one live and one cold model.401 fn app_with_cold() -> (App, std::path::PathBuf) {402 let (caller, serving) = UnixStream::pair().unwrap();403 thread::spawn(move || serve(serving, Arc::new(Echo)));404 let peer = Served::connect("echo", caller, "web-test", &[], WAIT).expect("connect");405 let core = Arc::new(Core::new());406 core.register(peer).expect("register");407 let mut cold = Echo.catalogue();408 cold.models[0].serve = "cold".to_string();409 core.register_cold("cold/cpu", &cold, 1)410 .expect("the cold catalogue");411 412 static NEXT: AtomicU64 = AtomicU64::new(1);413 let dir = std::env::temp_dir().join(format!(414 "inf3r-web-cold-{}-{}",415 std::process::id(),416 NEXT.fetch_add(1, Ordering::Relaxed)417 ));418 let _ = std::fs::remove_dir_all(&dir);419 std::fs::create_dir_all(&dir).unwrap();420 let blobs = Blobs::open(&dir, 8 << 20).unwrap();421 let auth = Auth::from_token(TOKEN).unwrap();422 (App::new(core, blobs, auth), dir)423 }424 425 fn headers(auth: bool) -> Headers {426 let mut headers = Headers::new();427 if auth {428 headers.push("authorization", &format!("Bearer {TOKEN}"));429 }430 headers431 }432 433 fn request(method: Method, target: &str, body: &str, auth: bool) -> Request {434 Request {435 method,436 target: target.to_string(),437 peer_uid: None,438 headers: headers(auth),439 body: body.as_bytes().to_vec(),440 upload: None,441 }442 }443 444 fn body_text(response: &Response) -> String {445 match &response.body {446 Body::Bytes(bytes) => String::from_utf8(bytes.clone()).unwrap(),447 Body::Chunks(_) => panic!("the response is a stream"),448 }449 }450 451 fn body_bytes(response: Response) -> Vec<u8> {452 match response.body {453 Body::Bytes(bytes) => bytes,454 Body::Chunks(chunks) => {455 let mut out = Vec::new();456 for chunk in chunks {457 out.extend_from_slice(&chunk.unwrap());458 }459 out460 }461 }462 }463 464 fn chat(stream: bool) -> String {465 format!(r#"{{"model":"echo","input":[{{"kind":"text","text":"hello"}}],"stream":{stream}}}"#)466 }467 468 #[test]469 fn healthz_needs_no_token() {470 let (app, dir) = app();471 let response = app.handle(request(Method::Get, "/healthz", "", false));472 assert_eq!(response.status, Status::OK);473 assert_eq!(body_text(&response), r#"{"status":"ok"}"#);474 let _ = std::fs::remove_dir_all(dir);475 }476 477 #[test]478 fn every_other_route_needs_the_token() {479 let (app, dir) = app();480 let response = app.handle(request(Method::Post, "/chat", &chat(false), false));481 assert_eq!(response.status, Status::UNAUTHORIZED);482 assert_eq!(483 response484 .headers485 .iter()486 .find(|(name, _)| name == "www-authenticate")487 .map(|(_, value)| value.as_str()),488 Some("Bearer")489 );490 let body = body_text(&response);491 assert!(body.contains(r#""code":"unauthorized""#), "{body}");492 assert!(body.contains(r#""request_id":"#), "{body}");493 let _ = std::fs::remove_dir_all(dir);494 }495 496 #[test]497 fn a_job_without_a_stream_is_one_object() {498 let (app, dir) = app();499 let response = app.handle(request(Method::Post, "/chat", &chat(false), true));500 assert_eq!(response.status, Status::OK);501 let body = body_text(&response);502 assert!(body.contains(r#""status":"completed""#), "{body}");503 assert!(body.contains(r#""output":"hello""#), "{body}");504 let _ = std::fs::remove_dir_all(dir);505 }506 507 #[test]508 fn a_streamed_job_is_sse_frames_and_one_done() {509 let (app, dir) = app();510 let response = app.handle(request(Method::Post, "/chat", &chat(true), true));511 assert_eq!(response.status, Status::OK);512 assert_eq!(513 response514 .headers515 .iter()516 .find(|(name, _)| name == "content-type")517 .map(|(_, value)| value.as_str()),518 Some("text/event-stream; charset=utf-8")519 );520 let bytes = body_bytes(response);521 let text = String::from_utf8(bytes).unwrap();522 assert!(text.starts_with(": ping\n\n"), "{text}");523 assert!(text.ends_with("data: [DONE]\n\n"), "{text}");524 // Every frame is a comment or one `data: ` line, then one blank line.525 for frame in text.split("\n\n").filter(|frame| !frame.is_empty()) {526 assert!(527 frame.starts_with("data: ") || frame.starts_with(": "),528 "{frame}"529 );530 }531 assert!(text.contains(r#""t":"started""#), "{text}");532 assert!(text.contains(r#""t":"delta""#), "{text}");533 assert!(text.contains(r#""t":"done""#), "{text}");534 535 let usage = text.find(r#""t":"usage""#).expect("a usage event");536 let done = text.find(r#""t":"done""#).expect("a done event");537 assert!(usage < done, "usage must precede done\n{text}");538 assert!(text.contains(r#""tokens_out":7"#), "{text}");539 let _ = std::fs::remove_dir_all(dir);540 }541 542 #[test]543 fn a_request_id_from_the_client_is_echoed() {544 let (app, dir) = app();545 let mut request = request(Method::Post, "/chat", &chat(false), true);546 request.headers.push("x-request-id", "abc-123");547 let response = app.handle(request);548 assert!(549 body_text(&response).contains(r#""request_id":"abc-123""#),550 "{}",551 body_text(&response)552 );553 let _ = std::fs::remove_dir_all(dir);554 }555 556 #[test]557 fn an_unknown_route_is_a_not_found() {558 let (app, dir) = app();559 let response = app.handle(request(Method::Get, "/v2/chat", "", true));560 assert_eq!(response.status, Status::NOT_FOUND);561 assert!(body_text(&response).contains(r#""code":"not_found""#));562 let _ = std::fs::remove_dir_all(dir);563 }564 565 #[test]566 fn a_wrong_method_is_a_method_not_allowed() {567 let (app, dir) = app();568 let response = app.handle(request(Method::Get, "/chat", "", true));569 assert_eq!(response.status, Status::METHOD_NOT_ALLOWED);570 let _ = std::fs::remove_dir_all(dir);571 }572 573 #[test]574 fn an_unknown_model_is_the_refusal_shape() {575 let (app, dir) = app();576 let body = r#"{"model":"absent","input":[{"kind":"text","text":"x"}],"stream":false}"#;577 let response = app.handle(request(Method::Post, "/chat", body, true));578 assert_eq!(response.status, Status::NOT_FOUND);579 let body = body_text(&response);580 assert!(body.contains(r#""code":"unknown_model""#), "{body}");581 assert!(body.contains(r#""retryable":false"#), "{body}");582 let _ = std::fs::remove_dir_all(dir);583 }584 585 #[test]586 fn a_finished_job_is_in_the_table_and_a_cancel_of_an_unknown_job_is_a_not_found() {587 let (app, dir) = app();588 let _ = app.handle(request(Method::Post, "/chat", &chat(false), true));589 590 let listed = app.handle(request(Method::Get, "/jobs", "", true));591 let body = body_text(&listed);592 assert!(body.contains(r#""state":"completed""#), "{body}");593 assert!(body.contains(r#""running":0"#), "{body}");594 595 let id = body596 .split(r#""id":""#)597 .nth(1)598 .and_then(|rest| rest.split('"').next())599 .expect("an id")600 .to_string();601 let one = app.handle(request(Method::Get, &format!("/jobs/{id}"), "", true));602 assert_eq!(one.status, Status::OK);603 assert!(body_text(&one).contains(r#""model":"echo""#));604 605 let absent = app.handle(request(Method::Delete, "/jobs/j-ffffffff", "", true));606 assert_eq!(absent.status, Status::NOT_FOUND);607 let _ = std::fs::remove_dir_all(dir);608 }609 610 #[test]611 fn an_openai_request_is_one_completion() {612 let (app, dir) = app();613 let body = r#"{"model":"echo","messages":[{"role":"user","content":"hello"}]}"#;614 let response = app.handle(request(615 Method::Post,616 "/openai/v1/chat/completions",617 body,618 true,619 ));620 assert_eq!(response.status, Status::OK);621 let body = body_text(&response);622 assert!(body.contains(r#""object":"chat.completion""#), "{body}");623 assert!(body.contains(r#""content":"hello""#), "{body}");624 assert!(body.contains(r#""finish_reason":"stop""#), "{body}");625 assert!(body.contains(r#""completion_tokens":7"#), "{body}");626 assert!(body.contains(r#""prompt_tokens":0"#), "{body}");627 let _ = std::fs::remove_dir_all(dir);628 }629 630 #[test]631 fn an_openai_stream_is_chunks_and_one_finish() {632 let (app, dir) = app();633 let body = r#"{"model":"echo","messages":[{"role":"user","content":"hello"}],"stream":true}"#;634 let response = app.handle(request(635 Method::Post,636 "/openai/v1/chat/completions",637 body,638 true,639 ));640 assert_eq!(response.status, Status::OK);641 let text = String::from_utf8(body_bytes(response)).unwrap();642 assert!(643 text.contains(r#""object":"chat.completion.chunk""#),644 "{text}"645 );646 assert!(text.contains(r#""delta":{"content":"hello"}"#), "{text}");647 assert!(text.contains(r#""finish_reason":"stop""#), "{text}");648 assert!(text.ends_with("data: [DONE]\n\n"), "{text}");649 let _ = std::fs::remove_dir_all(dir);650 }651 652 #[test]653 fn an_openai_request_accepts_standard_fields_and_ignores_unknown_ones() {654 let (app, dir) = app();655 let body = r#"{"model":"echo","messages":[{"role":"developer","content":"hi"}],656 "tools":[{"type":"function","function":{"name":"lookup"}}],657 "response_format":{"type":"json_object"},"logprobs":true,658 "max_completion_tokens":9,"stream_options":{"include_usage":true},659 "user":"u","future_field":1}"#;660 let response = app.handle(request(661 Method::Post,662 "/openai/v1/chat/completions",663 body,664 true,665 ));666 assert_eq!(response.status, Status::OK, "{}", body_text(&response));667 let text = body_text(&response);668 assert!(text.contains(r#""content":"hi""#), "{text}");669 let _ = std::fs::remove_dir_all(dir);670 }671 672 /// One multipart field: its name, filename, media type, and bytes.673 type MultipartField<'a> = (&'a str, Option<&'a str>, Option<&'a str>, &'a [u8]);674 675 /// One multipart body.676 fn multipart(boundary: &str, fields: &[MultipartField<'_>]) -> Vec<u8> {677 let mut body = Vec::new();678 for (name, filename, mime, bytes) in fields {679 body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());680 let mut disposition = format!("Content-Disposition: form-data; name=\"{name}\"");681 if let Some(filename) = filename {682 disposition.push_str(&format!("; filename=\"{filename}\""));683 }684 body.extend_from_slice(disposition.as_bytes());685 body.extend_from_slice(b"\r\n");686 if let Some(mime) = mime {687 body.extend_from_slice(format!("Content-Type: {mime}\r\n").as_bytes());688 }689 body.extend_from_slice(b"\r\n");690 body.extend_from_slice(bytes);691 body.extend_from_slice(b"\r\n");692 }693 body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());694 body695 }696 697 fn multipart_request(target: &str, boundary: &str, body: Vec<u8>) -> Request {698 let mut request = request(Method::Post, target, "", true);699 request.headers.push(700 "content-type",701 &format!("multipart/form-data; boundary={boundary}"),702 );703 request.body = body;704 request705 }706 707 fn upload_request(target: &str, boundary: &str, body: Vec<u8>) -> Request {708 static NEXT: AtomicU64 = AtomicU64::new(1);709 let path = std::env::temp_dir().join(format!(710 "inf3r-upload-test-{}-{}",711 std::process::id(),712 NEXT.fetch_add(1, Ordering::Relaxed)713 ));714 std::fs::write(&path, &body).unwrap();715 let file = std::fs::OpenOptions::new()716 .read(true)717 .write(true)718 .open(&path)719 .unwrap();720 let _ = std::fs::remove_file(&path);721 let mut request = request(Method::Post, target, "", true);722 request.headers.push(723 "content-type",724 &format!("multipart/form-data; boundary={boundary}"),725 );726 request.body = Vec::new();727 request.upload = Some(Upload {728 file,729 len: body.len() as u64,730 });731 request732 }733 734 #[test]735 fn an_openai_model_list_has_the_served_names() {736 let (app, dir) = app();737 let response = app.handle(request(Method::Get, "/openai/v1/models", "", true));738 assert_eq!(response.status, Status::OK);739 let body = body_text(&response);740 let root = parse(&body).expect("json");741 assert_eq!(root.get("object").and_then(Value::as_str), Some("list"));742 let ids: Vec<&str> = root743 .get("data")744 .and_then(Value::as_array)745 .expect("data")746 .iter()747 .filter_map(|model| model.get("id").and_then(Value::as_str))748 .collect();749 assert_eq!(ids, ["echo"]);750 let _ = std::fs::remove_dir_all(dir);751 }752 753 #[test]754 fn an_openai_stream_carries_reasoning_and_requested_usage() {755 let (app, dir) = app();756 let body = r#"{"model":"echo","messages":[{"role":"user","content":"hello"}],757 "stream":true,"stream_options":{"include_usage":true}}"#;758 let response = app.handle(request(759 Method::Post,760 "/openai/v1/chat/completions",761 body,762 true,763 ));764 assert_eq!(response.status, Status::OK);765 let text = String::from_utf8(body_bytes(response)).unwrap();766 assert!(text.contains(r#""reasoning_content":"think""#), "{text}");767 assert!(text.contains(r#""delta":{"content":"hello"}"#), "{text}");768 assert!(text.contains(r#""usage":{"completion_tokens":7"#), "{text}");769 assert!(text.contains(r#""choices":[]"#), "{text}");770 assert!(text.ends_with("data: [DONE]\n\n"), "{text}");771 let _ = std::fs::remove_dir_all(dir);772 }773 774 #[test]775 fn an_openai_embedding_is_the_cbor_array_as_json() {776 let (app, dir) = app();777 let body = r#"{"model":"echo","input":["a","b"]}"#;778 let response = app.handle(request(Method::Post, "/openai/v1/embeddings", body, true));779 assert_eq!(response.status, Status::OK, "{}", body_text(&response));780 let root = parse(&body_text(&response)).expect("json");781 let data = root.get("data").and_then(Value::as_array).expect("data");782 assert_eq!(data.len(), 2);783 assert_eq!(784 data[0]785 .get("embedding")786 .and_then(Value::as_array)787 .expect("embedding")788 .iter()789 .filter_map(Value::as_f64)790 .collect::<Vec<_>>(),791 [1.0, 2.0]792 );793 assert_eq!(794 root.get("usage")795 .and_then(|usage| usage.get("prompt_tokens"))796 .and_then(Value::as_u64),797 Some(2)798 );799 let _ = std::fs::remove_dir_all(dir);800 }801 802 #[test]803 fn an_openai_embedding_can_be_base64_floats() {804 let (app, dir) = app();805 let body = r#"{"model":"echo","input":["a"],"encoding_format":"base64"}"#;806 let response = app.handle(request(Method::Post, "/openai/v1/embeddings", body, true));807 assert_eq!(response.status, Status::OK, "{}", body_text(&response));808 let root = parse(&body_text(&response)).expect("json");809 let encoded = root810 .get("data")811 .and_then(Value::as_array)812 .and_then(|data| data.first())813 .and_then(|row| row.get("embedding"))814 .and_then(Value::as_str)815 .expect("base64 embedding");816 let bytes = inf3r_json::b64::decode(encoded).expect("base64");817 assert_eq!(bytes.len(), 8);818 assert_eq!(f32::from_le_bytes(bytes[0..4].try_into().unwrap()), 1.0);819 let _ = std::fs::remove_dir_all(dir);820 }821 822 #[test]823 fn an_openai_speech_reply_is_audio_bytes() {824 let (app, dir) = app();825 let body = r#"{"model":"echo","input":"hello","voice":"warm","response_format":"pcm"}"#;826 let response = app.handle(request(Method::Post, "/openai/v1/audio/speech", body, true));827 assert_eq!(response.status, Status::OK);828 assert_eq!(829 response830 .headers831 .iter()832 .find(|(name, _)| name == "content-type")833 .map(|(_, value)| value.as_str()),834 Some("audio/pcm; enc=s16le; rate=24000; channels=1")835 );836 assert_eq!(body_bytes(response), b"pcm-audio");837 let _ = std::fs::remove_dir_all(dir);838 }839 840 #[test]841 fn an_openai_image_generation_is_base64_images() {842 let (app, dir) = app();843 let body = r#"{"model":"echo","prompt":"a cat","n":2}"#;844 let response = app.handle(request(845 Method::Post,846 "/openai/v1/images/generations",847 body,848 true,849 ));850 assert_eq!(response.status, Status::OK, "{}", body_text(&response));851 let root = parse(&body_text(&response)).expect("json");852 let data = root.get("data").and_then(Value::as_array).expect("data");853 assert_eq!(data.len(), 2);854 let encoded = data[0]855 .get("b64_json")856 .and_then(Value::as_str)857 .expect("base64");858 assert_eq!(859 inf3r_json::b64::decode(encoded).unwrap(),860 b"png-image".to_vec()861 );862 let _ = std::fs::remove_dir_all(dir);863 }864 865 #[test]866 fn an_openai_transcription_takes_a_multipart_file() {867 let (app, dir) = app();868 let boundary = "inf3r-boundary";869 let body = multipart(870 boundary,871 &[872 ("model", None, None, b"echo"),873 ("language", None, None, b"en"),874 ("timestamp_granularities[]", None, None, b"segment"),875 ("response_format", None, None, b"verbose_json"),876 (877 "file",878 Some("clip.wav"),879 Some("audio/wav"),880 b"not really a wav",881 ),882 ],883 );884 let response = app.handle(multipart_request(885 "/openai/v1/audio/transcriptions",886 boundary,887 body,888 ));889 assert_eq!(response.status, Status::OK, "{}", body_text(&response));890 let root = parse(&body_text(&response)).expect("json");891 assert_eq!(root.get("text").and_then(Value::as_str), Some("heard"));892 assert_eq!(root.get("language").and_then(Value::as_str), Some("en"));893 assert!(root.get("segments").is_some(), "{root:?}");894 let _ = std::fs::remove_dir_all(dir);895 }896 897 #[test]898 fn an_openai_transcription_reads_a_spooled_multipart_body() {899 let (app, dir) = app();900 let boundary = "inf3r-large-boundary";901 let audio = vec![b'a'; (1 << 20) + 1];902 let body = multipart(903 boundary,904 &[905 ("model", None, None, b"echo"),906 ("file", Some("clip.wav"), Some("audio/wav"), &audio),907 ],908 );909 let response = app.handle(upload_request(910 "/openai/v1/audio/transcriptions",911 boundary,912 body,913 ));914 assert_eq!(response.status, Status::OK, "{}", body_text(&response));915 assert!(body_text(&response).contains(r#""text":"heard""#));916 let _ = std::fs::remove_dir_all(dir);917 }918 919 #[test]920 fn an_openai_image_edit_takes_a_source_and_a_mask() {921 let (app, dir) = app();922 let boundary = "inf3r-edit-boundary";923 let body = multipart(924 boundary,925 &[926 ("model", None, None, b"echo"),927 ("prompt", None, None, b"storm"),928 ("image", Some("source.png"), Some("image/png"), b"source"),929 ("mask", Some("mask.png"), Some("image/png"), b"mask"),930 ],931 );932 let response = app.handle(multipart_request("/openai/v1/images/edits", boundary, body));933 assert_eq!(response.status, Status::OK, "{}", body_text(&response));934 assert!(body_text(&response).contains(r#""data":[{"b64_json":"#));935 let _ = std::fs::remove_dir_all(dir);936 }937 938 #[test]939 fn an_openai_server_error_is_not_an_invalid_request() {940 let (app, dir) = app_with_cold();941 let body = r#"{"model":"cold","messages":[{"role":"user","content":"hi"}]}"#;942 let response = app.handle(request(943 Method::Post,944 "/openai/v1/chat/completions",945 body,946 true,947 ));948 assert!(response.status.0 >= 500, "{}", response.status.0);949 let body = body_text(&response);950 assert!(body.contains(r#""type":"server_error""#), "{body}");951 let _ = std::fs::remove_dir_all(dir);952 }953 954 #[test]955 fn an_openai_route_needs_the_token_in_the_openai_error_shape() {956 let (app, dir) = app();957 let response = app.handle(request(958 Method::Post,959 "/openai/v1/chat/completions",960 "{}",961 false,962 ));963 assert_eq!(response.status, Status::UNAUTHORIZED);964 let body = body_text(&response);965 assert!(body.contains(r#""type":"authentication_error""#), "{body}");966 assert!(body.contains(r#""code":"invalid_api_key""#), "{body}");967 let _ = std::fs::remove_dir_all(dir);968 }969 970 #[test]971 fn a_blob_round_trips() {972 let (app, dir) = app();973 let posted = app.handle(request(Method::Post, "/blobs", "the bytes", true));974 assert_eq!(975 posted.status,976 Status::CREATED,977 "{}",978 match &posted.body {979 Body::Bytes(bytes) => String::from_utf8_lossy(bytes).into_owned(),980 Body::Chunks(_) => "a stream".to_string(),981 }982 );983 let body = body_text(&posted);984 let id = body985 .split(r#""id":""#)986 .nth(1)987 .and_then(|rest| rest.split('"').next())988 .expect("an id");989 assert_eq!(id.len(), 64);990 991 let got = app.handle(request(Method::Get, &format!("/blobs/{id}"), "", true));992 assert_eq!(got.status, Status::OK);993 assert_eq!(body_bytes(got), b"the bytes");994 995 let absent = app.handle(request(996 Method::Get,997 &format!("/blobs/{}", "0".repeat(64)),998 "",999 true,1000 ));1001 assert_eq!(absent.status, Status::NOT_FOUND);1002 let _ = std::fs::remove_dir_all(dir);1003 }1004 1005 #[test]1006 fn a_blob_part_and_its_artifact_travel_as_descriptors() {1007 let (app, dir) = app();1008 let payload: Vec<u8> = (0..(2 << 20)).map(|index| (index % 251) as u8).collect();1009 let posted = app.handle(Request {1010 method: Method::Post,1011 target: "/blobs".to_string(),1012 peer_uid: None,1013 headers: headers(true),1014 body: payload.clone(),1015 upload: None,1016 });1017 assert_eq!(posted.status, Status::CREATED);1018 let body = body_text(&posted);1019 let id = body1020 .split(r#""id":""#)1021 .nth(1)1022 .and_then(|rest| rest.split('"').next())1023 .expect("an id")1024 .to_string();1025 1026 let job = format!(1027 r#"{{"model":"echo","input":[{{"kind":"image","mime":"application/octet-stream","blob":"{id}"}}],"stream":false}}"#1028 );1029 let response = app.handle(request(Method::Post, "/chat", &job, true));1030 assert_eq!(response.status, Status::OK, "{}", body_text(&response));1031 let body = body_text(&response);1032 assert!(body.contains(r#""bytes":2097152"#), "{body}");1033 assert!(body.contains(r#""channel":"image""#), "{body}");1034 let artifact = body1035 .split(r#""blob":""#)1036 .nth(1)1037 .and_then(|rest| rest.split('"').next())1038 .unwrap_or_else(|| panic!("no artifact in {body}"))1039 .to_string();1040 1041 let got = app.handle(request(1042 Method::Get,1043 &format!("/blobs/{artifact}"),1044 "",1045 true,1046 ));1047 assert_eq!(got.status, Status::OK);1048 assert_eq!(body_bytes(got), payload);1049 let _ = std::fs::remove_dir_all(dir);1050 }1051 1052 #[test]1053 fn models_lists_the_served_name_and_its_capability() {1054 let (app, dir) = app();1055 let response = app.handle(request(Method::Get, "/models", "", true));1056 let body = body_text(&response);1057 assert!(body.contains(r#""serve":"echo""#), "{body}");1058 assert!(body.contains(r#""name":"chat""#), "{body}");1059 assert!(body.contains(r#""vocab":"chat.v1""#), "{body}");1060 assert!(body.contains(r#""degraded":false"#), "{body}");1061 assert!(body.contains(r#""cancel":"token""#), "{body}");1062 let _ = std::fs::remove_dir_all(dir);1063 }1064 1065 #[test]1066 fn a_blob_above_the_buffer_reaches_the_store_over_http() {1067 let (app, dir) = app();1068 let listener = TcpListener::bind("127.0.0.1:0").unwrap();1069 let address = listener.local_addr().unwrap();1070 thread::spawn(move || {1071 inf3r_server::serve(1072 listener,1073 Limits {1074 max_head_bytes: 8 << 10,1075 max_body_bytes: 1 << 20,1076 max_upload_bytes: 4 << 20,1077 read_timeout: WAIT,1078 head_timeout: WAIT,1079 write_timeout: WAIT,1080 max_connections: CONNECTIONS,1081 },1082 move |request| app.handle(request),1083 )1084 });1085 1086 let payload = vec![b'z'; 2 << 20];1087 let head = format!(1088 "POST /blobs HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",1089 payload.len()1090 );1091 let mut stream = std::net::TcpStream::connect(address).unwrap();1092 stream.write_all(head.as_bytes()).unwrap();1093 stream.write_all(&payload).unwrap();1094 let mut response = String::new();1095 stream.read_to_string(&mut response).unwrap();1096 assert!(1097 response.starts_with("HTTP/1.1 201 Created\r\n"),1098 "{response}"1099 );1100 assert!(response.contains(r#""bytes":2097152"#), "{response}");1101 let _ = std::fs::remove_dir_all(dir);1102 }1103 1104 #[test]1105 fn the_transport_frames_a_stream_over_a_socket() {1106 let (app, dir) = app();1107 let listener = TcpListener::bind("127.0.0.1:0").unwrap();1108 let address = listener.local_addr().unwrap();1109 thread::spawn(move || {1110 inf3r_server::serve(1111 listener,1112 Limits {1113 max_head_bytes: 8 << 10,1114 max_body_bytes: 1 << 20,1115 max_upload_bytes: 4 << 20,1116 read_timeout: WAIT,1117 head_timeout: WAIT,1118 write_timeout: WAIT,1119 max_connections: CONNECTIONS,1120 },1121 move |request| app.handle(request),1122 )1123 });1124 1125 let body = chat(true);1126 let request = format!(1127 "POST /chat HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",1128 body.len()1129 );1130 let mut stream = std::net::TcpStream::connect(address).unwrap();1131 stream.write_all(request.as_bytes()).unwrap();1132 let mut response = String::new();1133 stream.read_to_string(&mut response).unwrap();1134 1135 assert!(response.starts_with("HTTP/1.1 200 OK\r\n"), "{response}");1136 assert!(1137 response.contains("transfer-encoding: chunked\r\n")1138 || response.contains("Transfer-Encoding: chunked\r\n"),1139 "{response}"1140 );1141 assert!(response.ends_with("0\r\n\r\n"), "{response}");1142 assert!(response.contains("data: [DONE]"), "{response}");1143 let _ = std::fs::remove_dir_all(dir);1144 }1145 1146 #[test]1147 fn stats_reports_a_cold_model_without_a_peer() {1148 let (app, dir) = app_with_cold();1149 let response = app.handle(request(Method::Get, "/stats", "", true));1150 assert_eq!(response.status, Status::OK);1151 let body = body_text(&response);1152 let root = parse(&body).expect("json");1153 let peers = root1154 .get("peers")1155 .and_then(Value::as_array)1156 .expect("a peers array");1157 assert_eq!(peers.len(), 2, "{body}");1158 let cold = peers1159 .iter()1160 .find(|row| row.get("model").and_then(Value::as_str) == Some("cold"))1161 .expect("the cold row");1162 assert_eq!(cold.get("plugin").and_then(Value::as_str), Some("cold/cpu"));1163 assert_eq!(cold.get("in_flight").and_then(Value::as_i64), Some(0));1164 let _ = std::fs::remove_dir_all(dir);1165 }1166 1167 #[test]1168 fn stats_has_one_engine_row_without_nulls() {1169 let (app, dir) = app();1170 let response = app.handle(request(Method::Get, "/stats", "", true));1171 assert_eq!(response.status, Status::OK);1172 let body = body_text(&response);1173 let root = parse(&body).expect("json");1174 let engines = root1175 .get("engines")1176 .and_then(Value::as_array)1177 .expect("an engines array");1178 assert_eq!(engines.len(), 1);1179 let row = &engines[0];1180 for key in [1181 "plugin",1182 "served",1183 "slots",1184 "in_flight",1185 "queued",1186 "declared_bytes",1187 ] {1188 assert!(row.get(key).is_some(), "no {key} in {body}");1189 }1190 assert_eq!(row.get("plugin").and_then(Value::as_str), Some("echo"));1191 assert_eq!(row.get("slots").and_then(Value::as_i64), Some(2));1192 assert_eq!(row.get("in_flight").and_then(Value::as_i64), Some(0));1193 assert_eq!(row.get("queued").and_then(Value::as_i64), Some(0));1194 assert_eq!(row.get("declared_bytes").and_then(Value::as_i64), Some(0));1195 assert!(row.get("tokens_out").is_none(), "{body}");1196 assert!(!body.contains("null"), "{body}");1197 let _ = std::fs::remove_dir_all(dir);1198 }1199 1200 #[test]1201 fn reload_names_an_unknown_bundle_without_stopping_the_host() {1202 let (app, dir) = app();1203 let response = app.handle(request(1204 Method::Post,1205 "/reload",1206 r#"{"bundle":"missing/cpu"}"#,1207 true,1208 ));1209 assert_eq!(response.status, Status::OK);1210 let body = body_text(&response);1211 let root = parse(&body).expect("json");1212 assert_eq!(1213 root.get("reloaded")1214 .and_then(Value::as_array)1215 .map(<[_]>::len),1216 Some(0)1217 );1218 let failed = root1219 .get("failed")1220 .and_then(Value::as_array)1221 .expect("a failed array");1222 assert_eq!(1223 failed[0].get("bundle").and_then(Value::as_str),1224 Some("missing/cpu")1225 );1226 assert_eq!(1227 failed[0].get("error").and_then(Value::as_str),1228 Some("no such bundle")1229 );1230 let stats = app.handle(request(Method::Get, "/stats", "", true));1231 assert_eq!(stats.status, Status::OK);1232 let _ = std::fs::remove_dir_all(dir);1233 }1234 1235 #[test]1236 fn a_reload_path_names_one_bundle() {1237 let (app, dir) = app();1238 let response = app.handle(request(Method::Post, "/reload/missing/cpu", "", true));1239 assert_eq!(response.status, Status::OK);1240 let body = body_text(&response);1241 assert!(body.contains(r#""bundle":"missing/cpu""#), "{body}");1242 assert!(body.contains("no such bundle"), "{body}");1243 let _ = std::fs::remove_dir_all(dir);1244 }1245 1246 #[test]1247 fn a_reload_body_that_is_not_an_object_is_bad_request() {1248 let (app, dir) = app();1249 let response = app.handle(request(Method::Post, "/reload", "[]", true));1250 assert_eq!(response.status, Status::BAD_REQUEST);1251 let body = body_text(&response);1252 assert!(body.contains("bad_request"), "{body}");1253 let _ = std::fs::remove_dir_all(dir);1254 }1255 1256 #[test]1257 fn a_query_string_is_not_a_route() {1258 let (app, dir) = app();1259 let response = app.handle(request(Method::Get, "/healthz?full=1", "", true));1260 assert_eq!(response.status, Status::NOT_FOUND);1261 let body = body_text(&response);1262 assert!(body.contains("not_found"), "{body}");1263 let _ = std::fs::remove_dir_all(dir);1264 }1265 1266 #[test]1267 fn delete_without_a_job_id_is_method_not_allowed() {1268 let (app, dir) = app();1269 let response = app.handle(request(Method::Delete, "/jobs", "", true));1270 assert_eq!(response.status, Status::METHOD_NOT_ALLOWED);1271 let body = body_text(&response);1272 assert!(body.contains("method_not_allowed"), "{body}");1273 let _ = std::fs::remove_dir_all(dir);1274 }1275 1276 #[test]1277 fn a_non_streaming_job_keeps_non_text_events_the_output_spec_and_usage() {1278 let (app, dir) = app();1279 let body = r#"{"model":"echo","input":[{"kind":"text","text":"hello"}],"params":{"steps":4},"output":{"image":{"mime":"image/png"}},"stream":false}"#;1280 let response = app.handle(request(Method::Post, "/chat", body, true));1281 assert_eq!(response.status, Status::OK, "{}", body_text(&response));1282 let text = body_text(&response);1283 let root = parse(&text).expect("json");1284 assert_eq!(root.get("output").and_then(Value::as_str), Some("hello"));1285 1286 let usage = root.get("usage").expect("usage");1287 assert_eq!(usage.get("tokens_out").and_then(Value::as_u64), Some(7));1288 assert_eq!(1289 usage.get("first_token_ms").and_then(Value::as_u64),1290 Some(12)1291 );1292 1293 let events = root1294 .get("events")1295 .and_then(Value::as_array)1296 .expect("non-text events");1297 let params = events1298 .iter()1299 .find(|event| event.get("channel").and_then(Value::as_str) == Some("params"))1300 .expect("the params event");1301 assert_eq!(1302 params.get("mime").and_then(Value::as_str),1303 Some("application/json")1304 );1305 let encoded = params1306 .get("b64")1307 .and_then(Value::as_str)1308 .expect("base64 bytes");1309 let decoded = inf3r_json::b64::decode(encoded).expect("valid base64");1310 let params: Value = parse(std::str::from_utf8(&decoded).expect("utf8")).expect("json");1311 assert_eq!(params.get("steps").and_then(Value::as_u64), Some(4));1312 assert_eq!(1313 params1314 .get("output")1315 .and_then(|output| output.get("image"))1316 .and_then(|image| image.get("mime"))1317 .and_then(Value::as_str),1318 Some("image/png")1319 );1320 let _ = std::fs::remove_dir_all(dir);1321 }1322 1323 #[test]1324 fn a_background_job_cannot_use_a_degraded_capability() {1325 let (app, dir) = app_with(Degraded);1326 let body = r#"{"model":"degraded","input":[{"kind":"text","text":"hello"}],"stream":false,"priority":"background"}"#;1327 let response = app.handle(request(Method::Post, "/chat", body, true));1328 assert_eq!(response.status, Status::BAD_REQUEST);1329 let text = body_text(&response);1330 assert!(text.contains(r#""code":"capability_missing""#), "{text}");1331 assert!(text.contains("degraded"), "{text}");1332 1333 let body = r#"{"model":"degraded","input":[{"kind":"text","text":"hello"}],"stream":false,"priority":"interactive"}"#;1334 let response = app.handle(request(Method::Post, "/chat", body, true));1335 assert_eq!(response.status, Status::OK, "{}", body_text(&response));1336 let _ = std::fs::remove_dir_all(dir);1337 }1338 1339 #[test]1340 fn the_canonical_image_route_serves_the_capability() {1341 let (app, dir) = app();1342 let body =1343 r#"{"model":"echo","input":[{"kind":"text","role":"prompt","text":"cat"}],"stream":false}"#;1344 let response = app.handle(request(Method::Post, "/image/generate", body, true));1345 assert_eq!(response.status, Status::OK, "{}", body_text(&response));1346 assert!(1347 body_text(&response).contains(r#""status":"completed""#),1348 "{}",1349 body_text(&response)1350 );1351 let _ = std::fs::remove_dir_all(dir);1352 }1353 1354 #[test]1355 fn the_old_flat_image_and_video_routes_are_not_found() {1356 let (app, dir) = app();1357 for path in ["/image-gen", "/image-edit", "/t2v-gen", "/i2v-gen"] {1358 let response = app.handle(request(Method::Post, path, &chat(false), true));1359 assert_eq!(response.status, Status::NOT_FOUND, "{path}");1360 assert!(1361 body_text(&response).contains(r#""code":"not_found""#),1362 "{path}"1363 );1364 }1365 let _ = std::fs::remove_dir_all(dir);1366 }1367 1368 #[test]1369 fn an_unknown_priority_is_a_bad_request() {1370 let (app, dir) = app();1371 let body = r#"{"model":"echo","input":[{"kind":"text","text":"hello"}],"stream":false,"priority":"urgent"}"#;1372 let response = app.handle(request(Method::Post, "/chat", body, true));1373 assert_eq!(response.status, Status::BAD_REQUEST);1374 let text = body_text(&response);1375 assert!(text.contains("priority"), "{text}");1376 let _ = std::fs::remove_dir_all(dir);1377 }1378 1379 #[test]1380 fn capabilities_are_the_twelve_of_the_spec_with_or_without_models() {1381 let (app, dir) = app();1382 let response = app.handle(request(Method::Get, "/capabilities", "", true));1383 assert_eq!(response.status, Status::OK);1384 let body = body_text(&response);1385 let root = parse(&body).expect("json");1386 let rows = root1387 .get("capabilities")1388 .and_then(Value::as_array)1389 .expect("a capabilities array");1390 let names: Vec<&str> = rows1391 .iter()1392 .filter_map(|row| row.get("name").and_then(Value::as_str))1393 .collect();1394 assert_eq!(1395 names,1396 [1397 "chat",1398 "embed",1399 "rerank",1400 "tts",1401 "stt",1402 "music",1403 "image-gen",1404 "image-edit",1405 "t2v-gen",1406 "i2v-gen",1407 "decide",1408 "extract"1409 ]1410 );1411 let routes: Vec<&str> = rows1412 .iter()1413 .filter_map(|row| row.get("route").and_then(Value::as_str))1414 .collect();1415 assert_eq!(1416 routes,1417 [1418 "/chat",1419 "/embed",1420 "/rerank",1421 "/tts",1422 "/stt",1423 "/music",1424 "/image/generate",1425 "/image/edit",1426 "/video/text-to-video",1427 "/video/image-to-video",1428 "/decide",1429 "/extract"1430 ]1431 );1432 1433 let chat = rows1434 .iter()1435 .find(|row| row.get("name").and_then(Value::as_str) == Some("chat"))1436 .expect("the chat row");1437 assert_eq!(chat.get("stream"), Some(&Value::Bool(true)));1438 let parts: Vec<&str> = chat1439 .get("parts")1440 .and_then(Value::as_array)1441 .expect("parts")1442 .iter()1443 .filter_map(Value::as_str)1444 .collect();1445 assert_eq!(parts, ["text", "image", "audio", "json"]);1446 let channels: Vec<&str> = chat1447 .get("channels")1448 .and_then(Value::as_array)1449 .expect("channels")1450 .iter()1451 .filter_map(Value::as_str)1452 .collect();1453 assert_eq!(channels, ["text", "tokens", "decision", "progress"]);1454 1455 let embed = rows1456 .iter()1457 .find(|row| row.get("name").and_then(Value::as_str) == Some("embed"))1458 .expect("the embed row");1459 assert_eq!(embed.get("stream"), Some(&Value::Bool(false)));1460 let _ = std::fs::remove_dir_all(dir);1461 }1462 1463 #[test]1464 fn a_non_streaming_job_returns_the_terminal_metadata() {1465 let (app, dir) = app();1466 let body = r#"{"model":"echo","input":[{"kind":"text","text":"hello"}],"stream":false}"#;1467 let response = app.handle(request(Method::Post, "/tts", body, true));1468 assert_eq!(response.status, Status::OK, "{}", body_text(&response));1469 let root = parse(&body_text(&response)).expect("json");1470 let meta = root.get("meta").expect("terminal metadata");1471 assert_eq!(meta.get("model").and_then(Value::as_str), Some("echo"));1472 assert_eq!(meta.get("rate").and_then(Value::as_u64), Some(24_000));1473 assert_eq!(meta.get("channels").and_then(Value::as_u64), Some(1));1474 let _ = std::fs::remove_dir_all(dir);1475 }