client_integration.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. use std::collections::HashMap;
  2. use std::sync::Arc;
  3. use std::time::Duration;
  4. use api::{
  5. AnthropicClient, ApiError, ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent,
  6. InputContentBlock, InputMessage, MessageDeltaEvent, MessageRequest, OutputContentBlock,
  7. StreamEvent, ToolChoice, ToolDefinition,
  8. };
  9. use serde_json::json;
  10. use telemetry::{ClientIdentity, MemoryTelemetrySink, SessionTracer, TelemetryEvent};
  11. use tokio::io::{AsyncReadExt, AsyncWriteExt};
  12. use tokio::net::TcpListener;
  13. use tokio::sync::Mutex;
  14. #[tokio::test]
  15. async fn send_message_posts_json_and_parses_response() {
  16. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  17. let body = concat!(
  18. "{",
  19. "\"id\":\"msg_test\",",
  20. "\"type\":\"message\",",
  21. "\"role\":\"assistant\",",
  22. "\"content\":[{\"type\":\"text\",\"text\":\"Hello from Claude\"}],",
  23. "\"model\":\"claude-3-7-sonnet-latest\",",
  24. "\"stop_reason\":\"end_turn\",",
  25. "\"stop_sequence\":null,",
  26. "\"usage\":{\"input_tokens\":12,\"output_tokens\":4},",
  27. "\"request_id\":\"req_body_123\"",
  28. "}"
  29. );
  30. let server = spawn_server(
  31. state.clone(),
  32. vec![http_response("200 OK", "application/json", body)],
  33. )
  34. .await;
  35. let client = AnthropicClient::new("test-key")
  36. .with_auth_token(Some("proxy-token".to_string()))
  37. .with_base_url(server.base_url());
  38. let response = client
  39. .send_message(&sample_request(false))
  40. .await
  41. .expect("request should succeed");
  42. assert_eq!(response.id, "msg_test");
  43. assert_eq!(response.total_tokens(), 16);
  44. assert_eq!(response.request_id.as_deref(), Some("req_body_123"));
  45. assert_eq!(
  46. response.content,
  47. vec![OutputContentBlock::Text {
  48. text: "Hello from Claude".to_string(),
  49. }]
  50. );
  51. let captured = state.lock().await;
  52. let request = captured.first().expect("server should capture request");
  53. assert_eq!(request.method, "POST");
  54. assert_eq!(request.path, "/v1/messages");
  55. assert_eq!(
  56. request.headers.get("x-api-key").map(String::as_str),
  57. Some("test-key")
  58. );
  59. assert_eq!(
  60. request.headers.get("authorization").map(String::as_str),
  61. Some("Bearer proxy-token")
  62. );
  63. assert_eq!(
  64. request.headers.get("anthropic-version").map(String::as_str),
  65. Some("2023-06-01")
  66. );
  67. assert_eq!(
  68. request.headers.get("user-agent").map(String::as_str),
  69. Some("claude-code/0.1.0")
  70. );
  71. assert_eq!(
  72. request.headers.get("anthropic-beta").map(String::as_str),
  73. Some("claude-code-20250219")
  74. );
  75. let body: serde_json::Value =
  76. serde_json::from_str(&request.body).expect("request body should be json");
  77. assert_eq!(
  78. body.get("model").and_then(serde_json::Value::as_str),
  79. Some("claude-3-7-sonnet-latest")
  80. );
  81. assert!(body.get("stream").is_none());
  82. assert_eq!(body["tools"][0]["name"], json!("get_weather"));
  83. assert_eq!(body["tool_choice"]["type"], json!("auto"));
  84. assert_eq!(body["betas"], json!(["claude-code-20250219"]));
  85. }
  86. #[tokio::test]
  87. async fn send_message_applies_request_profile_and_records_telemetry() {
  88. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  89. let server = spawn_server(
  90. state.clone(),
  91. vec![http_response_with_headers(
  92. "200 OK",
  93. "application/json",
  94. concat!(
  95. "{",
  96. "\"id\":\"msg_profile\",",
  97. "\"type\":\"message\",",
  98. "\"role\":\"assistant\",",
  99. "\"content\":[{\"type\":\"text\",\"text\":\"ok\"}],",
  100. "\"model\":\"claude-3-7-sonnet-latest\",",
  101. "\"stop_reason\":\"end_turn\",",
  102. "\"stop_sequence\":null,",
  103. "\"usage\":{\"input_tokens\":1,\"output_tokens\":1}",
  104. "}"
  105. ),
  106. &[("request-id", "req_profile_123")],
  107. )],
  108. )
  109. .await;
  110. let sink = Arc::new(MemoryTelemetrySink::default());
  111. let client = AnthropicClient::new("test-key")
  112. .with_base_url(server.base_url())
  113. .with_client_identity(ClientIdentity::new("claude-code", "9.9.9").with_runtime("rust-cli"))
  114. .with_beta("tools-2026-04-01")
  115. .with_extra_body_param("metadata", json!({"source": "clawd-code"}))
  116. .with_session_tracer(SessionTracer::new("session-telemetry", sink.clone()));
  117. let response = client
  118. .send_message(&sample_request(false))
  119. .await
  120. .expect("request should succeed");
  121. assert_eq!(response.request_id.as_deref(), Some("req_profile_123"));
  122. let captured = state.lock().await;
  123. let request = captured.first().expect("server should capture request");
  124. assert_eq!(
  125. request.headers.get("anthropic-beta").map(String::as_str),
  126. Some("claude-code-20250219,tools-2026-04-01")
  127. );
  128. assert_eq!(
  129. request.headers.get("user-agent").map(String::as_str),
  130. Some("claude-code/9.9.9")
  131. );
  132. let body: serde_json::Value =
  133. serde_json::from_str(&request.body).expect("request body should be json");
  134. assert_eq!(body["metadata"]["source"], json!("clawd-code"));
  135. assert_eq!(
  136. body["betas"],
  137. json!(["claude-code-20250219", "tools-2026-04-01"])
  138. );
  139. let events = sink.events();
  140. assert_eq!(events.len(), 4);
  141. assert!(matches!(
  142. &events[0],
  143. TelemetryEvent::HttpRequestStarted {
  144. session_id,
  145. attempt: 1,
  146. method,
  147. path,
  148. ..
  149. } if session_id == "session-telemetry" && method == "POST" && path == "/v1/messages"
  150. ));
  151. assert!(matches!(
  152. &events[1],
  153. TelemetryEvent::SessionTrace(trace) if trace.name == "http_request_started"
  154. ));
  155. assert!(matches!(
  156. &events[2],
  157. TelemetryEvent::HttpRequestSucceeded {
  158. request_id,
  159. status: 200,
  160. ..
  161. } if request_id.as_deref() == Some("req_profile_123")
  162. ));
  163. assert!(matches!(
  164. &events[3],
  165. TelemetryEvent::SessionTrace(trace) if trace.name == "http_request_succeeded"
  166. ));
  167. }
  168. #[tokio::test]
  169. async fn stream_message_parses_sse_events_with_tool_use() {
  170. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  171. let sse = concat!(
  172. "event: message_start\n",
  173. "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_stream\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-3-7-sonnet-latest\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":8,\"output_tokens\":0}}}\n\n",
  174. "event: content_block_start\n",
  175. "data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_123\",\"name\":\"get_weather\",\"input\":{}}}\n\n",
  176. "event: content_block_delta\n",
  177. "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"city\\\":\\\"Paris\\\"}\"}}\n\n",
  178. "event: content_block_stop\n",
  179. "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
  180. "event: message_delta\n",
  181. "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",\"stop_sequence\":null},\"usage\":{\"input_tokens\":8,\"output_tokens\":1}}\n\n",
  182. "event: message_stop\n",
  183. "data: {\"type\":\"message_stop\"}\n\n",
  184. "data: [DONE]\n\n"
  185. );
  186. let server = spawn_server(
  187. state.clone(),
  188. vec![http_response_with_headers(
  189. "200 OK",
  190. "text/event-stream",
  191. sse,
  192. &[("request-id", "req_stream_456")],
  193. )],
  194. )
  195. .await;
  196. let client = AnthropicClient::new("test-key")
  197. .with_auth_token(Some("proxy-token".to_string()))
  198. .with_base_url(server.base_url());
  199. let mut stream = client
  200. .stream_message(&sample_request(false))
  201. .await
  202. .expect("stream should start");
  203. assert_eq!(stream.request_id(), Some("req_stream_456"));
  204. let mut events = Vec::new();
  205. while let Some(event) = stream
  206. .next_event()
  207. .await
  208. .expect("stream event should parse")
  209. {
  210. events.push(event);
  211. }
  212. assert_eq!(events.len(), 6);
  213. assert!(matches!(events[0], StreamEvent::MessageStart(_)));
  214. assert!(matches!(
  215. events[1],
  216. StreamEvent::ContentBlockStart(ContentBlockStartEvent {
  217. content_block: OutputContentBlock::ToolUse { .. },
  218. ..
  219. })
  220. ));
  221. assert!(matches!(
  222. events[2],
  223. StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
  224. delta: ContentBlockDelta::InputJsonDelta { .. },
  225. ..
  226. })
  227. ));
  228. assert!(matches!(events[3], StreamEvent::ContentBlockStop(_)));
  229. assert!(matches!(
  230. events[4],
  231. StreamEvent::MessageDelta(MessageDeltaEvent { .. })
  232. ));
  233. assert!(matches!(events[5], StreamEvent::MessageStop(_)));
  234. match &events[1] {
  235. StreamEvent::ContentBlockStart(ContentBlockStartEvent {
  236. content_block: OutputContentBlock::ToolUse { name, input, .. },
  237. ..
  238. }) => {
  239. assert_eq!(name, "get_weather");
  240. assert_eq!(input, &json!({}));
  241. }
  242. other => panic!("expected tool_use block, got {other:?}"),
  243. }
  244. let captured = state.lock().await;
  245. let request = captured.first().expect("server should capture request");
  246. assert!(request.body.contains("\"stream\":true"));
  247. }
  248. #[tokio::test]
  249. async fn retries_retryable_failures_before_succeeding() {
  250. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  251. let server = spawn_server(
  252. state.clone(),
  253. vec![
  254. http_response(
  255. "429 Too Many Requests",
  256. "application/json",
  257. "{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",\"message\":\"slow down\"}}",
  258. ),
  259. http_response(
  260. "200 OK",
  261. "application/json",
  262. "{\"id\":\"msg_retry\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"Recovered\"}],\"model\":\"claude-3-7-sonnet-latest\",\"stop_reason\":\"end_turn\",\"stop_sequence\":null,\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}",
  263. ),
  264. ],
  265. )
  266. .await;
  267. let client = AnthropicClient::new("test-key")
  268. .with_base_url(server.base_url())
  269. .with_retry_policy(2, Duration::from_millis(1), Duration::from_millis(2));
  270. let response = client
  271. .send_message(&sample_request(false))
  272. .await
  273. .expect("retry should eventually succeed");
  274. assert_eq!(response.total_tokens(), 5);
  275. assert_eq!(state.lock().await.len(), 2);
  276. }
  277. #[tokio::test]
  278. async fn surfaces_retry_exhaustion_for_persistent_retryable_errors() {
  279. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  280. let server = spawn_server(
  281. state.clone(),
  282. vec![
  283. http_response(
  284. "503 Service Unavailable",
  285. "application/json",
  286. "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"busy\"}}",
  287. ),
  288. http_response(
  289. "503 Service Unavailable",
  290. "application/json",
  291. "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"still busy\"}}",
  292. ),
  293. ],
  294. )
  295. .await;
  296. let client = AnthropicClient::new("test-key")
  297. .with_base_url(server.base_url())
  298. .with_retry_policy(1, Duration::from_millis(1), Duration::from_millis(2));
  299. let error = client
  300. .send_message(&sample_request(false))
  301. .await
  302. .expect_err("persistent 503 should fail");
  303. match error {
  304. ApiError::RetriesExhausted {
  305. attempts,
  306. last_error,
  307. } => {
  308. assert_eq!(attempts, 2);
  309. assert!(matches!(
  310. *last_error,
  311. ApiError::Api {
  312. status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
  313. retryable: true,
  314. ..
  315. }
  316. ));
  317. }
  318. other => panic!("expected retries exhausted, got {other:?}"),
  319. }
  320. }
  321. #[tokio::test]
  322. #[ignore = "requires ANTHROPIC_API_KEY and network access"]
  323. async fn live_stream_smoke_test() {
  324. let client = AnthropicClient::from_env().expect("ANTHROPIC_API_KEY must be set");
  325. let mut stream = client
  326. .stream_message(&MessageRequest {
  327. model: std::env::var("ANTHROPIC_MODEL")
  328. .unwrap_or_else(|_| "claude-3-7-sonnet-latest".to_string()),
  329. max_tokens: 32,
  330. messages: vec![InputMessage::user_text(
  331. "Reply with exactly: hello from rust",
  332. )],
  333. system: None,
  334. tools: None,
  335. tool_choice: None,
  336. stream: false,
  337. })
  338. .await
  339. .expect("live stream should start");
  340. while let Some(_event) = stream
  341. .next_event()
  342. .await
  343. .expect("live stream should yield events")
  344. {}
  345. }
  346. #[derive(Debug, Clone, PartialEq, Eq)]
  347. struct CapturedRequest {
  348. method: String,
  349. path: String,
  350. headers: HashMap<String, String>,
  351. body: String,
  352. }
  353. struct TestServer {
  354. base_url: String,
  355. join_handle: tokio::task::JoinHandle<()>,
  356. }
  357. impl TestServer {
  358. fn base_url(&self) -> String {
  359. self.base_url.clone()
  360. }
  361. }
  362. impl Drop for TestServer {
  363. fn drop(&mut self) {
  364. self.join_handle.abort();
  365. }
  366. }
  367. async fn spawn_server(
  368. state: Arc<Mutex<Vec<CapturedRequest>>>,
  369. responses: Vec<String>,
  370. ) -> TestServer {
  371. let listener = TcpListener::bind("127.0.0.1:0")
  372. .await
  373. .expect("listener should bind");
  374. let address = listener
  375. .local_addr()
  376. .expect("listener should have local addr");
  377. let join_handle = tokio::spawn(async move {
  378. for response in responses {
  379. let (mut socket, _) = listener.accept().await.expect("server should accept");
  380. let mut buffer = Vec::new();
  381. let mut header_end = None;
  382. loop {
  383. let mut chunk = [0_u8; 1024];
  384. let read = socket
  385. .read(&mut chunk)
  386. .await
  387. .expect("request read should succeed");
  388. if read == 0 {
  389. break;
  390. }
  391. buffer.extend_from_slice(&chunk[..read]);
  392. if let Some(position) = find_header_end(&buffer) {
  393. header_end = Some(position);
  394. break;
  395. }
  396. }
  397. let header_end = header_end.expect("request should include headers");
  398. let (header_bytes, remaining) = buffer.split_at(header_end);
  399. let header_text =
  400. String::from_utf8(header_bytes.to_vec()).expect("headers should be utf8");
  401. let mut lines = header_text.split("\r\n");
  402. let request_line = lines.next().expect("request line should exist");
  403. let mut parts = request_line.split_whitespace();
  404. let method = parts.next().expect("method should exist").to_string();
  405. let path = parts.next().expect("path should exist").to_string();
  406. let mut headers = HashMap::new();
  407. let mut content_length = 0_usize;
  408. for line in lines {
  409. if line.is_empty() {
  410. continue;
  411. }
  412. let (name, value) = line.split_once(':').expect("header should have colon");
  413. let value = value.trim().to_string();
  414. if name.eq_ignore_ascii_case("content-length") {
  415. content_length = value.parse().expect("content length should parse");
  416. }
  417. headers.insert(name.to_ascii_lowercase(), value);
  418. }
  419. let mut body = remaining[4..].to_vec();
  420. while body.len() < content_length {
  421. let mut chunk = vec![0_u8; content_length - body.len()];
  422. let read = socket
  423. .read(&mut chunk)
  424. .await
  425. .expect("body read should succeed");
  426. if read == 0 {
  427. break;
  428. }
  429. body.extend_from_slice(&chunk[..read]);
  430. }
  431. state.lock().await.push(CapturedRequest {
  432. method,
  433. path,
  434. headers,
  435. body: String::from_utf8(body).expect("body should be utf8"),
  436. });
  437. socket
  438. .write_all(response.as_bytes())
  439. .await
  440. .expect("response write should succeed");
  441. }
  442. });
  443. TestServer {
  444. base_url: format!("http://{address}"),
  445. join_handle,
  446. }
  447. }
  448. fn find_header_end(bytes: &[u8]) -> Option<usize> {
  449. bytes.windows(4).position(|window| window == b"\r\n\r\n")
  450. }
  451. fn http_response(status: &str, content_type: &str, body: &str) -> String {
  452. http_response_with_headers(status, content_type, body, &[])
  453. }
  454. fn http_response_with_headers(
  455. status: &str,
  456. content_type: &str,
  457. body: &str,
  458. headers: &[(&str, &str)],
  459. ) -> String {
  460. let mut extra_headers = String::new();
  461. for (name, value) in headers {
  462. use std::fmt::Write as _;
  463. write!(&mut extra_headers, "{name}: {value}\r\n").expect("header write should succeed");
  464. }
  465. format!(
  466. "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\n{extra_headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
  467. body.len()
  468. )
  469. }
  470. fn sample_request(stream: bool) -> MessageRequest {
  471. MessageRequest {
  472. model: "claude-3-7-sonnet-latest".to_string(),
  473. max_tokens: 64,
  474. messages: vec![InputMessage {
  475. role: "user".to_string(),
  476. content: vec![
  477. InputContentBlock::Text {
  478. text: "Say hello".to_string(),
  479. },
  480. InputContentBlock::ToolResult {
  481. tool_use_id: "toolu_prev".to_string(),
  482. content: vec![api::ToolResultContentBlock::Json {
  483. value: json!({"forecast": "sunny"}),
  484. }],
  485. is_error: false,
  486. },
  487. ],
  488. }],
  489. system: Some("Use tools when needed".to_string()),
  490. tools: Some(vec![ToolDefinition {
  491. name: "get_weather".to_string(),
  492. description: Some("Fetches the weather".to_string()),
  493. input_schema: json!({
  494. "type": "object",
  495. "properties": {"city": {"type": "string"}},
  496. "required": ["city"]
  497. }),
  498. }]),
  499. tool_choice: Some(ToolChoice::Auto),
  500. stream,
  501. }
  502. }