crates/edge/api/tests/api.rs 7.2 KiB 240 lines Raw
1 //! The client's face: SSE bytes, refusal JSON, and the event object.2 3 use inf3r_api::code::{Code, Refusal};4 use inf3r_api::event::{Artifact, Body, Event, Seq};5 use inf3r_api::{DONE, sse};6 use inf3r_json::Value;7 8 #[test]9 fn sse_frames_are_exactly_the_bytes_of_r18() {10     let event = Event::new(Body::Text {11         channel: "text".into(),12         text: "Hel".into(),13     })14     .to_json(2);15 16     let mut out = Vec::new();17     sse::write_event(&mut out, &event).unwrap();18     let text = String::from_utf8(out).unwrap();19 20     assert!(text.starts_with("data: {"), "{text}");21     assert!(text.ends_with("}\n\n"), "{text}");22     assert_eq!(23         text.matches("\n\n").count(),24         1,25         "one frame is one blank line"26     );27 28     let mut out = Vec::new();29     sse::write_done(&mut out).unwrap();30     assert_eq!(out, DONE.as_bytes());31 }32 33 #[test]34 fn a_comment_cannot_carry_a_newline() {35     let mut out = Vec::new();36     sse::write_comment(&mut out, "ping\r\nnope").unwrap();37     assert_eq!(out, b": ping  nope\n\n");38 }39 40 #[test]41 fn the_sequence_numbers_a_job() {42     let mut seq = Seq::new();43     assert_eq!(seq.next(), 1);44     assert_eq!(seq.next(), 2);45     assert_eq!(seq.value(), 2);46 }47 48 #[test]49 fn a_started_event_has_the_fields_of_the_spec_example() {50     let event = Event::new(Body::Started {51         model: "example".into(),52         plugin: "flux-q8-gpu".into(),53         est_ms: Some(9000),54     })55     .about("019", "r-7");56     let json = event.to_json(1);57 58     // The envelope is sorted, because the object is a BTreeMap.59     let text = inf3r_json::to_string(&json);60     assert_eq!(61         text,62         format!(63             "{{\"at\":\"{}\",\"body\":{{\"est_ms\":9000,\"model\":\"example\",\"plugin\":\"flux-q8-gpu\",\"t\":\"started\"}},\"job\":\"019\",\"request_id\":\"r-7\",\"seq\":1}}",64             event.at.as_deref().unwrap()65         )66     );67 }68 69 #[test]70 fn a_delta_of_bytes_is_base64_of_the_bytes() {71     let event = Event::new(Body::Bytes {72         channel: "pcm".into(),73         mime: "audio/pcm".into(),74         data: vec![0, 1, 2],75     })76     .to_json(3);77 78     assert_eq!(79         event.get("body").and_then(|b| b.get("b64")),80         Some(&Value::str("AAEC"))81     );82     assert_eq!(83         event.get("body").and_then(|b| b.get("t")),84         Some(&Value::str("delta"))85     );86 }87 88 #[test]89 fn a_usage_event_puts_its_counts_in_the_body_not_a_wrapper() {90     let event = Event::new(Body::Usage(91         inf3r_json::Object::new()92             .put("text_in", Value::Int(12))93             .put("text_out", Value::Int(84))94             .put("images", Value::Int(1))95             .build(),96     ))97     .to_json(20);98 99     let body = event.get("body").expect("a body");100     assert_eq!(body.get("t"), Some(&Value::str("usage")));101     assert_eq!(body.get("text_in"), Some(&Value::Int(12)));102     assert_eq!(body.get("text_out"), Some(&Value::Int(84)));103     assert_eq!(body.get("images"), Some(&Value::Int(1)));104     assert!(body.get("counts").is_none());105 }106 107 #[test]108 fn a_done_event_carries_its_artifacts_and_its_meta() {109     let event = Event::new(Body::Done {110         outcome: "completed".into(),111         artifacts: vec![Artifact {112             channel: "image".into(),113             mime: "image/png".into(),114             blob: "a".repeat(64),115             bytes: 1843200,116         }],117         meta: Some(inf3r_json::Value::Object(Default::default())),118     })119     .to_json(21);120 121     let body = event.get("body").unwrap();122     assert_eq!(body.get("t"), Some(&Value::str("done")));123     let artifacts = body.get("artifacts").unwrap().as_array().unwrap();124     assert_eq!(artifacts.len(), 1);125     assert_eq!(artifacts[0].get("bytes"), Some(&Value::Int(1843200)));126     assert!(body.get("meta").is_some());127 }128 129 #[test]130 fn a_refusal_is_the_shape_of_rule_2() {131     let refusal = Refusal::new(Code::QueueFull, "r-7").with("the queue holds 32 jobs");132     let text = inf3r_json::to_string(&refusal.to_json());133 134     assert_eq!(135         text,136         "{\"error\":{\"code\":\"queue_full\",\"message\":\"the queue holds 32 jobs\",\"request_id\":\"r-7\",\"retryable\":true}}"137     );138 }139 140 #[test]141 fn every_code_has_a_status_and_the_two_tables_agree() {142     // The condition column of section 12, in a test: a code that a client can143     // retry is 429, 502, 503, or 504, and a `Retry-After` belongs to 429 and144     // 503 only.145     let codes = [146         Code::UnknownModel,147         Code::UnknownCapability,148         Code::CapabilityMissing,149         Code::InvalidPart,150         Code::PayloadTooLarge,151         Code::QueueFull,152         Code::NoRoom,153         Code::LoadFailed,154         Code::PluginCrashed,155         Code::Mismatch,156         Code::Protocol,157         Code::Timeout,158         Code::AmbiguousModel,159     ];160     for code in codes {161         let status = code.status();162         assert!((400..=504).contains(&status), "{code} is {status}");163         if code.has_retry_after() {164             // Section 12 gives `Retry-After` to `queue_full` (429) and165             // `no_room` (503): one queue, one device, both wait.166             assert!(matches!(status, 429 | 503), "{code} is {status}");167         }168         if code.retryable() {169             assert!(170                 matches!(status, 429 | 502 | 503 | 504),171                 "{code} is {status}"172             );173         }174     }175     assert_eq!(Code::UnknownModel.status(), 404);176     assert_eq!(Code::PayloadTooLarge.status(), 413);177     assert_eq!(Code::PluginCrashed.status(), 502);178 }179 180 #[test]181 fn a_wire_fault_is_a_protocol_refusal_and_never_a_client_404() {182     use inf3r_proto::body::ErrorCode as Wire;183     assert_eq!(Code::from_wire(Wire::UnknownModel), Code::UnknownModel);184     assert_eq!(Code::from_wire(Wire::Busy), Code::QueueFull);185     assert_eq!(Code::from_wire(Wire::Frame), Code::Protocol);186     assert_eq!(Code::from_wire(Wire::Stream), Code::Protocol);187     assert_eq!(Code::from_wire(Wire::Size), Code::PayloadTooLarge);188 }189 190 #[test]191 fn the_clock_writes_the_day_it_was_given() {192     assert_eq!(inf3r_api::clock::rfc3339(0, 0), "1970-01-01T00:00:00.000Z");193     assert_eq!(194         inf3r_api::clock::rfc3339(1_767_225_600, 100),195         "2026-01-01T00:00:00.100Z"196     );197     // A leap day, which a wrong civil conversion gets wrong by one day.198     assert_eq!(199         inf3r_api::clock::rfc3339(1_709_164_800, 0),200         "2024-02-29T00:00:00.000Z"201     );202     // The end of a day rolls the date.203     assert_eq!(204         inf3r_api::clock::rfc3339(86_399, 999),205         "1970-01-01T23:59:59.999Z"206     );207     assert_eq!(208         inf3r_api::clock::rfc3339(1_767_312_000, 0),209         "2026-01-02T00:00:00.000Z"210     );211 }212 213 #[test]214 fn base64_matches_the_rfc_4648_vectors() {215     let vectors = [216         (&b""[..], ""),217         (&b"f"[..], "Zg=="),218         (&b"fo"[..], "Zm8="),219         (&b"foo"[..], "Zm9v"),220         (&b"foob"[..], "Zm9vYg=="),221         (&b"fooba"[..], "Zm9vYmE="),222         (&b"foobar"[..], "Zm9vYmFy"),223     ];224     for (bytes, text) in vectors {225         assert_eq!(inf3r_api::b64::encode(bytes), text);226         assert_eq!(inf3r_api::b64::decode(text).unwrap(), bytes);227     }228     // Every byte value survives the round trip.229     let all: Vec<u8> = (0..=255).collect();230     assert_eq!(231         inf3r_api::b64::decode(&inf3r_api::b64::encode(&all)).unwrap(),232         all233     );234     assert_eq!(235         inf3r_api::b64::decode("Zg="),236         None,237         "a short group is not base64"238     );239     assert_eq!(inf3r_api::b64::decode("Z!=="), None);240 }