| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | mod common; |
| 21 | |
| 22 | use std::sync::Arc; |
| 23 | use std::time::Duration; |
| 24 | |
| 25 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; |
| 26 | use hezarfen_backend::module::ModuleSet; |
| 27 | use hezarfen_backend::tenant::{SchoolStatus, SchoolId, Tenants}; |
| 28 | use serde_json::{Value, json}; |
| 29 | |
| 30 | const TOKEN: &str = "shared-ai-token"; |
| 31 | |
| 32 | |
| 33 | |
| 34 | const SCHOOL: &str = "019732e3-7b00-7000-8000-00000000dead"; |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | const PROTOCOL: &str = "hab/2"; |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | mod raw { |
| 45 | use super::*; |
| 46 | |
| 47 | |
| 48 | |
| 49 | pub fn frame(body: &[u8]) -> Vec<u8> { |
| 50 | let mut out = Vec::with_capacity(4 + body.len()); |
| 51 | let len = body.len() as u32; |
| 52 | out.push((len >> 24) as u8); |
| 53 | out.push((len >> 16) as u8); |
| 54 | out.push((len >> 8) as u8); |
| 55 | out.push(len as u8); |
| 56 | out.extend_from_slice(body); |
| 57 | out |
| 58 | } |
| 59 | |
| 60 | |
| 61 | async fn read_exact(recv: &mut quinn::RecvStream, n: usize) -> Result<Vec<u8>, String> { |
| 62 | let mut buf = vec![0u8; n]; |
| 63 | recv.read_exact(&mut buf) |
| 64 | .await |
| 65 | .map_err(|e| format!("short read of {n} bytes: {e}"))?; |
| 66 | Ok(buf) |
| 67 | } |
| 68 | |
| 69 | |
| 70 | |
| 71 | pub async fn read_frame(recv: &mut quinn::RecvStream) -> Result<(Value, Vec<u8>), String> { |
| 72 | let header = read_exact(recv, 4).await?; |
| 73 | let len = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize; |
| 74 | let body = read_exact(recv, len).await?; |
| 75 | let value = |
| 76 | serde_json::from_slice(&body).map_err(|e| format!("frame was not JSON: {e}"))?; |
| 77 | Ok((value, body)) |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | pub fn endpoint(bridge: &AiBridge) -> quinn::Endpoint { |
| 83 | hezarfen_backend::ai::tls::install_crypto_provider(); |
| 84 | let mut roots = rustls::RootCertStore::empty(); |
| 85 | roots.add(bridge.certificate()).expect("pin the leaf"); |
| 86 | let mut tls = rustls::ClientConfig::builder() |
| 87 | .with_root_certificates(roots) |
| 88 | .with_no_client_auth(); |
| 89 | tls.alpn_protocols = vec![PROTOCOL.as_bytes().to_vec()]; |
| 90 | finish_endpoint(tls) |
| 91 | } |
| 92 | |
| 93 | |
| 94 | pub fn endpoint_with_alpn(bridge: &AiBridge, alpn: &[u8]) -> quinn::Endpoint { |
| 95 | hezarfen_backend::ai::tls::install_crypto_provider(); |
| 96 | let mut roots = rustls::RootCertStore::empty(); |
| 97 | roots.add(bridge.certificate()).expect("pin the leaf"); |
| 98 | let mut tls = rustls::ClientConfig::builder() |
| 99 | .with_root_certificates(roots) |
| 100 | .with_no_client_auth(); |
| 101 | tls.alpn_protocols = vec![alpn.to_vec()]; |
| 102 | finish_endpoint(tls) |
| 103 | } |
| 104 | |
| 105 | fn finish_endpoint(tls: rustls::ClientConfig) -> quinn::Endpoint { |
| 106 | let mut config = quinn::ClientConfig::new(Arc::new( |
| 107 | quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("QUIC-usable TLS"), |
| 108 | )); |
| 109 | let mut transport = quinn::TransportConfig::default(); |
| 110 | |
| 111 | |
| 112 | transport.max_concurrent_bidi_streams(128u32.into()); |
| 113 | config.transport_config(Arc::new(transport)); |
| 114 | let mut endpoint = |
| 115 | quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind"); |
| 116 | endpoint.set_default_client_config(config); |
| 117 | endpoint |
| 118 | } |
| 119 | |
| 120 | |
| 121 | pub struct Service { |
| 122 | pub _endpoint: quinn::Endpoint, |
| 123 | pub conn: quinn::Connection, |
| 124 | pub control: (quinn::SendStream, quinn::RecvStream), |
| 125 | |
| 126 | pub greeting: Value, |
| 127 | } |
| 128 | |
| 129 | |
| 130 | pub async fn handshake(bridge: &AiBridge, hello_body: &[u8]) -> Service { |
| 131 | let endpoint = endpoint(bridge); |
| 132 | let conn = endpoint |
| 133 | .connect(bridge.local_addr().unwrap(), "localhost") |
| 134 | .expect("dial") |
| 135 | .await |
| 136 | .expect("QUIC handshake"); |
| 137 | let (mut send, mut recv) = conn.open_bi().await.expect("control stream"); |
| 138 | send.write_all(&frame(hello_body)) |
| 139 | .await |
| 140 | .expect("write Hello"); |
| 141 | let (greeting, _) = frame_or_fail(&mut recv, "read Greeting").await; |
| 142 | Service { |
| 143 | _endpoint: endpoint, |
| 144 | conn, |
| 145 | control: (send, recv), |
| 146 | greeting, |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | |
| 151 | pub fn hello(service: &str, capability: &str) -> Vec<u8> { |
| 152 | format!( |
| 153 | r#"{{"protocol":"{PROTOCOL}","service":"{service}","capabilities":["{capability}"],"token":"{TOKEN}"}}"# |
| 154 | ) |
| 155 | .into_bytes() |
| 156 | } |
| 157 | |
| 158 | |
| 159 | |
| 160 | pub async fn take_request( |
| 161 | conn: &quinn::Connection, |
| 162 | ) -> (Value, Vec<u8>, quinn::SendStream, quinn::RecvStream) { |
| 163 | let (send, mut recv) = conn |
| 164 | .accept_bi() |
| 165 | .await |
| 166 | .expect("bridge opened a request stream"); |
| 167 | let (request, bytes) = frame_or_fail(&mut recv, "read Request").await; |
| 168 | (request, bytes, send, recv) |
| 169 | } |
| 170 | |
| 171 | |
| 172 | pub async fn answer(mut send: quinn::SendStream, body: &[u8]) { |
| 173 | send.write_all(&frame(body)).await.expect("write Response"); |
| 174 | let _ = send.finish(); |
| 175 | let _ = send.stopped().await; |
| 176 | } |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | pub async fn api_read(conn: &quinn::Connection, body: &[u8]) -> (Value, Vec<u8>) { |
| 183 | let (mut send, mut recv) = conn.open_bi().await.expect("api-read stream"); |
| 184 | send.write_all(&frame(body)) |
| 185 | .await |
| 186 | .expect("write ApiRequest"); |
| 187 | let _ = send.finish(); |
| 188 | frame_or_fail(&mut recv, "read ApiResponse").await |
| 189 | } |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | pub async fn blob_read(conn: &quinn::Connection, body: &[u8]) -> (Value, Vec<u8>, Vec<u8>) { |
| 196 | let (mut send, mut recv) = conn.open_bi().await.expect("blob stream"); |
| 197 | send.write_all(&frame(body)) |
| 198 | .await |
| 199 | .expect("write BlobRequest"); |
| 200 | let _ = send.finish(); |
| 201 | let (header, bytes) = frame_or_fail(&mut recv, "read BlobResponse").await; |
| 202 | |
| 203 | |
| 204 | let body = recv |
| 205 | .read_to_end(16 * 1024 * 1024) |
| 206 | .await |
| 207 | .expect("read to EOF after the header"); |
| 208 | (header, bytes, body) |
| 209 | } |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | pub async fn frame_or_fail(recv: &mut quinn::RecvStream, what: &str) -> (Value, Vec<u8>) { |
| 215 | match tokio::time::timeout(Duration::from_secs(10), read_frame(recv)).await { |
| 216 | Ok(Ok(frame)) => frame, |
| 217 | Ok(Err(err)) => panic!("{what}: the frame could not be read: {err}"), |
| 218 | Err(_) => panic!("{what}: no frame arrived within 10s — the bridge did not answer"), |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | |
| 223 | pub fn keys(value: &Value) -> Vec<String> { |
| 224 | let mut k: Vec<String> = value |
| 225 | .as_object() |
| 226 | .expect("a JSON object") |
| 227 | .keys() |
| 228 | .cloned() |
| 229 | .collect(); |
| 230 | k.sort(); |
| 231 | k |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | |
| 236 | |
| 237 | async fn bridge_with_timeout(timeout: Duration) -> AiBridge { |
| 238 | AiBridge::bind(BridgeConfig { |
| 239 | addr: "127.0.0.1:0".parse().unwrap(), |
| 240 | token: TOKEN.to_string(), |
| 241 | cert_path: None, |
| 242 | key_path: None, |
| 243 | request_timeout: timeout, |
| 244 | }) |
| 245 | .await |
| 246 | .expect("bridge binds") |
| 247 | } |
| 248 | |
| 249 | async fn bridge() -> AiBridge { |
| 250 | bridge_with_timeout(Duration::from_secs(5)).await |
| 251 | } |
| 252 | |
| 253 | async fn await_workers(bridge: &AiBridge, expected: usize) { |
| 254 | for _ in 0..300 { |
| 255 | if bridge.workers().len() == expected { |
| 256 | return; |
| 257 | } |
| 258 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 259 | } |
| 260 | panic!("expected {expected} workers, saw {:?}", bridge.workers()); |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | fn dispatch( |
| 266 | bridge: &AiBridge, |
| 267 | capability: &str, |
| 268 | payload: Value, |
| 269 | ) -> tokio::task::JoinHandle<Result<Value, AiError>> { |
| 270 | let bridge = bridge.clone(); |
| 271 | let capability = capability.to_string(); |
| 272 | let school = hezarfen_backend::tenant::SchoolId::try_parse(SCHOOL).expect("the demo slug"); |
| 273 | tokio::spawn(async move { bridge.dispatch(&school, &capability, payload).await }) |
| 274 | } |
| 275 | |
| 276 | |
| 277 | |
| 278 | #[tokio::test] |
| 279 | async fn the_length_prefix_is_four_byte_big_endian() { |
| 280 | |
| 281 | |
| 282 | |
| 283 | let bridge = bridge().await; |
| 284 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 285 | await_workers(&bridge, 1).await; |
| 286 | |
| 287 | let call = dispatch(&bridge, "ocr.extract", json!({ "k": "v" })); |
| 288 | let (_send, mut recv) = service.conn.accept_bi().await.unwrap(); |
| 289 | |
| 290 | let mut header = [0u8; 4]; |
| 291 | recv.read_exact(&mut header) |
| 292 | .await |
| 293 | .expect("four header bytes"); |
| 294 | let big_endian = u32::from_be_bytes(header) as usize; |
| 295 | let little_endian = u32::from_le_bytes(header) as usize; |
| 296 | |
| 297 | let mut body = vec![0u8; big_endian]; |
| 298 | recv.read_exact(&mut body) |
| 299 | .await |
| 300 | .expect("the body the header promised"); |
| 301 | assert_eq!(body.len(), big_endian); |
| 302 | |
| 303 | |
| 304 | assert_eq!( |
| 305 | header[0], 0, |
| 306 | "top byte of a small frame's length must be zero" |
| 307 | ); |
| 308 | assert_eq!(header[1], 0); |
| 309 | assert_ne!( |
| 310 | big_endian, little_endian, |
| 311 | "test is only meaningful when the two readings differ" |
| 312 | ); |
| 313 | assert!( |
| 314 | serde_json::from_slice::<Value>(&body).is_ok(), |
| 315 | "the big-endian length delimited exactly one JSON document" |
| 316 | ); |
| 317 | call.abort(); |
| 318 | } |
| 319 | |
| 320 | #[tokio::test] |
| 321 | async fn a_frame_split_across_many_writes_is_reassembled() { |
| 322 | |
| 323 | |
| 324 | |
| 325 | let bridge = bridge().await; |
| 326 | let endpoint = raw::endpoint(&bridge); |
| 327 | let conn = endpoint |
| 328 | .connect(bridge.local_addr().unwrap(), "localhost") |
| 329 | .unwrap() |
| 330 | .await |
| 331 | .unwrap(); |
| 332 | let (mut send, mut recv) = conn.open_bi().await.unwrap(); |
| 333 | |
| 334 | let bytes = raw::frame(&raw::hello("ocr", "ocr.extract")); |
| 335 | for byte in &bytes { |
| 336 | send.write_all(&[*byte]).await.expect("dribble"); |
| 337 | tokio::task::yield_now().await; |
| 338 | } |
| 339 | |
| 340 | let (greeting, _) = raw::frame_or_fail(&mut recv, "still welcomed").await; |
| 341 | assert_eq!(greeting["type"], "welcome"); |
| 342 | await_workers(&bridge, 1).await; |
| 343 | } |
| 344 | |
| 345 | #[tokio::test] |
| 346 | async fn a_declared_length_over_the_cap_is_refused_without_the_body() { |
| 347 | |
| 348 | |
| 349 | |
| 350 | let bridge = bridge().await; |
| 351 | let endpoint = raw::endpoint(&bridge); |
| 352 | let conn = endpoint |
| 353 | .connect(bridge.local_addr().unwrap(), "localhost") |
| 354 | .unwrap() |
| 355 | .await |
| 356 | .unwrap(); |
| 357 | let (mut send, _recv) = conn.open_bi().await.unwrap(); |
| 358 | let oversized: u32 = 9 * 1024 * 1024; |
| 359 | send.write_all(&oversized.to_be_bytes()).await.unwrap(); |
| 360 | |
| 361 | |
| 362 | |
| 363 | tokio::time::sleep(Duration::from_millis(300)).await; |
| 364 | assert!( |
| 365 | bridge.workers().is_empty(), |
| 366 | "an oversized frame must not produce a registration" |
| 367 | ); |
| 368 | } |
| 369 | |
| 370 | #[tokio::test] |
| 371 | async fn a_zero_length_frame_is_rejected_not_treated_as_empty() { |
| 372 | let bridge = bridge().await; |
| 373 | let service = raw::handshake(&bridge, b"").await; |
| 374 | assert_eq!(service.greeting["type"], "rejected"); |
| 375 | assert_eq!(service.greeting["code"], "malformed"); |
| 376 | assert!(bridge.workers().is_empty()); |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | #[tokio::test] |
| 382 | async fn the_welcome_frame_carries_exactly_the_published_keys() { |
| 383 | let bridge = bridge().await; |
| 384 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 385 | |
| 386 | assert_eq!( |
| 387 | raw::keys(&service.greeting), |
| 388 | ["protocol", "type", "worker_id"] |
| 389 | ); |
| 390 | assert_eq!(service.greeting["type"], "welcome"); |
| 391 | assert_eq!(service.greeting["protocol"], PROTOCOL); |
| 392 | assert!( |
| 393 | service.greeting["worker_id"] |
| 394 | .as_str() |
| 395 | .is_some_and(|w| !w.is_empty()), |
| 396 | "worker_id is a non-empty string a service can log" |
| 397 | ); |
| 398 | } |
| 399 | |
| 400 | #[tokio::test] |
| 401 | async fn the_rejection_frame_carries_exactly_the_published_keys_and_codes() { |
| 402 | |
| 403 | |
| 404 | let bridge = bridge().await; |
| 405 | |
| 406 | let cases: [(&str, Vec<u8>); 5] = [ |
| 407 | ( |
| 408 | "unauthorized", |
| 409 | format!( |
| 410 | r#"{{"protocol":"{PROTOCOL}","service":"s","capabilities":["c"],"token":"wrong"}}"# |
| 411 | ) |
| 412 | .into_bytes(), |
| 413 | ), |
| 414 | ( |
| 415 | "unsupported_protocol", |
| 416 | format!( |
| 417 | r#"{{"protocol":"hab/99","service":"s","capabilities":["c"],"token":"{TOKEN}"}}"# |
| 418 | ) |
| 419 | .into_bytes(), |
| 420 | ), |
| 421 | |
| 422 | |
| 423 | |
| 424 | ( |
| 425 | "unsupported_protocol", |
| 426 | format!( |
| 427 | r#"{{"protocol":"hab/1","service":"s","capabilities":["c"],"token":"{TOKEN}"}}"# |
| 428 | ) |
| 429 | .into_bytes(), |
| 430 | ), |
| 431 | ( |
| 432 | "no_capabilities", |
| 433 | format!( |
| 434 | r#"{{"protocol":"{PROTOCOL}","service":"s","capabilities":[],"token":"{TOKEN}"}}"# |
| 435 | ) |
| 436 | .into_bytes(), |
| 437 | ), |
| 438 | ("malformed", b"not json".to_vec()), |
| 439 | ]; |
| 440 | |
| 441 | for (expected_code, hello) in cases { |
| 442 | let service = raw::handshake(&bridge, &hello).await; |
| 443 | assert_eq!( |
| 444 | raw::keys(&service.greeting), |
| 445 | ["code", "message", "type"], |
| 446 | "rejection shape changed for {expected_code}" |
| 447 | ); |
| 448 | assert_eq!(service.greeting["type"], "rejected"); |
| 449 | assert_eq!( |
| 450 | service.greeting["code"], expected_code, |
| 451 | "reject code spelling changed: {}", |
| 452 | service.greeting |
| 453 | ); |
| 454 | assert!( |
| 455 | service.greeting["message"].as_str().is_some(), |
| 456 | "message must be a string a service can log" |
| 457 | ); |
| 458 | } |
| 459 | assert!(bridge.workers().is_empty()); |
| 460 | } |
| 461 | |
| 462 | #[tokio::test] |
| 463 | async fn hello_accepts_unknown_fields_so_services_can_run_ahead() { |
| 464 | |
| 465 | |
| 466 | let bridge = bridge().await; |
| 467 | let hello = format!( |
| 468 | r#"{{"protocol":"{PROTOCOL}","service":"ocr","capabilities":["ocr.extract"],"token":"{TOKEN}","future_field":{{"nested":true}},"model":"gpt-9"}}"# |
| 469 | ); |
| 470 | let service = raw::handshake(&bridge, hello.as_bytes()).await; |
| 471 | assert_eq!(service.greeting["type"], "welcome"); |
| 472 | await_workers(&bridge, 1).await; |
| 473 | } |
| 474 | |
| 475 | #[tokio::test] |
| 476 | async fn hello_requires_its_documented_fields() { |
| 477 | |
| 478 | |
| 479 | |
| 480 | let bridge = bridge().await; |
| 481 | let required = ["protocol", "service", "capabilities", "token"]; |
| 482 | |
| 483 | for missing in required { |
| 484 | let mut fields = json!({ |
| 485 | "protocol": PROTOCOL, |
| 486 | "service": "ocr", |
| 487 | "capabilities": ["ocr.extract"], |
| 488 | "token": TOKEN, |
| 489 | }); |
| 490 | fields.as_object_mut().unwrap().remove(missing); |
| 491 | let body = serde_json::to_vec(&fields).unwrap(); |
| 492 | |
| 493 | let service = raw::handshake(&bridge, &body).await; |
| 494 | assert_eq!( |
| 495 | service.greeting["type"], "rejected", |
| 496 | "a Hello without `{missing}` was accepted" |
| 497 | ); |
| 498 | assert_eq!(service.greeting["code"], "malformed"); |
| 499 | } |
| 500 | assert!(bridge.workers().is_empty()); |
| 501 | } |
| 502 | |
| 503 | #[tokio::test] |
| 504 | async fn max_concurrent_stays_optional() { |
| 505 | |
| 506 | |
| 507 | let bridge = bridge().await; |
| 508 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 509 | assert_eq!(service.greeting["type"], "welcome"); |
| 510 | await_workers(&bridge, 1).await; |
| 511 | assert!( |
| 512 | bridge.workers()[0].max_concurrent >= 1, |
| 513 | "an omitted max_concurrent yields a usable default" |
| 514 | ); |
| 515 | } |
| 516 | |
| 517 | #[tokio::test] |
| 518 | async fn a_foreign_alpn_is_refused_at_the_tls_handshake() { |
| 519 | |
| 520 | |
| 521 | let bridge = bridge().await; |
| 522 | |
| 523 | |
| 524 | for alpn in [b"hab/99".as_slice(), b"hab/1".as_slice()] { |
| 525 | let endpoint = raw::endpoint_with_alpn(&bridge, alpn); |
| 526 | let result = endpoint |
| 527 | .connect(bridge.local_addr().unwrap(), "localhost") |
| 528 | .unwrap() |
| 529 | .await; |
| 530 | assert!( |
| 531 | result.is_err(), |
| 532 | "ALPN {} must not connect", |
| 533 | String::from_utf8_lossy(alpn) |
| 534 | ); |
| 535 | } |
| 536 | assert!(bridge.workers().is_empty()); |
| 537 | } |
| 538 | |
| 539 | |
| 540 | |
| 541 | #[tokio::test] |
| 542 | async fn the_request_frame_carries_exactly_the_published_keys() { |
| 543 | |
| 544 | |
| 545 | |
| 546 | let bridge = bridge_with_timeout(Duration::from_secs(7)).await; |
| 547 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 548 | await_workers(&bridge, 1).await; |
| 549 | |
| 550 | let call = dispatch(&bridge, "ocr.extract", json!({ "image": "abc", "n": 3 })); |
| 551 | let (request, _bytes, send, _recv) = raw::take_request(&service.conn).await; |
| 552 | |
| 553 | assert_eq!( |
| 554 | raw::keys(&request), |
| 555 | ["capability", "deadline_ms", "id", "payload", "school"], |
| 556 | "request shape changed: {request}" |
| 557 | ); |
| 558 | assert_eq!(request["capability"], "ocr.extract"); |
| 559 | assert_eq!(request["deadline_ms"], 7000); |
| 560 | assert!(request["id"].as_str().is_some_and(|i| !i.is_empty())); |
| 561 | |
| 562 | |
| 563 | assert_eq!(request["payload"], json!({ "image": "abc", "n": 3 })); |
| 564 | |
| 565 | let id = request["id"].as_str().unwrap().to_string(); |
| 566 | raw::answer( |
| 567 | send, |
| 568 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"hi"}}}}"#) |
| 569 | .as_bytes(), |
| 570 | ) |
| 571 | .await; |
| 572 | let answer = call.await.unwrap().expect("dispatch succeeded"); |
| 573 | assert_eq!(answer, json!({ "text": "hi" })); |
| 574 | } |
| 575 | |
| 576 | #[tokio::test] |
| 577 | async fn a_payload_of_any_json_shape_survives_unchanged() { |
| 578 | |
| 579 | |
| 580 | |
| 581 | let bridge = bridge().await; |
| 582 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 583 | await_workers(&bridge, 1).await; |
| 584 | |
| 585 | let payloads = [ |
| 586 | json!(null), |
| 587 | json!(true), |
| 588 | json!(-17), |
| 589 | json!(1.5), |
| 590 | json!("düz metin — ünicode"), |
| 591 | json!([]), |
| 592 | json!([1, [2, [3]], { "deep": { "deeper": null } }]), |
| 593 | json!({ "empty": {}, "zero": 0, "false": false, "nul": null }), |
| 594 | ]; |
| 595 | |
| 596 | for payload in payloads { |
| 597 | let call = dispatch(&bridge, "ocr.extract", payload.clone()); |
| 598 | let (request, _, send, _recv) = raw::take_request(&service.conn).await; |
| 599 | assert_eq!(request["payload"], payload, "payload mutated in flight"); |
| 600 | |
| 601 | let id = request["id"].as_str().unwrap(); |
| 602 | let echo = json!({ "status": "ok", "id": id, "school": SCHOOL, "payload": payload }); |
| 603 | raw::answer(send, &serde_json::to_vec(&echo).unwrap()).await; |
| 604 | assert_eq!( |
| 605 | call.await.unwrap().unwrap(), |
| 606 | payload, |
| 607 | "payload mutated on return" |
| 608 | ); |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | #[tokio::test] |
| 613 | async fn the_response_tags_are_the_published_literals() { |
| 614 | |
| 615 | |
| 616 | let bridge = bridge().await; |
| 617 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 618 | await_workers(&bridge, 1).await; |
| 619 | |
| 620 | let ok = dispatch(&bridge, "ocr.extract", json!(1)); |
| 621 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 622 | let id = request["id"].as_str().unwrap().to_string(); |
| 623 | raw::answer( |
| 624 | send, |
| 625 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":42}}"#).as_bytes(), |
| 626 | ) |
| 627 | .await; |
| 628 | assert_eq!(ok.await.unwrap().unwrap(), json!(42)); |
| 629 | |
| 630 | let err = dispatch(&bridge, "ocr.extract", json!(2)); |
| 631 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 632 | let id = request["id"].as_str().unwrap().to_string(); |
| 633 | raw::answer( |
| 634 | send, |
| 635 | format!(r#"{{"status":"err","id":"{id}","school":"{SCHOOL}","code":"bad_input","message":"nope"}}"#).as_bytes(), |
| 636 | ) |
| 637 | .await; |
| 638 | match err.await.unwrap() { |
| 639 | Err(AiError::Remote { code, message }) => { |
| 640 | assert_eq!(code, "bad_input"); |
| 641 | assert_eq!(message, "nope"); |
| 642 | } |
| 643 | other => panic!("expected a remote error, got {other:?}"), |
| 644 | } |
| 645 | |
| 646 | let bogus = dispatch(&bridge, "ocr.extract", json!(3)); |
| 647 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 648 | let id = request["id"].as_str().unwrap().to_string(); |
| 649 | raw::answer( |
| 650 | send, |
| 651 | format!(r#"{{"status":"success","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(), |
| 652 | ) |
| 653 | .await; |
| 654 | assert!( |
| 655 | matches!(bogus.await.unwrap(), Err(AiError::Protocol(_))), |
| 656 | "an unpublished status tag must be refused, not guessed at" |
| 657 | ); |
| 658 | } |
| 659 | |
| 660 | #[tokio::test] |
| 661 | async fn a_response_may_carry_unknown_fields() { |
| 662 | |
| 663 | |
| 664 | let bridge = bridge().await; |
| 665 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 666 | await_workers(&bridge, 1).await; |
| 667 | |
| 668 | let call = dispatch(&bridge, "ocr.extract", json!(null)); |
| 669 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 670 | let id = request["id"].as_str().unwrap().to_string(); |
| 671 | raw::answer( |
| 672 | send, |
| 673 | format!( |
| 674 | r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"x"}},"took_ms":91,"model":"v2"}}"# |
| 675 | ) |
| 676 | .as_bytes(), |
| 677 | ) |
| 678 | .await; |
| 679 | assert_eq!(call.await.unwrap().unwrap(), json!({ "text": "x" })); |
| 680 | } |
| 681 | |
| 682 | #[tokio::test] |
| 683 | async fn a_response_missing_its_id_is_refused() { |
| 684 | let bridge = bridge().await; |
| 685 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 686 | await_workers(&bridge, 1).await; |
| 687 | |
| 688 | let call = dispatch(&bridge, "ocr.extract", json!(null)); |
| 689 | let (_request, _, send, _r) = raw::take_request(&service.conn).await; |
| 690 | raw::answer(send, br#"{"status":"ok","payload":1}"#).await; |
| 691 | assert!( |
| 692 | matches!(call.await.unwrap(), Err(AiError::Protocol(_))), |
| 693 | "id is required on the wire" |
| 694 | ); |
| 695 | } |
| 696 | |
| 697 | |
| 698 | |
| 699 | #[tokio::test] |
| 700 | async fn each_request_gets_its_own_stream_and_answers_may_come_back_in_any_order() { |
| 701 | |
| 702 | |
| 703 | |
| 704 | let bridge = bridge_with_timeout(Duration::from_secs(20)).await; |
| 705 | let hello = format!( |
| 706 | r#"{{"protocol":"{PROTOCOL}","service":"ocr","capabilities":["ocr.extract"],"token":"{TOKEN}","max_concurrent":8}}"# |
| 707 | ); |
| 708 | let service = raw::handshake(&bridge, hello.as_bytes()).await; |
| 709 | await_workers(&bridge, 1).await; |
| 710 | |
| 711 | let calls: Vec<_> = (0..5) |
| 712 | .map(|i| dispatch(&bridge, "ocr.extract", json!({ "n": i }))) |
| 713 | .collect(); |
| 714 | |
| 715 | |
| 716 | |
| 717 | let mut pending = Vec::new(); |
| 718 | for _ in 0..5 { |
| 719 | let (request, _, send, _recv) = raw::take_request(&service.conn).await; |
| 720 | pending.push((request, send)); |
| 721 | } |
| 722 | |
| 723 | |
| 724 | pending.reverse(); |
| 725 | for (request, send) in pending { |
| 726 | let id = request["id"].as_str().unwrap().to_string(); |
| 727 | let n = request["payload"]["n"].clone(); |
| 728 | raw::answer( |
| 729 | send, |
| 730 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"n":{n}}}}}"#) |
| 731 | .as_bytes(), |
| 732 | ) |
| 733 | .await; |
| 734 | } |
| 735 | |
| 736 | for (i, call) in calls.into_iter().enumerate() { |
| 737 | let answer = call.await.unwrap().expect("dispatch ok"); |
| 738 | assert_eq!( |
| 739 | answer["n"], i as u64, |
| 740 | "answer {i} came back on the wrong caller's future" |
| 741 | ); |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | #[tokio::test] |
| 746 | async fn request_ids_are_unique_per_request() { |
| 747 | |
| 748 | |
| 749 | let bridge = bridge().await; |
| 750 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 751 | await_workers(&bridge, 1).await; |
| 752 | |
| 753 | let mut seen = std::collections::HashSet::new(); |
| 754 | for _ in 0..6 { |
| 755 | let call = dispatch(&bridge, "ocr.extract", json!(null)); |
| 756 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 757 | let id = request["id"].as_str().unwrap().to_string(); |
| 758 | assert!(seen.insert(id.clone()), "id {id} was reused"); |
| 759 | raw::answer( |
| 760 | send, |
| 761 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(), |
| 762 | ) |
| 763 | .await; |
| 764 | call.await.unwrap().unwrap(); |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | #[tokio::test] |
| 769 | async fn the_control_stream_carries_no_frames_after_the_welcome() { |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | let bridge = bridge().await; |
| 775 | let mut service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 776 | await_workers(&bridge, 1).await; |
| 777 | |
| 778 | let quiet = tokio::time::timeout( |
| 779 | Duration::from_millis(400), |
| 780 | raw::read_frame(&mut service.control.1), |
| 781 | ) |
| 782 | .await; |
| 783 | assert!( |
| 784 | quiet.is_err(), |
| 785 | "nothing should arrive on the control stream" |
| 786 | ); |
| 787 | |
| 788 | let call = dispatch(&bridge, "ocr.extract", json!(null)); |
| 789 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 790 | let id = request["id"].as_str().unwrap().to_string(); |
| 791 | raw::answer( |
| 792 | send, |
| 793 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":1}}"#).as_bytes(), |
| 794 | ) |
| 795 | .await; |
| 796 | call.await |
| 797 | .unwrap() |
| 798 | .expect("still serving after the silence"); |
| 799 | } |
| 800 | |
| 801 | #[tokio::test] |
| 802 | async fn closing_the_control_stream_deregisters_the_service() { |
| 803 | |
| 804 | |
| 805 | let bridge = bridge().await; |
| 806 | let mut service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 807 | await_workers(&bridge, 1).await; |
| 808 | |
| 809 | let _ = service.control.0.finish(); |
| 810 | drop(service.control); |
| 811 | service.conn.close(0u32.into(), b"goodbye"); |
| 812 | await_workers(&bridge, 0).await; |
| 813 | |
| 814 | assert!(matches!( |
| 815 | bridge |
| 816 | .dispatch( |
| 817 | &hezarfen_backend::tenant::SchoolId::try_parse(SCHOOL).unwrap(), |
| 818 | "ocr.extract", |
| 819 | json!(null) |
| 820 | ) |
| 821 | .await, |
| 822 | Err(AiError::NoWorker(_)) |
| 823 | )); |
| 824 | } |
| 825 | |
| 826 | #[tokio::test] |
| 827 | async fn a_service_that_drops_a_request_stream_fails_that_request_only() { |
| 828 | |
| 829 | |
| 830 | |
| 831 | let bridge = bridge().await; |
| 832 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 833 | await_workers(&bridge, 1).await; |
| 834 | |
| 835 | let doomed = dispatch(&bridge, "ocr.extract", json!("first")); |
| 836 | let (_request, _, send, recv) = raw::take_request(&service.conn).await; |
| 837 | drop(send); |
| 838 | drop(recv); |
| 839 | let err = doomed |
| 840 | .await |
| 841 | .unwrap() |
| 842 | .expect_err("the dropped stream failed"); |
| 843 | assert!( |
| 844 | matches!(err, AiError::Transport(_) | AiError::Protocol(_)), |
| 845 | "unexpected error: {err}" |
| 846 | ); |
| 847 | |
| 848 | assert_eq!( |
| 849 | bridge.workers().len(), |
| 850 | 1, |
| 851 | "the worker survives one bad stream" |
| 852 | ); |
| 853 | let next = dispatch(&bridge, "ocr.extract", json!("second")); |
| 854 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 855 | let id = request["id"].as_str().unwrap().to_string(); |
| 856 | raw::answer( |
| 857 | send, |
| 858 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":"ok"}}"#).as_bytes(), |
| 859 | ) |
| 860 | .await; |
| 861 | assert_eq!(next.await.unwrap().unwrap(), json!("ok")); |
| 862 | } |
| 863 | |
| 864 | #[tokio::test] |
| 865 | async fn a_late_answer_after_the_deadline_is_not_delivered() { |
| 866 | |
| 867 | |
| 868 | |
| 869 | let bridge = bridge_with_timeout(Duration::from_millis(250)).await; |
| 870 | let service = raw::handshake(&bridge, &raw::hello("ocr", "ocr.extract")).await; |
| 871 | await_workers(&bridge, 1).await; |
| 872 | |
| 873 | let call = dispatch(&bridge, "ocr.extract", json!(null)); |
| 874 | let (request, _, send, _r) = raw::take_request(&service.conn).await; |
| 875 | assert_eq!( |
| 876 | request["deadline_ms"], 250, |
| 877 | "the service was told the deadline" |
| 878 | ); |
| 879 | |
| 880 | assert!( |
| 881 | matches!(call.await.unwrap(), Err(AiError::Timeout(250))), |
| 882 | "the call fails at the deadline" |
| 883 | ); |
| 884 | assert_eq!(bridge.workers()[0].inflight, 0, "the slot was released"); |
| 885 | |
| 886 | |
| 887 | |
| 888 | |
| 889 | |
| 890 | |
| 891 | |
| 892 | |
| 893 | let stopped = tokio::time::timeout(Duration::from_secs(2), send.stopped()).await; |
| 894 | assert!( |
| 895 | stopped.is_ok(), |
| 896 | "the abandoned stream must be torn down, not left open for a late answer" |
| 897 | ); |
| 898 | |
| 899 | |
| 900 | |
| 901 | assert_eq!(bridge.workers()[0].inflight, 0); |
| 902 | } |
| 903 | |
| 904 | #[tokio::test] |
| 905 | async fn several_raw_services_serve_one_capability_together() { |
| 906 | |
| 907 | |
| 908 | |
| 909 | let bridge = bridge_with_timeout(Duration::from_secs(20)).await; |
| 910 | let mut services = Vec::new(); |
| 911 | for i in 0..3 { |
| 912 | services |
| 913 | .push(raw::handshake(&bridge, &raw::hello(&format!("ocr-{i}"), "ocr.extract")).await); |
| 914 | } |
| 915 | await_workers(&bridge, 3).await; |
| 916 | |
| 917 | |
| 918 | for service in &services { |
| 919 | let conn = service.conn.clone(); |
| 920 | tokio::spawn(async move { |
| 921 | while let Ok((send, mut recv)) = conn.accept_bi().await { |
| 922 | let Ok((request, _)) = raw::read_frame(&mut recv).await else { |
| 923 | return; |
| 924 | }; |
| 925 | let id = request["id"].as_str().unwrap().to_string(); |
| 926 | let n = request["payload"]["n"].clone(); |
| 927 | raw::answer( |
| 928 | send, |
| 929 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{n}}}"#) |
| 930 | .as_bytes(), |
| 931 | ) |
| 932 | .await; |
| 933 | } |
| 934 | }); |
| 935 | } |
| 936 | |
| 937 | let calls: Vec<_> = (0..12) |
| 938 | .map(|n| dispatch(&bridge, "ocr.extract", json!({ "n": n }))) |
| 939 | .collect(); |
| 940 | let mut got: Vec<u64> = Vec::new(); |
| 941 | for call in calls { |
| 942 | got.push(call.await.unwrap().unwrap().as_u64().expect("echoed n")); |
| 943 | } |
| 944 | got.sort_unstable(); |
| 945 | assert_eq!( |
| 946 | got, |
| 947 | (0..12).collect::<Vec<u64>>(), |
| 948 | "every request answered once" |
| 949 | ); |
| 950 | } |
| 951 | |
| 952 | |
| 953 | |
| 954 | |
| 955 | |
| 956 | |
| 957 | |
| 958 | |
| 959 | #[tokio::test] |
| 960 | async fn a_chat_request_names_the_askers_school_role() { |
| 961 | |
| 962 | |
| 963 | |
| 964 | let bridge = bridge().await; |
| 965 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 966 | await_workers(&bridge, 1).await; |
| 967 | |
| 968 | let tenants = hezarfen_backend::database::init_test_tenants().await; |
| 969 | let db = tenants |
| 970 | .get(&hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap()) |
| 971 | .await |
| 972 | .expect("the demo school"); |
| 973 | let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { |
| 974 | db: tenants.control().clone(), |
| 975 | tenants, |
| 976 | files_path: common::files_dir(), |
| 977 | cookie_secure: false, |
| 978 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| 979 | chatbot_limit: Default::default(), |
| 980 | rag_limit: Default::default(), |
| 981 | exam_presence: Default::default(), |
| 982 | board_hub: Default::default(), |
| 983 | ai: Some(bridge.clone()), |
| 984 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 985 | }); |
| 986 | let cookie = common::login_as(&app, &db, "veli", "teacher").await; |
| 987 | let res = common::send( |
| 988 | &app, |
| 989 | "POST", |
| 990 | "/chatbot/threads", |
| 991 | Some(&cookie), |
| 992 | Some(json!({})), |
| 993 | ) |
| 994 | .await; |
| 995 | let thread = common::id_of(&res.body); |
| 996 | let res = common::send( |
| 997 | &app, |
| 998 | "POST", |
| 999 | &format!("/chatbot/threads/{thread}/messages"), |
| 1000 | Some(&cookie), |
| 1001 | Some(json!({ "content": "ikinci yasa nedir?" })), |
| 1002 | ) |
| 1003 | .await; |
| 1004 | assert_eq!(res.status, axum::http::StatusCode::ACCEPTED, "{}", res.body); |
| 1005 | |
| 1006 | let (request, bytes, send, _recv) = raw::take_request(&service.conn).await; |
| 1007 | assert_eq!(request["capability"], "chat.reply"); |
| 1008 | assert_eq!( |
| 1009 | raw::keys(&request["payload"]), |
| 1010 | ["asker_role", "history", "message"], |
| 1011 | "the documented chat request payload keys" |
| 1012 | ); |
| 1013 | assert_eq!(request["payload"]["message"], "ikinci yasa nedir?"); |
| 1014 | assert_eq!(request["payload"]["asker_role"], "teacher"); |
| 1015 | |
| 1016 | |
| 1017 | let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON"); |
| 1018 | assert!(text.contains(r#""asker_role":"teacher""#), "{text}"); |
| 1019 | |
| 1020 | let id = request["id"].as_str().expect("trace id").to_string(); |
| 1021 | raw::answer( |
| 1022 | send, |
| 1023 | format!( |
| 1024 | r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{{"text":"F = ma"}}}}"# |
| 1025 | ) |
| 1026 | .as_bytes(), |
| 1027 | ) |
| 1028 | .await; |
| 1029 | } |
| 1030 | |
| 1031 | |
| 1032 | |
| 1033 | |
| 1034 | |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | #[tokio::test] |
| 1040 | async fn rag_chat_payloads_carry_the_documented_wire_keys() { |
| 1041 | use hezarfen_backend::ai::{ |
| 1042 | RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair, |
| 1043 | }; |
| 1044 | |
| 1045 | let bridge = bridge().await; |
| 1046 | let service = raw::handshake(&bridge, &raw::hello("rag", "rag.chat")).await; |
| 1047 | await_workers(&bridge, 1).await; |
| 1048 | |
| 1049 | let request = serde_json::to_value(RagChatRequestPayload { |
| 1050 | message: "ikinci yasa nedir?".into(), |
| 1051 | asker: "01ASKER".into(), |
| 1052 | asker_role: "student".into(), |
| 1053 | scope: vec![RagScopePair { |
| 1054 | sinif: Some("11".into()), |
| 1055 | ders: "Fizik".into(), |
| 1056 | }], |
| 1057 | history: Vec::new(), |
| 1058 | }) |
| 1059 | .unwrap(); |
| 1060 | let call = dispatch(&bridge, "rag.chat", request); |
| 1061 | |
| 1062 | let (frame, bytes, send, _recv) = raw::take_request(&service.conn).await; |
| 1063 | assert_eq!(frame["capability"], "rag.chat"); |
| 1064 | assert_eq!( |
| 1065 | raw::keys(&frame["payload"]), |
| 1066 | ["asker", "asker_role", "history", "message", "scope"], |
| 1067 | "the documented rag.chat request payload keys" |
| 1068 | ); |
| 1069 | assert_eq!( |
| 1070 | raw::keys(&frame["payload"]["scope"][0]), |
| 1071 | ["ders", "sinif"], |
| 1072 | "a scope pair is routed by (sinif, ders)" |
| 1073 | ); |
| 1074 | |
| 1075 | let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON"); |
| 1076 | assert!( |
| 1077 | text.contains(r#""scope":[{"ders":"Fizik","sinif":"11"}]"#), |
| 1078 | "{text}" |
| 1079 | ); |
| 1080 | |
| 1081 | let reply = serde_json::to_value(RagChatReplyPayload { |
| 1082 | text: "F = m·a [1]".into(), |
| 1083 | abstained: false, |
| 1084 | reason: String::new(), |
| 1085 | citations: vec![RagCitation { |
| 1086 | n: 1, |
| 1087 | doc_id: "01DOC".into(), |
| 1088 | pages: vec![3], |
| 1089 | span_ids: vec!["s-7".into()], |
| 1090 | ders: Some("Fizik".into()), |
| 1091 | }], |
| 1092 | }) |
| 1093 | .unwrap(); |
| 1094 | let id = frame["id"].as_str().expect("trace id").to_string(); |
| 1095 | raw::answer( |
| 1096 | send, |
| 1097 | format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{reply}}}"#) |
| 1098 | .as_bytes(), |
| 1099 | ) |
| 1100 | .await; |
| 1101 | |
| 1102 | let answer = call.await.unwrap().unwrap(); |
| 1103 | assert_eq!( |
| 1104 | raw::keys(&answer), |
| 1105 | ["abstained", "citations", "reason", "text"], |
| 1106 | "the documented rag.chat reply payload keys" |
| 1107 | ); |
| 1108 | assert_eq!( |
| 1109 | raw::keys(&answer["citations"][0]), |
| 1110 | ["ders", "doc_id", "n", "pages", "span_ids"], |
| 1111 | "the documented citation keys" |
| 1112 | ); |
| 1113 | } |
| 1114 | |
| 1115 | |
| 1116 | |
| 1117 | |
| 1118 | |
| 1119 | |
| 1120 | |
| 1121 | |
| 1122 | |
| 1123 | |
| 1124 | |
| 1125 | |
| 1126 | async fn armed(bridge: &AiBridge) -> (axum::Router, String) { |
| 1127 | let (app, db) = common::app_with_ai(Some(bridge.clone())).await; |
| 1128 | let cookie = common::login_as(&app, &db, "ayse", "student").await; |
| 1129 | let student = common::me_id(&app, &cookie).await; |
| 1130 | (app, student) |
| 1131 | } |
| 1132 | |
| 1133 | #[tokio::test] |
| 1134 | async fn the_api_request_field_names_are_the_published_literals() { |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | let bridge = bridge().await; |
| 1139 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 1140 | await_workers(&bridge, 1).await; |
| 1141 | let (_app, student) = armed(&bridge).await; |
| 1142 | |
| 1143 | let (answer, bytes) = raw::api_read( |
| 1144 | &service.conn, |
| 1145 | format!( |
| 1146 | r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","school":"{SCHOOL}","path":"/notes","query":"limit=1&offset=0","on_behalf_of":"{student}","method":"GET"}}"# |
| 1147 | ) |
| 1148 | .as_bytes(), |
| 1149 | ) |
| 1150 | .await; |
| 1151 | |
| 1152 | assert_eq!( |
| 1153 | raw::keys(&answer), |
| 1154 | ["body", "id", "outcome", "school", "status"], |
| 1155 | "api answer shape changed: {answer}" |
| 1156 | ); |
| 1157 | assert_eq!(answer["outcome"], "ok"); |
| 1158 | assert_eq!(answer["status"], 200); |
| 1159 | assert_eq!( |
| 1160 | answer["id"], "01ARZ3NDEKTSV4RRFFQ69G5FAV", |
| 1161 | "the trace id is echoed" |
| 1162 | ); |
| 1163 | assert!(answer["body"]["items"].is_array(), "{answer}"); |
| 1164 | |
| 1165 | |
| 1166 | let text = String::from_utf8(bytes).expect("the answer frame is UTF-8 JSON"); |
| 1167 | assert!(text.contains(r#""outcome":"ok""#), "{text}"); |
| 1168 | assert!(text.contains(r#""status":200"#), "{text}"); |
| 1169 | } |
| 1170 | |
| 1171 | #[tokio::test] |
| 1172 | async fn only_id_and_path_are_required_of_an_api_request() { |
| 1173 | |
| 1174 | |
| 1175 | let bridge = bridge().await; |
| 1176 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 1177 | await_workers(&bridge, 1).await; |
| 1178 | let (_app, _student) = armed(&bridge).await; |
| 1179 | |
| 1180 | let (answer, _) = raw::api_read( |
| 1181 | &service.conn, |
| 1182 | br#"{"id":"trace-1","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me","unknown_field":true}"#, |
| 1183 | ) |
| 1184 | .await; |
| 1185 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| 1186 | assert_eq!(answer["status"], 200); |
| 1187 | |
| 1188 | assert_eq!(answer["body"]["role"], "ai", "{answer}"); |
| 1189 | } |
| 1190 | |
| 1191 | #[tokio::test] |
| 1192 | async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() { |
| 1193 | |
| 1194 | |
| 1195 | |
| 1196 | let bridge = bridge().await; |
| 1197 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 1198 | await_workers(&bridge, 1).await; |
| 1199 | let (_app, _student) = armed(&bridge).await; |
| 1200 | |
| 1201 | let cases = [ |
| 1202 | ( |
| 1203 | "method_not_allowed", |
| 1204 | r#"{"id":"t1","school":"019732e3-7b00-7000-8000-00000000dead","path":"/notes","method":"DELETE"}"#.to_string(), |
| 1205 | ), |
| 1206 | ( |
| 1207 | "method_not_allowed", |
| 1208 | |
| 1209 | r#"{"id":"t2","school":"019732e3-7b00-7000-8000-00000000dead","path":"/notes","method":"get"}"#.to_string(), |
| 1210 | ), |
| 1211 | ( |
| 1212 | "path_not_allowed", |
| 1213 | r#"{"id":"t3","school":"019732e3-7b00-7000-8000-00000000dead","path":"/courses"}"#.to_string(), |
| 1214 | ), |
| 1215 | ( |
| 1216 | |
| 1217 | "method_not_allowed", |
| 1218 | r#"{"id":"t4","school":"019732e3-7b00-7000-8000-00000000dead","path":"/nope","method":"POST"}"#.to_string(), |
| 1219 | ), |
| 1220 | ( |
| 1221 | "unknown_user", |
| 1222 | r#"{"id":"t5","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me","on_behalf_of":"nobodyatall"}"# |
| 1223 | .to_string(), |
| 1224 | ), |
| 1225 | ( |
| 1226 | "malformed", |
| 1227 | r#"{"id":"t6","school":"019732e3-7b00-7000-8000-00000000dead","path":42}"#.to_string(), |
| 1228 | ), |
| 1229 | |
| 1230 | ("malformed", r#"{"id":"t7","path":"/auth/me"}"#.to_string()), |
| 1231 | |
| 1232 | |
| 1233 | ( |
| 1234 | "unknown_school", |
| 1235 | r#"{"id":"t8","school":"NOT A SLUG","path":"/auth/me"}"#.to_string(), |
| 1236 | ), |
| 1237 | |
| 1238 | ( |
| 1239 | "unknown_school", |
| 1240 | r#"{"id":"t9","school":"019732e3-7b00-7000-8000-00000000eeee","path":"/auth/me"}"#.to_string(), |
| 1241 | ), |
| 1242 | ]; |
| 1243 | |
| 1244 | for (expected_code, request) in cases { |
| 1245 | let (answer, _) = raw::api_read(&service.conn, request.as_bytes()).await; |
| 1246 | assert_eq!( |
| 1247 | raw::keys(&answer), |
| 1248 | ["code", "id", "message", "outcome", "school"], |
| 1249 | "refusal shape changed for {expected_code}: {answer}" |
| 1250 | ); |
| 1251 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1252 | assert_eq!( |
| 1253 | answer["code"], expected_code, |
| 1254 | "refusal code spelling changed: {answer}" |
| 1255 | ); |
| 1256 | assert!( |
| 1257 | answer["message"].as_str().is_some_and(|m| !m.is_empty()), |
| 1258 | "message must be a string a service can log: {answer}" |
| 1259 | ); |
| 1260 | |
| 1261 | |
| 1262 | assert!( |
| 1263 | answer["id"].as_str().is_some_and(|i| i.starts_with('t')), |
| 1264 | "{answer}" |
| 1265 | ); |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | #[tokio::test] |
| 1270 | async fn an_api_read_answers_a_named_user_with_that_users_own_data() { |
| 1271 | |
| 1272 | |
| 1273 | |
| 1274 | let bridge = bridge().await; |
| 1275 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 1276 | await_workers(&bridge, 1).await; |
| 1277 | let (_app, student) = armed(&bridge).await; |
| 1278 | |
| 1279 | let (answer, _) = raw::api_read( |
| 1280 | &service.conn, |
| 1281 | format!( |
| 1282 | r#"{{"id":"tme","school":"{SCHOOL}","path":"/auth/me","on_behalf_of":"{student}"}}"# |
| 1283 | ) |
| 1284 | .as_bytes(), |
| 1285 | ) |
| 1286 | .await; |
| 1287 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| 1288 | assert_eq!(answer["status"], 200); |
| 1289 | assert_eq!(answer["body"]["id"], student, "{answer}"); |
| 1290 | assert_eq!(answer["body"]["role"], "student", "{answer}"); |
| 1291 | } |
| 1292 | |
| 1293 | |
| 1294 | |
| 1295 | |
| 1296 | |
| 1297 | |
| 1298 | |
| 1299 | |
| 1300 | |
| 1301 | |
| 1302 | |
| 1303 | async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, String) { |
| 1304 | let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; |
| 1305 | let beta_db = tenants |
| 1306 | .create( |
| 1307 | hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(), |
| 1308 | "Beta College", |
| 1309 | ModuleSet::all(), |
| 1310 | ) |
| 1311 | .await |
| 1312 | .expect("a second school"); |
| 1313 | |
| 1314 | let demo_cookie = common::login_as(&app, &demo_db, "ayse", "student").await; |
| 1315 | let beta_cookie = common::login_as_school(&app, &beta_db, "beta", "ayse", "student").await; |
| 1316 | let demo_ayse = common::me_id(&app, &demo_cookie).await; |
| 1317 | let beta_ayse = common::me_id(&app, &beta_cookie).await; |
| 1318 | assert_ne!( |
| 1319 | demo_ayse, beta_ayse, |
| 1320 | "two schools, two separate `ayse` rows" |
| 1321 | ); |
| 1322 | (app, tenants, demo_ayse, beta_ayse) |
| 1323 | } |
| 1324 | |
| 1325 | #[tokio::test] |
| 1326 | async fn an_api_read_answers_out_of_the_school_the_frame_named() { |
| 1327 | |
| 1328 | |
| 1329 | |
| 1330 | |
| 1331 | let bridge = bridge().await; |
| 1332 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 1333 | await_workers(&bridge, 1).await; |
| 1334 | let (_app, _tenants, demo_ayse, beta_ayse) = two_schools(&bridge).await; |
| 1335 | |
| 1336 | for (school, who) in [("019732e3-7b00-7000-8000-00000000dead", &demo_ayse), ("019732e3-7b00-7000-8000-00000000beef", &beta_ayse)] { |
| 1337 | let (answer, _) = raw::api_read( |
| 1338 | &service.conn, |
| 1339 | format!( |
| 1340 | r#"{{"id":"t-own","school":"{school}","path":"/auth/me","on_behalf_of":"{who}"}}"# |
| 1341 | ) |
| 1342 | .as_bytes(), |
| 1343 | ) |
| 1344 | .await; |
| 1345 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| 1346 | assert_eq!(answer["school"], school, "the school is echoed: {answer}"); |
| 1347 | assert_eq!(answer["body"]["id"], who.as_str(), "{answer}"); |
| 1348 | assert_eq!(answer["body"]["username"], "ayse"); |
| 1349 | } |
| 1350 | |
| 1351 | |
| 1352 | for (school, who) in [("019732e3-7b00-7000-8000-00000000dead", &beta_ayse), ("019732e3-7b00-7000-8000-00000000beef", &demo_ayse)] { |
| 1353 | let (answer, _) = raw::api_read( |
| 1354 | &service.conn, |
| 1355 | format!( |
| 1356 | r#"{{"id":"t-cross","school":"{school}","path":"/auth/me","on_behalf_of":"{who}"}}"# |
| 1357 | ) |
| 1358 | .as_bytes(), |
| 1359 | ) |
| 1360 | .await; |
| 1361 | assert_eq!( |
| 1362 | answer["code"], "unknown_user", |
| 1363 | "a user id from another school resolved in `{school}`: {answer}" |
| 1364 | ); |
| 1365 | } |
| 1366 | } |
| 1367 | |
| 1368 | #[tokio::test] |
| 1369 | async fn a_suspended_school_is_refused_with_its_own_code() { |
| 1370 | |
| 1371 | |
| 1372 | let bridge = bridge().await; |
| 1373 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 1374 | await_workers(&bridge, 1).await; |
| 1375 | let (_app, tenants, _demo_ayse, beta_ayse) = two_schools(&bridge).await; |
| 1376 | |
| 1377 | let read = format!( |
| 1378 | r#"{{"id":"t-susp","school":"019732e3-7b00-7000-8000-00000000beef","path":"/auth/me","on_behalf_of":"{beta_ayse}"}}"# |
| 1379 | ); |
| 1380 | let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await; |
| 1381 | assert_eq!(answer["outcome"], "ok", "the school starts out active"); |
| 1382 | |
| 1383 | tenants |
| 1384 | .set_status(&SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(), SchoolStatus::Suspended) |
| 1385 | .await |
| 1386 | .expect("suspend beta"); |
| 1387 | |
| 1388 | let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await; |
| 1389 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1390 | assert_eq!(answer["code"], "school_suspended", "{answer}"); |
| 1391 | assert_eq!( |
| 1392 | answer["school"], "019732e3-7b00-7000-8000-00000000beef", |
| 1393 | "the refusal names the school back" |
| 1394 | ); |
| 1395 | assert_eq!(answer["id"], "t-susp"); |
| 1396 | |
| 1397 | |
| 1398 | let (answer, _) = raw::api_read( |
| 1399 | &service.conn, |
| 1400 | br#"{"id":"t-neighbour","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me"}"#, |
| 1401 | ) |
| 1402 | .await; |
| 1403 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| 1404 | } |
| 1405 | |
| 1406 | #[tokio::test] |
| 1407 | async fn a_blob_read_names_its_school_too() { |
| 1408 | |
| 1409 | |
| 1410 | let bridge = bridge().await; |
| 1411 | let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; |
| 1412 | await_workers(&bridge, 1).await; |
| 1413 | let (_app, student, file, uploaded, _tenants) = armed_with_file(&bridge).await; |
| 1414 | |
| 1415 | let (header, _, body) = raw::blob_read( |
| 1416 | &service.conn, |
| 1417 | format!( |
| 1418 | r#"{{"id":"t-b1","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"# |
| 1419 | ) |
| 1420 | .as_bytes(), |
| 1421 | ) |
| 1422 | .await; |
| 1423 | assert_eq!(header["status"], "ok", "{header}"); |
| 1424 | assert_eq!(body.len(), uploaded.len()); |
| 1425 | |
| 1426 | for (school, code) in [("019732e3-7b00-7000-8000-00000000eeee", "unknown_school"), ("NOT A SLUG", "unknown_school")] { |
| 1427 | let (header, _, body) = raw::blob_read( |
| 1428 | &service.conn, |
| 1429 | format!( |
| 1430 | r#"{{"id":"t-b2","school":"{school}","file":"{file}","on_behalf_of":"{student}"}}"# |
| 1431 | ) |
| 1432 | .as_bytes(), |
| 1433 | ) |
| 1434 | .await; |
| 1435 | assert_eq!(header["status"], "err", "{header}"); |
| 1436 | assert_eq!(header["code"], code, "{header}"); |
| 1437 | assert!(body.is_empty(), "a refused blob stream carries no bytes"); |
| 1438 | } |
| 1439 | |
| 1440 | |
| 1441 | let (header, _, _) = raw::blob_read( |
| 1442 | &service.conn, |
| 1443 | format!(r#"{{"id":"t-b3","file":"{file}","on_behalf_of":"{student}"}}"#).as_bytes(), |
| 1444 | ) |
| 1445 | .await; |
| 1446 | assert_eq!(header["code"], "malformed", "{header}"); |
| 1447 | } |
| 1448 | |
| 1449 | |
| 1450 | |
| 1451 | |
| 1452 | |
| 1453 | |
| 1454 | |
| 1455 | |
| 1456 | |
| 1457 | |
| 1458 | async fn armed_with_file(bridge: &AiBridge) -> (axum::Router, String, String, Vec<u8>, Tenants) { |
| 1459 | let (app, db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; |
| 1460 | let student_cookie = common::login_as(&app, &db, "ayse", "student").await; |
| 1461 | let student = common::me_id(&app, &student_cookie).await; |
| 1462 | let teacher = common::login_as(&app, &db, "hoca", "teacher").await; |
| 1463 | let mudur = common::login_as(&app, &db, "mudur", "manager").await; |
| 1464 | |
| 1465 | |
| 1466 | let t = common::taught_under(&app, &mudur, &teacher, "Physics").await; |
| 1467 | common::enroll(&app, &teacher, &t.instance, &student).await; |
| 1468 | let course = t.course.clone(); |
| 1469 | |
| 1470 | let res = common::send( |
| 1471 | &app, |
| 1472 | "POST", |
| 1473 | "/course-notes", |
| 1474 | Some(&teacher), |
| 1475 | Some(json!({ "course": course, "title": "Newton", "content": "F = ma" })), |
| 1476 | ) |
| 1477 | .await; |
| 1478 | assert_eq!(res.status, 201, "{}", res.body); |
| 1479 | let note = common::id_of(&res.body); |
| 1480 | |
| 1481 | |
| 1482 | |
| 1483 | let uploaded: Vec<u8> = (0..200 * 1024u32).map(|i| (i % 251) as u8).collect(); |
| 1484 | let res = common::upload_file_at( |
| 1485 | &app, |
| 1486 | &teacher, |
| 1487 | &format!("/course-notes/{note}/files"), |
| 1488 | "recap.pdf", |
| 1489 | "application/pdf", |
| 1490 | &uploaded, |
| 1491 | ) |
| 1492 | .await; |
| 1493 | assert_eq!(res.status, 201, "{}", res.body); |
| 1494 | let file = common::id_of(&res.body); |
| 1495 | (app, student, file, uploaded, tenants) |
| 1496 | } |
| 1497 | |
| 1498 | #[tokio::test] |
| 1499 | async fn the_blob_header_frame_carries_exactly_the_published_keys_then_size_bytes() { |
| 1500 | |
| 1501 | |
| 1502 | |
| 1503 | |
| 1504 | let bridge = bridge().await; |
| 1505 | let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; |
| 1506 | await_workers(&bridge, 1).await; |
| 1507 | let (_app, student, file, uploaded, _tenants) = armed_with_file(&bridge).await; |
| 1508 | |
| 1509 | let (header, bytes, body) = raw::blob_read( |
| 1510 | &service.conn, |
| 1511 | format!( |
| 1512 | r#"{{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"# |
| 1513 | ) |
| 1514 | .as_bytes(), |
| 1515 | ) |
| 1516 | .await; |
| 1517 | |
| 1518 | assert_eq!( |
| 1519 | raw::keys(&header), |
| 1520 | ["content_type", "id", "name", "school", "size", "status"], |
| 1521 | "blob header shape changed: {header}" |
| 1522 | ); |
| 1523 | assert_eq!(header["status"], "ok"); |
| 1524 | assert_eq!( |
| 1525 | header["id"], "01ARZ3NDEKTSV4RRFFQ69G5FAV", |
| 1526 | "the trace id is echoed" |
| 1527 | ); |
| 1528 | assert_eq!(header["name"], "recap.pdf"); |
| 1529 | assert_eq!(header["content_type"], "application/pdf"); |
| 1530 | assert_eq!(header["size"], uploaded.len(), "{header}"); |
| 1531 | |
| 1532 | |
| 1533 | |
| 1534 | let text = String::from_utf8(bytes).expect("the header frame is UTF-8 JSON"); |
| 1535 | assert!(text.contains(r#""status":"ok""#), "{text}"); |
| 1536 | assert!( |
| 1537 | text.contains(&format!(r#""size":{}"#, uploaded.len())), |
| 1538 | "{text}" |
| 1539 | ); |
| 1540 | |
| 1541 | |
| 1542 | assert_eq!(body.len(), uploaded.len(), "`size` bytes then EOF"); |
| 1543 | assert!(body == uploaded, "the bytes differ from what was uploaded"); |
| 1544 | } |
| 1545 | |
| 1546 | #[tokio::test] |
| 1547 | async fn a_blob_refusal_frame_carries_exactly_the_published_keys_and_no_bytes() { |
| 1548 | let bridge = bridge().await; |
| 1549 | let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; |
| 1550 | await_workers(&bridge, 1).await; |
| 1551 | let (_app, student, file, _uploaded, tenants) = armed_with_file(&bridge).await; |
| 1552 | |
| 1553 | let (header, _, body) = raw::blob_read( |
| 1554 | &service.conn, |
| 1555 | format!( |
| 1556 | r#"{{"id":"t-blob","school":"{SCHOOL}","file":"01NOSUCHFILE","on_behalf_of":"{student}"}}"# |
| 1557 | ) |
| 1558 | .as_bytes(), |
| 1559 | ) |
| 1560 | .await; |
| 1561 | assert_eq!( |
| 1562 | raw::keys(&header), |
| 1563 | ["code", "id", "message", "school", "status"], |
| 1564 | "blob refusal shape changed: {header}" |
| 1565 | ); |
| 1566 | assert_eq!(header["status"], "err"); |
| 1567 | assert_eq!(header["code"], "not_found"); |
| 1568 | assert_eq!(header["id"], "t-blob"); |
| 1569 | assert!(body.is_empty(), "a refusal is followed by nothing at all"); |
| 1570 | |
| 1571 | |
| 1572 | |
| 1573 | |
| 1574 | let mut modules = ModuleSet::all(); |
| 1575 | modules.remove(hezarfen_backend::module::Module::CourseNotes); |
| 1576 | tenants |
| 1577 | .set_modules(&SchoolId::try_parse(SCHOOL).unwrap(), &modules) |
| 1578 | .await |
| 1579 | .expect("take course_notes off the demo school"); |
| 1580 | |
| 1581 | let (header, _, body) = raw::blob_read( |
| 1582 | &service.conn, |
| 1583 | format!( |
| 1584 | r#"{{"id":"t-mod","school":"{SCHOOL}","file":"{file}","on_behalf_of":"{student}"}}"# |
| 1585 | ) |
| 1586 | .as_bytes(), |
| 1587 | ) |
| 1588 | .await; |
| 1589 | assert_eq!( |
| 1590 | raw::keys(&header), |
| 1591 | ["code", "id", "message", "school", "status"], |
| 1592 | "blob refusal shape changed: {header}" |
| 1593 | ); |
| 1594 | assert_eq!(header["code"], "module_disabled", "{header}"); |
| 1595 | assert_eq!(header["school"], SCHOOL, "{header}"); |
| 1596 | assert_eq!(header["id"], "t-mod"); |
| 1597 | assert!(body.is_empty(), "a refused blob stream carries no bytes"); |
| 1598 | } |
| 1599 | |
| 1600 | #[tokio::test] |
| 1601 | async fn an_api_read_still_answers_on_the_shared_client_stream_path() { |
| 1602 | |
| 1603 | |
| 1604 | |
| 1605 | |
| 1606 | |
| 1607 | |
| 1608 | let bridge = bridge().await; |
| 1609 | let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; |
| 1610 | await_workers(&bridge, 1).await; |
| 1611 | let (_app, student, file, _uploaded, _tenants) = armed_with_file(&bridge).await; |
| 1612 | |
| 1613 | let (answer, _) = raw::api_read( |
| 1614 | &service.conn, |
| 1615 | format!( |
| 1616 | r#"{{"id":"t-api","school":"{SCHOOL}","path":"/auth/me","on_behalf_of":"{student}"}}"# |
| 1617 | ) |
| 1618 | .as_bytes(), |
| 1619 | ) |
| 1620 | .await; |
| 1621 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| 1622 | assert_eq!(answer["status"], 200); |
| 1623 | assert_eq!(answer["body"]["id"], student, "{answer}"); |
| 1624 | |
| 1625 | |
| 1626 | |
| 1627 | let (answer, _) = raw::api_read( |
| 1628 | &service.conn, |
| 1629 | format!( |
| 1630 | r#"{{"id":"t-both","school":"{SCHOOL}","path":"/auth/me","file":"{file}","on_behalf_of":"{student}"}}"# |
| 1631 | ) |
| 1632 | .as_bytes(), |
| 1633 | ) |
| 1634 | .await; |
| 1635 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| 1636 | assert_eq!(answer["status"], 200); |
| 1637 | |
| 1638 | |
| 1639 | let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"019732e3-7b00-7000-8000-00000000dead"}"#).await; |
| 1640 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1641 | assert_eq!(answer["code"], "malformed"); |
| 1642 | assert_eq!(answer["id"], "t-neither"); |
| 1643 | } |
| 1644 | |
| 1645 | |
| 1646 | |
| 1647 | |
| 1648 | |
| 1649 | |
| 1650 | |
| 1651 | |
| 1652 | |
| 1653 | |
| 1654 | |
| 1655 | |
| 1656 | #[tokio::test] |
| 1657 | async fn a_capability_call_carries_exactly_the_published_keys() { |
| 1658 | let bridge = bridge().await; |
| 1659 | let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await; |
| 1660 | await_workers(&bridge, 1).await; |
| 1661 | |
| 1662 | |
| 1663 | let (app, db) = common::app_with_ai(Some(bridge.clone())).await; |
| 1664 | let _ = db; |
| 1665 | let ayse = common::login(&app, "ayse").await; |
| 1666 | let student = common::me_id(&app, &ayse).await; |
| 1667 | |
| 1668 | let body = format!( |
| 1669 | r#"{{"id":"t-cap","school":"{SCHOOL}","capability":"insight.summary.upsert","payload":{{"rows":[{{"student":"{student}","marks":{{"ortalama":72}},"confidence":"stable","computed_at":1700000000000,"retain_until":1800000000000}}]}}}}"# |
| 1670 | ); |
| 1671 | let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; |
| 1672 | |
| 1673 | assert_eq!( |
| 1674 | raw::keys(&answer), |
| 1675 | ["id", "payload", "school", "status"], |
| 1676 | "capability answer shape changed: {answer}" |
| 1677 | ); |
| 1678 | assert_eq!(answer["status"], "ok", "{answer}"); |
| 1679 | assert_eq!(answer["id"], "t-cap"); |
| 1680 | assert_eq!( |
| 1681 | answer["school"], SCHOOL, |
| 1682 | "the answer echoes the school the call named" |
| 1683 | ); |
| 1684 | assert_eq!(answer["payload"]["written"], 1, "{answer}"); |
| 1685 | } |
| 1686 | |
| 1687 | #[tokio::test] |
| 1688 | async fn a_capability_refusal_is_flat_and_never_reports_ok() { |
| 1689 | |
| 1690 | |
| 1691 | |
| 1692 | let bridge = bridge().await; |
| 1693 | let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await; |
| 1694 | await_workers(&bridge, 1).await; |
| 1695 | let (_app, _db) = common::app_with_ai(Some(bridge.clone())).await; |
| 1696 | |
| 1697 | let body = format!( |
| 1698 | r#"{{"id":"t-nope","school":"{SCHOOL}","capability":"insight.database.query","payload":{{"sql":"select 1"}}}}"# |
| 1699 | ); |
| 1700 | let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; |
| 1701 | assert_eq!( |
| 1702 | raw::keys(&answer), |
| 1703 | ["code", "id", "message", "school", "status"], |
| 1704 | "capability refusal shape changed: {answer}" |
| 1705 | ); |
| 1706 | assert_eq!(answer["status"], "err", "{answer}"); |
| 1707 | assert_eq!(answer["code"], "unknown_capability", "{answer}"); |
| 1708 | assert_eq!(answer["id"], "t-nope"); |
| 1709 | assert_eq!(answer["school"], SCHOOL); |
| 1710 | assert!( |
| 1711 | answer["message"].as_str().is_some_and(|m| !m.is_empty()), |
| 1712 | "message must be a string a service can log" |
| 1713 | ); |
| 1714 | } |
| 1715 | |
| 1716 | #[tokio::test] |
| 1717 | async fn the_capability_shape_does_not_steal_the_shapes_that_existed_before() { |
| 1718 | |
| 1719 | |
| 1720 | |
| 1721 | let bridge = bridge().await; |
| 1722 | let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; |
| 1723 | await_workers(&bridge, 1).await; |
| 1724 | let (app, _db) = common::app_with_ai(Some(bridge.clone())).await; |
| 1725 | let ayse = common::login(&app, "ayse").await; |
| 1726 | let student = common::me_id(&app, &ayse).await; |
| 1727 | |
| 1728 | |
| 1729 | let body = format!( |
| 1730 | r#"{{"id":"t-both","school":"{SCHOOL}","path":"/auth/me","capability":"insight.pending.list","payload":{{}},"on_behalf_of":"{student}"}}"# |
| 1731 | ); |
| 1732 | let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; |
| 1733 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| 1734 | assert_eq!(answer["status"], 200, "{answer}"); |
| 1735 | |
| 1736 | |
| 1737 | |
| 1738 | let body = format!( |
| 1739 | r#"{{"id":"t-pending","school":"{SCHOOL}","capability":"insight.pending.list","payload":{{}}}}"# |
| 1740 | ); |
| 1741 | let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; |
| 1742 | assert_eq!(answer["status"], "ok", "{answer}"); |
| 1743 | assert_eq!(answer["payload"]["students"], json!([]), "{answer}"); |
| 1744 | |
| 1745 | |
| 1746 | let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"019732e3-7b00-7000-8000-00000000dead"}"#).await; |
| 1747 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1748 | assert_eq!(answer["code"], "malformed"); |
| 1749 | } |