File size: 54,948 Bytes
ea39c0e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 | use std::future::Future;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_exec_server::ExecServerClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestBodyDeltaNotification;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::InitializeParams;
use codex_exec_server::InitializeResponse;
use codex_exec_server::RemoteExecServerConnectArgs;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCNotification;
use codex_exec_server_protocol::JSONRPCRequest;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_exec_server_protocol::MAX_HTTP_BODY_DELTA_BYTES;
use codex_exec_server_protocol::RequestId;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::from_slice;
use serde_json::from_str;
use serde_json::from_value;
use serde_json::to_string;
use serde_json::to_value;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message;
const CLIENT_NAME: &str = "test-exec-server-client";
const HTTP_REQUEST_METHOD: &str = "http/request";
const HTTP_REQUEST_BODY_DELTA_METHOD: &str = "http/request/bodyDelta";
const INITIALIZE_METHOD: &str = "initialize";
const INITIALIZED_METHOD: &str = "initialized";
const TEST_TIMEOUT: Duration = Duration::from_secs(5);
const BYTE_BUDGET_TEST_TIMEOUT: Duration = Duration::from_secs(30);
const HTTP_BODY_DELTA_CHANNEL_CAPACITY: u64 = 256;
const HTTP_BODY_DELTA_BYTE_BUDGET: usize = 16 * 1024 * 1024;
const OVERFLOWING_BODY_DELTA_FRAMES: u64 = 1_024;
/// What this tests: the buffered HTTP helper always sends a buffered
/// `http/request`, even when a caller accidentally provides streaming flags.
#[tokio::test]
async fn http_request_forces_buffered_request_params() -> Result<()> {
// Phase 1: start a fake WebSocket exec-server so the test covers the
// public client connection path without depending on the HTTP runner.
let server = spawn_scripted_exec_server(|mut peer| async move {
// Phase 2: verify the buffered helper forces buffered mode before it
// sends the JSON-RPC call.
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/buffered".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "ignored-stream-id".to_string(),
stream_response: false,
}
);
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: b"buffered".to_vec().into(),
},
)
.await
})
.await?;
let client = server.connect_client().await?;
// Phase 3: call the buffered helper with streaming-only fields populated
// and assert callers still receive the buffered response body.
let response = timeout(
TEST_TIMEOUT,
client.http_request(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/buffered".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "ignored-stream-id".to_string(),
stream_response: true,
}),
)
.await
.context("buffered http/request should complete")??;
assert_eq!(
response,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: b"buffered".to_vec().into(),
}
);
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: streamed executor HTTP response frames are routed by the
/// client's generated request id, delivered in sequence, and concatenated by
/// the caller.
#[tokio::test]
async fn http_response_body_stream_uses_generated_ids_and_receives_ordered_deltas() -> Result<()> {
// Phase 1: script two requests. The caller supplies reusable ids, but the
// client replaces them with connection-local ids on the wire.
let server = spawn_scripted_exec_server(|mut peer| async move {
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp".to_string(),
headers: vec![HttpHeader {
name: "accept".to_string(),
value: "text/event-stream".to_string(),
value_env_var: None,
}],
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
// Phase 2: return headers first, then body notifications in the order
// the public body stream should expose them.
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: vec![HttpHeader {
name: "content-type".to_string(),
value: "text/event-stream".to_string(),
value_env_var: None,
}],
body: Vec::new().into(),
},
)
.await?;
for delta in [
HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq: 1,
delta: b"hello ".to_vec().into(),
done: false,
error: None,
},
HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq: 2,
delta: b"world".to_vec().into(),
done: false,
error: None,
},
HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq: 3,
delta: b"!".to_vec().into(),
done: true,
error: None,
},
] {
peer.write_body_delta(delta).await?;
}
// Phase 3: accept the next generated request id after EOF.
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/reuse".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-2".to_string(),
stream_response: true,
}
);
peer.write_response(
request_id,
HttpRequestResponse {
status: 204,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await
})
.await?;
let client = server.connect_client().await?;
// Phase 4: start a streaming HTTP request through the public client API.
let (response, mut body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp".to_string(),
headers: vec![HttpHeader {
name: "accept".to_string(),
value: "text/event-stream".to_string(),
value_env_var: None,
}],
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("streamed http/request should return headers")??;
assert_eq!(
response,
HttpRequestResponse {
status: 200,
headers: vec![HttpHeader {
name: "content-type".to_string(),
value: "text/event-stream".to_string(),
value_env_var: None,
}],
body: Vec::new().into(),
}
);
// Phase 5: drain the body stream and verify the caller-visible byte order.
let mut body = Vec::new();
while let Some(chunk) = timeout(TEST_TIMEOUT, body_stream.recv())
.await
.context("http response body delta should arrive")??
{
body.extend_from_slice(&chunk);
}
assert_eq!(body, b"hello world!".to_vec());
// Phase 6: start another stream through the public API to validate cleanup
// after EOF without reaching into the client routing table.
let (reuse_response, _reuse_body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/reuse".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("second streamed http/request should return headers")??;
assert_eq!(
reuse_response,
HttpRequestResponse {
status: 204,
headers: Vec::new(),
body: Vec::new().into(),
}
);
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: dropping a body stream with a queued terminal frame removes
/// the old route while the next stream gets a fresh generated id.
#[tokio::test]
async fn http_response_body_stream_drops_queued_terminal_before_next_generated_id() -> Result<()> {
// Phase 1: send terminal EOF before the header response so the public body
// stream starts with EOF already queued but unread.
let server = spawn_scripted_exec_server(|mut peer| async move {
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/queued-terminal".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq: 1,
delta: Vec::new().into(),
done: true,
error: None,
})
.await?;
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
// Phase 2: accept another stream after the client drops the unread
// body. The second request receives a distinct generated id.
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/retry-queued-terminal".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-2".to_string(),
stream_response: true,
}
);
peer.write_response(
request_id,
HttpRequestResponse {
status: 204,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await
})
.await?;
let client = server.connect_client().await?;
// Phase 3: drop the body stream without reading the queued EOF frame.
let (response, body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/queued-terminal".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("streamed http/request should return headers")??;
assert_eq!(
response,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
}
);
drop(body_stream);
// Phase 4: start another stream through the public API. The caller-provided
// id is ignored, so the request uses the next generated route id.
let params = HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/retry-queued-terminal".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
};
let (reuse_response, _reuse_body_stream) =
timeout(TEST_TIMEOUT, client.http_request_stream(params))
.await
.context("second streamed http/request should return headers")??;
assert_eq!(
reuse_response,
HttpRequestResponse {
status: 204,
headers: Vec::new(),
body: Vec::new().into(),
}
);
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: cancelling a streaming HTTP request while it is waiting for
/// headers drops its route, and a later stream gets a fresh generated id.
#[tokio::test]
async fn http_response_body_stream_ignores_late_deltas_after_cancelled_request() -> Result<()> {
// Phase 1: coordinate cancellation after the fake server observes the
// first request but before it returns headers. The server later sends a
// stale delta for the cancelled id before serving the fresh stream.
let (request_seen_tx, request_seen_rx) = oneshot::channel();
let server = spawn_scripted_exec_server(|mut peer| async move {
let (_request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/cancel".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
request_seen_tx
.send(())
.expect("test should wait for the first request");
// Phase 2: the next stream uses a new generated id. A late body delta
// for the cancelled id is ignored by the client-side router.
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/retry-cancelled".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-2".to_string(),
stream_response: true,
}
);
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq: 1,
delta: b"stale".to_vec().into(),
done: false,
error: None,
})
.await?;
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-2".to_string(),
seq: 1,
delta: b"fresh".to_vec().into(),
done: true,
error: None,
})
.await
})
.await?;
let client = server.connect_client().await?;
// Phase 3: start a streaming request and abort the caller future while it
// is blocked waiting for response headers.
let client_for_request = client.clone();
let stream_task = tokio::spawn(async move {
let _ = client_for_request
.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/cancel".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
})
.await;
});
request_seen_rx
.await
.expect("server should observe the first http/request");
stream_task.abort();
let _ = stream_task.await;
// Phase 4: start a new stream immediately. It receives only the fresh body
// bytes for its generated id.
let (response, mut body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/retry-cancelled".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("second streamed http/request should return headers")??;
assert_eq!(
response,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
}
);
let mut body = Vec::new();
while let Some(chunk) = timeout(TEST_TIMEOUT, body_stream.recv())
.await
.context("fresh http response body delta should arrive")??
{
body.extend_from_slice(&chunk);
}
assert_eq!(body, b"fresh".to_vec());
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: dropping a returned body stream before EOF removes its
/// route and prevents stale body deltas from reaching the next stream.
#[tokio::test]
async fn http_response_body_stream_ignores_late_deltas_after_drop() -> Result<()> {
// Phase 1: script two requests. The first returns only headers; after the
// client drops its body receiver, the server sends a stale body delta.
let (body_dropped_tx, body_dropped_rx) = oneshot::channel();
let (stale_delta_sent_tx, stale_delta_sent_rx) = oneshot::channel();
let server = spawn_scripted_exec_server(|mut peer| async move {
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/drop".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
body_dropped_rx
.await
.expect("test should drop the first body stream");
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq: 1,
delta: b"stale".to_vec().into(),
done: false,
error: None,
})
.await?;
stale_delta_sent_tx
.send(())
.expect("test should wait for the stale delta");
// Phase 2: accept the next request with a new generated id. The new
// stream must receive only fresh body bytes.
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/retry-dropped".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-2".to_string(),
stream_response: true,
}
);
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-2".to_string(),
seq: 1,
delta: b"fresh".to_vec().into(),
done: true,
error: None,
})
.await
})
.await?;
let client = server.connect_client().await?;
// Phase 3: receive headers for the first stream, then drop the body stream
// without reading any body frames.
let (response, body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/drop".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("streamed http/request should return headers")??;
assert_eq!(
response,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
}
);
drop(body_stream);
body_dropped_tx
.send(())
.expect("server should wait for the body stream drop");
stale_delta_sent_rx
.await
.expect("server should send one stale nonterminal delta");
// Phase 4: start the next stream immediately. The caller-provided id is
// ignored, and the fresh generated id isolates it from stale bytes.
let (reuse_response, mut reuse_body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/retry-dropped".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("second streamed http/request should return headers")??;
assert_eq!(
reuse_response,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
}
);
let mut body = Vec::new();
while let Some(chunk) = timeout(TEST_TIMEOUT, reuse_body_stream.recv())
.await
.context("fresh http response body delta should arrive")??
{
body.extend_from_slice(&chunk);
}
assert_eq!(body, b"fresh".to_vec());
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: an in-flight streamed HTTP body is failed when the shared
/// JSON-RPC transport disconnects before a terminal body frame.
#[tokio::test]
async fn http_response_body_stream_fails_when_transport_disconnects() -> Result<()> {
// Phase 1: return response headers for a streaming request, then drop the
// fake server transport without sending EOF.
let server = spawn_scripted_exec_server(|mut peer| async move {
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/disconnect".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await
})
.await?;
let client = server.connect_client().await?;
// Phase 2: start a streaming HTTP request and receive headers.
let (_response, mut body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/disconnect".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("streamed http/request should return headers")??;
// Phase 3: assert transport disconnect wakes the body stream with a
// terminal error instead of hanging.
let error = timeout(TEST_TIMEOUT, body_stream.recv())
.await
.context("disconnect should wake http body stream")?
.expect_err("disconnect should fail the http body stream");
let error_message = error.to_string();
assert_eq!(
error_message.starts_with(
"exec-server protocol error: http response stream `http-1` failed: exec-server transport disconnected"
),
true
);
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: an executor cannot make the orchestrator decode and retain
/// a body frame larger than the response-stream wire contract allows.
#[tokio::test]
async fn http_response_body_stream_rejects_oversized_delta() -> Result<()> {
let (finish_tx, finish_rx) = oneshot::channel();
let server = spawn_scripted_exec_server(|mut peer| async move {
let (_request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/oversized-delta".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq: 1,
delta: vec![0; MAX_HTTP_BODY_DELTA_BYTES + 1].into(),
done: false,
error: None,
})
.await?;
finish_rx.await.expect("test should finish server task");
Ok(())
})
.await?;
let client = server.connect_client().await?;
let request = HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/oversized-delta".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
};
let result = timeout(TEST_TIMEOUT, client.http_request_stream(request))
.await
.context("oversized body delta should close the executor transport")?;
let error = match result {
Ok(_) => bail!("oversized body delta should fail the request"),
Err(error) => error,
};
let error = error.to_string();
assert_eq!(error, "exec-server transport disconnected");
finish_tx.send(()).expect("server task should stay active");
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: frame-count backpressure cannot hide an unbounded amount
/// of executor-controlled body bytes across the orchestrator's stream queues.
#[tokio::test]
async fn http_response_body_stream_enforces_queued_byte_budget() -> Result<()> {
let (finish_tx, finish_rx) = oneshot::channel();
let server = spawn_scripted_exec_server(|mut peer| async move {
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/byte-budget".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
let frame_count = HTTP_BODY_DELTA_BYTE_BUDGET / MAX_HTTP_BODY_DELTA_BYTES + 1;
for seq in 1..=frame_count as u64 {
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq,
delta: vec![0; MAX_HTTP_BODY_DELTA_BYTES].into(),
done: false,
error: None,
})
.await?;
}
let (barrier_request_id, barrier_params) = peer.read_http_request().await?;
assert_eq!(
barrier_params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/byte-budget-barrier".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-2".to_string(),
stream_response: true,
}
);
peer.write_response(
barrier_request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-2".to_string(),
seq: 1,
delta: Vec::new().into(),
done: true,
error: None,
})
.await?;
finish_rx.await.expect("test should finish server task");
Ok(())
})
.await?;
let client = server.connect_client().await?;
let (_response, mut body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/byte-budget".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("streamed http/request should return headers")??;
// Receiving this terminal notification proves the earlier byte-budget
// notifications have all passed through the ordered notification handler.
let (_response, mut barrier_stream) = timeout(
BYTE_BUDGET_TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/byte-budget-barrier".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-barrier-id".to_string(),
stream_response: false,
}),
)
.await
.context("barrier http/request should return headers")??;
assert_eq!(
timeout(TEST_TIMEOUT, barrier_stream.recv())
.await
.context("barrier body stream should finish")??,
None
);
let mut delivered_bytes = 0;
let error = loop {
match timeout(TEST_TIMEOUT, body_stream.recv())
.await
.context("queued body stream should finish")?
{
Ok(Some(chunk)) => delivered_bytes += chunk.len(),
Ok(None) => bail!("byte-budget exhaustion should not look like clean EOF"),
Err(error) => break error,
}
};
assert_eq!(delivered_bytes, HTTP_BODY_DELTA_BYTE_BUDGET);
assert!(
error
.to_string()
.contains("queued body deltas exceed 16777216 bytes")
);
finish_tx.send(()).expect("server task should stay active");
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: every response stream on one executor connection shares
/// the same queued-body byte budget.
#[tokio::test]
async fn http_response_body_streams_share_queued_byte_budget() -> Result<()> {
let (finish_tx, finish_rx) = oneshot::channel();
let server = spawn_scripted_exec_server(|mut peer| async move {
for (request_id, url) in [
("http-1", "https://example.test/mcp/shared-budget-one"),
("http-2", "https://example.test/mcp/shared-budget-two"),
] {
let (rpc_request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: url.to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: request_id.to_string(),
stream_response: true,
}
);
peer.write_response(
rpc_request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
}
let frames_per_stream = HTTP_BODY_DELTA_BYTE_BUDGET / MAX_HTTP_BODY_DELTA_BYTES / 2;
for request_id in ["http-1", "http-2"] {
for seq in 1..=frames_per_stream as u64 {
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: request_id.to_string(),
seq,
delta: vec![0; MAX_HTTP_BODY_DELTA_BYTES].into(),
done: false,
error: None,
})
.await?;
}
}
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-2".to_string(),
seq: frames_per_stream as u64 + 1,
delta: vec![0; MAX_HTTP_BODY_DELTA_BYTES].into(),
done: false,
error: None,
})
.await?;
let (barrier_request_id, barrier_params) = peer.read_http_request().await?;
assert_eq!(
barrier_params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/shared-budget-barrier".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-3".to_string(),
stream_response: true,
}
);
peer.write_response(
barrier_request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
for (request_id, seq) in [
("http-3", 1),
("http-1", frames_per_stream as u64 + 1),
("http-2", frames_per_stream as u64 + 2),
] {
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: request_id.to_string(),
seq,
delta: Vec::new().into(),
done: true,
error: None,
})
.await?;
}
finish_rx.await.expect("test should finish server task");
Ok(())
})
.await?;
let client = server.connect_client().await?;
let (_response, mut first_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/shared-budget-one".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-one".to_string(),
stream_response: false,
}),
)
.await
.context("first streamed http/request should return headers")??;
let (_response, mut second_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/shared-budget-two".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-two".to_string(),
stream_response: false,
}),
)
.await
.context("second streamed http/request should return headers")??;
// This terminal notification is ordered after both streams contend for the
// budget, so neither stream is drained before the overflow is observed.
let (_response, mut barrier_stream) = timeout(
BYTE_BUDGET_TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/shared-budget-barrier".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-barrier-id".to_string(),
stream_response: false,
}),
)
.await
.context("barrier http/request should return headers")??;
assert_eq!(
timeout(TEST_TIMEOUT, barrier_stream.recv())
.await
.context("barrier body stream should finish")??,
None
);
let mut failed_stream_bytes = 0;
let error = loop {
match timeout(TEST_TIMEOUT, second_stream.recv())
.await
.context("second body stream should finish")?
{
Ok(Some(chunk)) => failed_stream_bytes += chunk.len(),
Ok(None) => bail!("shared byte-budget exhaustion should not look like clean EOF"),
Err(error) => break error,
}
};
assert_eq!(
(failed_stream_bytes, error.to_string()),
(
HTTP_BODY_DELTA_BYTE_BUDGET / 2,
"exec-server protocol error: http response stream `http-2` failed: queued body deltas exceed 16777216 bytes".to_string(),
)
);
let mut surviving_stream_bytes = 0;
while let Some(chunk) = timeout(TEST_TIMEOUT, first_stream.recv())
.await
.context("first body stream should finish")??
{
surviving_stream_bytes += chunk.len();
}
assert_eq!(surviving_stream_bytes, HTTP_BODY_DELTA_BYTE_BUDGET / 2);
finish_tx.send(()).expect("server task should stay active");
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: transport disconnect still records a terminal stream
/// failure even when the client-side body-delta queue is already full.
#[tokio::test]
async fn http_response_body_stream_reports_disconnect_when_queue_is_full() -> Result<()> {
// Phase 1: fill the queued body-delta route exactly to capacity before the
// response headers arrive, then drop the transport without sending EOF.
let server = spawn_scripted_exec_server(|mut peer| async move {
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/disconnect-full-queue".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
for seq in 1..=HTTP_BODY_DELTA_CHANNEL_CAPACITY {
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq,
delta: b"x".to_vec().into(),
done: false,
error: None,
})
.await?;
}
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await
})
.await?;
let client = server.connect_client().await?;
// Phase 2: start the streaming request and receive headers while the
// queue is already full.
let (_response, mut body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/disconnect-full-queue".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("streamed http/request should return headers")??;
// Phase 3: drain the queued chunks and assert the transport disconnect is
// still reported as an error rather than a clean EOF.
let mut chunks = 0;
let error = loop {
match timeout(TEST_TIMEOUT, body_stream.recv())
.await
.context("disconnect should wake the full queued body stream")?
{
Ok(Some(_chunk)) => {
chunks += 1;
}
Ok(None) => bail!("disconnect with a full queue should not look like clean EOF"),
Err(error) => break error,
}
};
assert_eq!(
(
chunks,
error
.to_string()
.starts_with(
"exec-server protocol error: http response stream `http-1` failed: exec-server transport disconnected",
),
),
(HTTP_BODY_DELTA_CHANNEL_CAPACITY as usize, true)
);
drop(client);
server.finish().await?;
Ok(())
}
/// What this tests: body-delta backpressure closes the public body stream as
/// an error rather than letting callers accept a truncated body as clean EOF.
#[tokio::test]
async fn http_response_body_stream_reports_backpressure_truncation() -> Result<()> {
// Phase 1: send enough body frames before headers to overflow the bounded
// client-side route while the public request future is still pending.
let (finish_tx, finish_rx) = oneshot::channel();
let server = spawn_scripted_exec_server(|mut peer| async move {
let (request_id, params) = peer.read_http_request().await?;
assert_eq!(
params,
HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/backpressure".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "http-1".to_string(),
stream_response: true,
}
);
for seq in 1..=OVERFLOWING_BODY_DELTA_FRAMES {
peer.write_body_delta(HttpRequestBodyDeltaNotification {
request_id: "http-1".to_string(),
seq,
delta: b"x".to_vec().into(),
done: false,
error: None,
})
.await?;
}
peer.write_response(
request_id,
HttpRequestResponse {
status: 200,
headers: Vec::new(),
body: Vec::new().into(),
},
)
.await?;
// Phase 2: keep the transport connected so the body stream reports the
// backpressure failure rather than a disconnect.
finish_rx.await.expect("test should finish server task");
Ok(())
})
.await?;
let client = server.connect_client().await?;
// Phase 3: start the streaming request; the server overfills the route
// before returning the body stream to this consumer.
let (_response, mut body_stream) = timeout(
TEST_TIMEOUT,
client.http_request_stream(HttpRequestParams {
method: "GET".to_string(),
url: "https://example.test/mcp/backpressure".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "caller-stream-id".to_string(),
stream_response: false,
}),
)
.await
.context("streamed http/request should return headers")??;
// Phase 4: drain queued chunks and assert the truncated stream ends in an
// explicit error, not a clean EOF.
let mut chunks = 0;
let error = loop {
match timeout(TEST_TIMEOUT, body_stream.recv())
.await
.context("backpressure should close http body stream")?
{
Ok(Some(_chunk)) => {
chunks += 1;
}
Ok(None) => bail!("backpressure truncation should not look like clean EOF"),
Err(error) => break error,
}
};
assert_eq!(
(
chunks < OVERFLOWING_BODY_DELTA_FRAMES as usize,
error.to_string(),
),
(
true,
"exec-server protocol error: http response stream `http-1` failed: body delta channel filled before delivery".to_string(),
)
);
finish_tx
.send(())
.expect("server task should wait for test completion");
drop(client);
server.finish().await?;
Ok(())
}
/// Fake WebSocket exec-server used by the integration tests.
///
/// The helper exercises `ExecServerClient::connect_websocket`, including the
/// initialize handshake, while each test controls the exact JSON-RPC traffic
/// that follows.
struct ScriptedExecServer {
websocket_url: String,
task: JoinHandle<Result<()>>,
}
impl ScriptedExecServer {
/// Connects the public exec-server client to this fake WebSocket endpoint.
async fn connect_client(&self) -> Result<ExecServerClient> {
ExecServerClient::connect_websocket(RemoteExecServerConnectArgs::new(
self.websocket_url.clone(),
CLIENT_NAME.to_string(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
))
.await
.context("client should connect to fake exec-server")
}
/// Waits for the scripted fake server to finish.
async fn finish(self) -> Result<()> {
self.task
.await
.context("fake exec-server task should join")??;
Ok(())
}
}
/// Starts a fake exec-server that accepts one WebSocket client.
async fn spawn_scripted_exec_server<F, Fut>(script: F) -> Result<ScriptedExecServer>
where
F: FnOnce(JsonRpcPeer) -> Fut + Send + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
let listener = TcpListener::bind("127.0.0.1:0")
.await
.context("fake exec-server should bind")?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let task = tokio::spawn(async move {
let (stream, _) = timeout(TEST_TIMEOUT, listener.accept())
.await
.context("fake exec-server should accept a client")??;
let websocket = accept_async(stream)
.await
.context("fake exec-server websocket handshake should complete")?;
let mut peer = JsonRpcPeer { websocket };
peer.complete_initialize().await?;
script(peer).await
});
Ok(ScriptedExecServer {
websocket_url,
task,
})
}
/// JSON-RPC peer for the fake exec-server WebSocket.
struct JsonRpcPeer {
websocket: WebSocketStream<TcpStream>,
}
impl JsonRpcPeer {
/// Completes and validates the client initialize handshake.
async fn complete_initialize(&mut self) -> Result<()> {
let request = self.read_request(INITIALIZE_METHOD).await?;
let params: InitializeParams = decode_request_params(&request)?;
assert_eq!(
params,
InitializeParams {
client_name: CLIENT_NAME.to_string(),
resume_session_id: None,
}
);
self.write_response(
request.id,
InitializeResponse {
session_id: "session-1".to_string(),
environment_info: None,
},
)
.await?;
self.read_notification(INITIALIZED_METHOD).await?;
Ok(())
}
/// Reads one typed `http/request` call from the client.
async fn read_http_request(&mut self) -> Result<(RequestId, HttpRequestParams)> {
let request = self.read_request(HTTP_REQUEST_METHOD).await?;
let params = decode_request_params(&request)?;
Ok((request.id, params))
}
/// Reads a JSON-RPC request and validates its method.
async fn read_request(&mut self, expected_method: &str) -> Result<JSONRPCRequest> {
let message = self.read_message().await?;
let JSONRPCMessage::Request(request) = message else {
bail!("expected JSON-RPC request `{expected_method}`, got {message:?}");
};
if request.method != expected_method {
bail!(
"expected JSON-RPC request `{expected_method}`, got `{}`",
request.method
);
}
Ok(request)
}
/// Reads a JSON-RPC notification and validates its method.
async fn read_notification(&mut self, expected_method: &str) -> Result<JSONRPCNotification> {
let message = self.read_message().await?;
let JSONRPCMessage::Notification(notification) = message else {
bail!("expected JSON-RPC notification `{expected_method}`, got {message:?}");
};
if notification.method != expected_method {
bail!(
"expected JSON-RPC notification `{expected_method}`, got `{}`",
notification.method
);
}
Ok(notification)
}
/// Sends a successful JSON-RPC response.
async fn write_response<T>(&mut self, id: RequestId, result: T) -> Result<()>
where
T: Serialize,
{
self.write_message(JSONRPCMessage::Response(JSONRPCResponse {
id,
result: to_value(result)?,
}))
.await
}
/// Sends one streamed HTTP body notification.
async fn write_body_delta(&mut self, delta: HttpRequestBodyDeltaNotification) -> Result<()> {
self.write_message(JSONRPCMessage::Notification(JSONRPCNotification {
method: HTTP_REQUEST_BODY_DELTA_METHOD.to_string(),
params: Some(to_value(delta)?),
}))
.await
}
/// Reads one WebSocket JSON-RPC message.
async fn read_message(&mut self) -> Result<JSONRPCMessage> {
let message = timeout(TEST_TIMEOUT, self.websocket.next())
.await
.context("timed out waiting for JSON-RPC message")?
.context("client websocket closed before JSON-RPC message arrived")?
.context("failed to read websocket message")?;
match message {
Message::Text(text) => from_str(text.as_ref()).context("text JSON-RPC"),
Message::Binary(bytes) => from_slice(bytes.as_ref()).context("binary JSON-RPC"),
Message::Close(frame) => bail!("client websocket closed: {frame:?}"),
other => bail!("expected text or binary JSON-RPC message, got {other:?}"),
}
}
/// Writes one WebSocket JSON-RPC message.
async fn write_message(&mut self, message: JSONRPCMessage) -> Result<()> {
let encoded = to_string(&message)?;
timeout(
TEST_TIMEOUT,
self.websocket.send(Message::Text(encoded.into())),
)
.await
.context("timed out writing JSON-RPC message")?
.context("failed to write JSON-RPC message")
}
}
/// Decodes a request params object into its typed protocol payload.
fn decode_request_params<T>(request: &JSONRPCRequest) -> Result<T>
where
T: DeserializeOwned,
{
let params = request
.params
.clone()
.context("JSON-RPC request should include params")?;
from_value(params).context("JSON-RPC request params should decode")
}
|