1use crate::cli::AppServerBuilder;
46use crate::error::{Error, ParseError, Result};
47use crate::jsonrpc::{
48 JsonRpcError, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, RequestId,
49};
50use crate::messages::{Notification, ServerMessage, ServerRequest};
51use crate::protocol::{
52 ClientInfo, InitializeParams, InitializeResponse, ThreadArchiveParams, ThreadArchiveResponse,
53 ThreadDeleteParams, ThreadDeleteResponse, ThreadForkParams, ThreadForkResponse,
54 ThreadItemsListParams, ThreadItemsListResponse, ThreadResumeParams, ThreadResumeResponse,
55 ThreadRevertParams, ThreadRevertResponse, ThreadStartParams, ThreadStartResponse,
56 ThreadTurnsListParams, ThreadTurnsListResponse, TurnInterruptParams, TurnInterruptResponse,
57 TurnStartParams, TurnStartResponse, TurnSteerParams, TurnSteerResponse,
58};
59use crate::protocol_generated::types::{
60 CancelLoginAccountParams, CancelLoginAccountResponse, GetAccountParams,
61 GetAccountRateLimitsParams, GetAccountRateLimitsResponse, GetAccountResponse,
62 GetAccountTokenUsageParams, GetAccountTokenUsageResponse, LoginAccountParams,
63 LoginAccountResponse, LogoutAccountResponse,
64};
65use log::{debug, error, warn};
66use serde::de::DeserializeOwned;
67use serde::Serialize;
68use std::collections::VecDeque;
69use std::sync::atomic::{AtomicI64, Ordering};
70use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter};
71use tokio::process::Child;
72
73const STDOUT_BUFFER_SIZE: usize = 10 * 1024 * 1024;
75
76pub struct AsyncClient {
90 child: Child,
91 writer: BufWriter<tokio::process::ChildStdin>,
92 reader: BufReader<tokio::process::ChildStdout>,
93 inbound_frame: Vec<u8>,
95 _stderr_drain: tokio::task::JoinHandle<()>,
99 next_id: AtomicI64,
100 buffered: VecDeque<ServerMessage>,
103}
104
105impl AsyncClient {
106 pub fn new(mut child: Child) -> Result<Self> {
113 let stdin = child
114 .stdin
115 .take()
116 .ok_or_else(|| Error::Protocol("Failed to get stdin".to_string()))?;
117 let stdout = child
118 .stdout
119 .take()
120 .ok_or_else(|| Error::Protocol("Failed to get stdout".to_string()))?;
121 let stderr = child
122 .stderr
123 .take()
124 .ok_or_else(|| Error::Protocol("Failed to get stderr".to_string()))?;
125
126 let stderr_drain = crate::stderr_drain::spawn_async(stderr);
131
132 Ok(Self {
133 child,
134 writer: BufWriter::new(stdin),
135 reader: BufReader::with_capacity(STDOUT_BUFFER_SIZE, stdout),
136 inbound_frame: Vec::new(),
137 _stderr_drain: stderr_drain,
138 next_id: AtomicI64::new(1),
139 buffered: VecDeque::new(),
140 })
141 }
142
143 pub async fn start() -> Result<Self> {
155 Self::start_with(AppServerBuilder::new()).await
156 }
157
158 pub async fn start_with(builder: AppServerBuilder) -> Result<Self> {
169 let mut client = Self::spawn(builder).await?;
170 client
171 .initialize(&InitializeParams {
172 client_info: ClientInfo {
173 name: "codex-codes".to_string(),
174 version: env!("CARGO_PKG_VERSION").to_string(),
175 title: None,
176 },
177 capabilities: None,
178 })
179 .await?;
180 Ok(client)
181 }
182
183 pub async fn spawn(builder: AppServerBuilder) -> Result<Self> {
189 crate::version::check_codex_version_async().await?;
190 Self::new(builder.spawn().await?)
191 }
192
193 pub async fn request<P: Serialize, R: DeserializeOwned>(
206 &mut self,
207 method: &str,
208 params: &P,
209 ) -> Result<R> {
210 let id = RequestId::Integer(self.next_id.fetch_add(1, Ordering::Relaxed));
211
212 let req = JsonRpcRequest {
213 id: id.clone(),
214 method: method.to_string(),
215 params: Some(serde_json::to_value(params).map_err(Error::Json)?),
216 };
217
218 self.send_raw(&req).await?;
219
220 loop {
222 let msg = self.read_message().await?;
223 match msg {
224 JsonRpcMessage::Response(resp) if resp.id == id => {
225 let result: R = serde_json::from_value(resp.result).map_err(Error::Json)?;
226 return Ok(result);
227 }
228 JsonRpcMessage::Error(err) if err.id == id => {
229 return Err(err.error.into());
230 }
231 JsonRpcMessage::Notification(notif) => {
233 let typed = Notification::from_envelope(¬if.method, notif.params)
234 .map_err(Error::Json)?;
235 self.buffered.push_back(ServerMessage::Notification(typed));
236 }
237 JsonRpcMessage::Request(req) => {
238 let typed = ServerRequest::from_envelope(&req.method, req.params)
239 .map_err(Error::Json)?;
240 self.buffered.push_back(ServerMessage::Request {
241 id: req.id,
242 request: typed,
243 });
244 }
245 JsonRpcMessage::Response(resp) => {
247 warn!(
248 "[CLIENT] Unexpected response for id={}, expected id={}",
249 resp.id, id
250 );
251 }
252 JsonRpcMessage::Error(err) => {
253 warn!(
254 "[CLIENT] Unexpected error for id={}, expected id={}",
255 err.id, id
256 );
257 }
258 }
259 }
260 }
261
262 pub async fn thread_start(
267 &mut self,
268 params: &ThreadStartParams,
269 ) -> Result<ThreadStartResponse> {
270 self.request(crate::protocol::methods::THREAD_START, params)
271 .await
272 }
273
274 pub async fn thread_resume(
278 &mut self,
279 params: &ThreadResumeParams,
280 ) -> Result<ThreadResumeResponse> {
281 self.request(crate::protocol::methods::THREAD_RESUME, params)
282 .await
283 }
284
285 pub async fn thread_fork(&mut self, params: &ThreadForkParams) -> Result<ThreadForkResponse> {
287 self.request(crate::protocol::methods::THREAD_FORK, params)
288 .await
289 }
290
291 pub async fn turn_start(&mut self, params: &TurnStartParams) -> Result<TurnStartResponse> {
296 self.request(crate::protocol::methods::TURN_START, params)
297 .await
298 }
299
300 pub async fn turn_steer(&mut self, params: &TurnSteerParams) -> Result<TurnSteerResponse> {
303 self.request(crate::protocol::methods::TURN_STEER, params)
304 .await
305 }
306
307 pub async fn thread_items_list(
310 &mut self,
311 params: &ThreadItemsListParams,
312 ) -> Result<ThreadItemsListResponse> {
313 self.request(crate::protocol::methods::THREAD_ITEMS_LIST, params)
314 .await
315 }
316
317 pub async fn thread_turns_list(
320 &mut self,
321 params: &ThreadTurnsListParams,
322 ) -> Result<ThreadTurnsListResponse> {
323 self.request(crate::protocol::methods::THREAD_TURNS_LIST, params)
324 .await
325 }
326
327 pub async fn thread_revert(
331 &mut self,
332 params: &ThreadRevertParams,
333 ) -> Result<ThreadRevertResponse> {
334 self.request(crate::protocol::methods::THREAD_REVERT, params)
335 .await
336 }
337
338 pub async fn turn_interrupt(
340 &mut self,
341 params: &TurnInterruptParams,
342 ) -> Result<TurnInterruptResponse> {
343 self.request(crate::protocol::methods::TURN_INTERRUPT, params)
344 .await
345 }
346
347 pub async fn thread_archive(
349 &mut self,
350 params: &ThreadArchiveParams,
351 ) -> Result<ThreadArchiveResponse> {
352 self.request(crate::protocol::methods::THREAD_ARCHIVE, params)
353 .await
354 }
355
356 pub async fn thread_delete(
358 &mut self,
359 params: &ThreadDeleteParams,
360 ) -> Result<ThreadDeleteResponse> {
361 self.request(crate::protocol::methods::THREAD_DELETE, params)
362 .await
363 }
364
365 pub async fn initialize(&mut self, params: &InitializeParams) -> Result<InitializeResponse> {
371 let resp: InitializeResponse = self
372 .request(crate::protocol::methods::INITIALIZE, params)
373 .await?;
374 self.send_notification(crate::protocol::methods::INITIALIZED)
375 .await?;
376 Ok(resp)
377 }
378
379 pub async fn respond<R: Serialize>(&mut self, id: RequestId, result: &R) -> Result<()> {
386 let resp = JsonRpcResponse {
387 id,
388 result: serde_json::to_value(result).map_err(Error::Json)?,
389 };
390 self.send_raw(&resp).await
391 }
392
393 pub async fn respond_error(&mut self, id: RequestId, code: i64, message: &str) -> Result<()> {
395 let err = JsonRpcError {
396 id,
397 error: crate::jsonrpc::JsonRpcErrorData {
398 code,
399 message: message.to_string(),
400 data: None,
401 },
402 };
403 self.send_raw(&err).await
404 }
405
406 pub async fn next_message(&mut self) -> Result<Option<ServerMessage>> {
426 if let Some(msg) = self.buffered.pop_front() {
428 return Ok(Some(msg));
429 }
430
431 loop {
433 let msg = match self.read_message_opt().await? {
434 Some(m) => m,
435 None => return Ok(None),
436 };
437
438 match msg {
439 JsonRpcMessage::Notification(notif) => {
440 let JsonRpcNotification { method, params } = notif;
441 let typed =
442 Notification::from_envelope(&method, params.clone()).map_err(|e| {
443 Error::Deserialization(ParseError::from_envelope(method, params, e))
444 })?;
445 return Ok(Some(ServerMessage::Notification(typed)));
446 }
447 JsonRpcMessage::Request(req) => {
448 let JsonRpcRequest { id, method, params } = req;
449 let typed =
450 ServerRequest::from_envelope(&method, params.clone()).map_err(|e| {
451 Error::Deserialization(ParseError::from_envelope(method, params, e))
452 })?;
453 return Ok(Some(ServerMessage::Request { id, request: typed }));
454 }
455 JsonRpcMessage::Response(resp) => {
457 warn!(
458 "[CLIENT] Unexpected response (no pending request): id={}",
459 resp.id
460 );
461 }
462 JsonRpcMessage::Error(err) => {
463 warn!(
464 "[CLIENT] Unexpected error (no pending request): id={} code={}",
465 err.id, err.error.code
466 );
467 }
468 }
469 }
470 }
471
472 pub fn events(&mut self) -> EventStream<'_> {
478 EventStream { client: self }
479 }
480
481 pub fn pid(&self) -> Option<u32> {
483 self.child.id()
484 }
485
486 pub async fn account_read(&mut self, params: &GetAccountParams) -> Result<GetAccountResponse> {
491 self.request(crate::protocol::methods::ACCOUNT_READ, params)
492 .await
493 }
494
495 pub async fn account_login_start(
502 &mut self,
503 params: &LoginAccountParams,
504 ) -> Result<LoginAccountResponse> {
505 self.request(crate::protocol::methods::ACCOUNT_LOGIN_START, params)
506 .await
507 }
508
509 pub async fn account_login_cancel(
511 &mut self,
512 params: &CancelLoginAccountParams,
513 ) -> Result<CancelLoginAccountResponse> {
514 self.request(crate::protocol::methods::ACCOUNT_LOGIN_CANCEL, params)
515 .await
516 }
517
518 pub async fn account_logout(&mut self) -> Result<LogoutAccountResponse> {
520 self.request(
521 crate::protocol::methods::ACCOUNT_LOGOUT,
522 &serde_json::json!({}),
523 )
524 .await
525 }
526
527 pub async fn account_rate_limits_read(
533 &mut self,
534 params: GetAccountRateLimitsParams,
535 ) -> Result<GetAccountRateLimitsResponse> {
536 self.request(crate::protocol::methods::ACCOUNT_RATELIMITS_READ, ¶ms)
537 .await
538 }
539
540 pub async fn account_usage_read(&mut self) -> Result<GetAccountTokenUsageResponse> {
544 self.account_usage_read_with(&GetAccountTokenUsageParams::default())
545 .await
546 }
547
548 pub async fn account_usage_read_with(
553 &mut self,
554 params: &GetAccountTokenUsageParams,
555 ) -> Result<GetAccountTokenUsageResponse> {
556 self.request(crate::protocol::methods::ACCOUNT_USAGE_READ, params)
557 .await
558 }
559
560 pub fn is_alive(&mut self) -> bool {
562 self.child.try_wait().ok().flatten().is_none()
563 }
564
565 pub async fn shutdown(mut self) -> Result<()> {
570 debug!("[CLIENT] Shutting down");
571 self.child.kill().await.map_err(Error::Io)?;
572 Ok(())
573 }
574
575 async fn send_notification(&mut self, method: &str) -> Result<()> {
578 let notif = JsonRpcNotification {
579 method: method.to_string(),
580 params: None,
581 };
582 self.send_raw(¬if).await
583 }
584
585 async fn send_raw<T: Serialize>(&mut self, msg: &T) -> Result<()> {
586 let json = serde_json::to_string(msg).map_err(Error::Json)?;
587 debug!("[CLIENT] Sending: {}", json);
588 self.writer
589 .write_all(json.as_bytes())
590 .await
591 .map_err(Error::Io)?;
592 self.writer.write_all(b"\n").await.map_err(Error::Io)?;
593 self.writer.flush().await.map_err(Error::Io)?;
594 Ok(())
595 }
596
597 async fn read_message(&mut self) -> Result<JsonRpcMessage> {
598 self.read_message_opt().await?.ok_or(Error::ServerClosed)
599 }
600
601 async fn read_message_opt(&mut self) -> Result<Option<JsonRpcMessage>> {
602 loop {
603 let bytes_read = self
607 .reader
608 .read_until(b'\n', &mut self.inbound_frame)
609 .await
610 .map_err(Error::Io)?;
611
612 if bytes_read == 0 {
613 debug!("[CLIENT] Stream closed (EOF)");
614 if self.inbound_frame.is_empty() {
615 return Ok(None);
616 }
617 }
618
619 if !self.inbound_frame.ends_with(b"\n") && bytes_read != 0 {
620 continue;
621 }
622
623 let line = match std::str::from_utf8(&self.inbound_frame) {
624 Ok(line) => line,
625 Err(error) => {
626 let error = std::io::Error::new(std::io::ErrorKind::InvalidData, error);
627 self.inbound_frame.clear();
628 return Err(Error::Io(error));
629 }
630 };
631 let trimmed = line.trim();
632 if trimmed.is_empty() {
633 self.inbound_frame.clear();
634 continue;
635 }
636
637 debug!("[CLIENT] Received: {}", trimmed);
638
639 let decoded = serde_json::from_str::<JsonRpcMessage>(trimmed);
640 match decoded {
641 Ok(msg) => {
642 self.inbound_frame.clear();
643 return Ok(Some(msg));
644 }
645 Err(e) => {
646 warn!(
647 "[CLIENT] Failed to deserialize message. \
648 Please report this at https://github.com/meawoppl/rust-code-agent-sdks/issues"
649 );
650 warn!("[CLIENT] Parse error: {}", e);
651 warn!("[CLIENT] Raw: {}", trimmed);
652 let parse_error = ParseError::from_line(trimmed, e);
653 self.inbound_frame.clear();
654 return Err(Error::Deserialization(parse_error));
655 }
656 }
657 }
658 }
659}
660
661impl Drop for AsyncClient {
662 fn drop(&mut self) {
663 if self.is_alive() {
664 if let Err(e) = self.child.start_kill() {
665 error!("Failed to kill app-server process on drop: {}", e);
666 }
667 }
668 }
669}
670
671pub struct EventStream<'a> {
673 client: &'a mut AsyncClient,
674}
675
676impl EventStream<'_> {
677 pub async fn next(&mut self) -> Option<Result<ServerMessage>> {
679 match self.client.next_message().await {
680 Ok(Some(msg)) => Some(Ok(msg)),
681 Ok(None) => None,
682 Err(e) => Some(Err(e)),
683 }
684 }
685
686 pub async fn collect(mut self) -> Result<Vec<ServerMessage>> {
688 let mut msgs = Vec::new();
689 while let Some(result) = self.next().await {
690 msgs.push(result?);
691 }
692 Ok(msgs)
693 }
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699 use crate::protocol::ModelProviderError;
700 use std::process::Stdio;
701 use tokio::process::Command;
702
703 #[cfg(unix)]
704 fn scripted_client(script: &str) -> AsyncClient {
705 let mut command = Command::new("sh");
706 command
707 .arg("-c")
708 .arg(script)
709 .stdin(Stdio::piped())
710 .stdout(Stdio::piped())
711 .stderr(Stdio::piped());
712 AsyncClient::new(command.spawn().expect("spawn scripted app-server"))
713 .expect("construct async client")
714 }
715
716 fn unknown_method(message: ServerMessage) -> String {
717 match message {
718 ServerMessage::Notification(Notification::Unknown { method, .. }) => method,
719 other => panic!("expected unknown notification, got {other:?}"),
720 }
721 }
722
723 #[test]
724 fn test_buffer_size() {
725 assert_eq!(STDOUT_BUFFER_SIZE, 10 * 1024 * 1024);
726 }
727
728 #[cfg(unix)]
729 #[tokio::test]
730 async fn request_error_keeps_model_provider_data() {
731 let mut client = scripted_client(
732 r#"IFS= read -r req; printf '%s\n' '{"id":1,"error":{"code":-32600,"message":"provider mismatch","data":{"type":"modelProviderMismatch","modelProvider":"old","currentModelProvider":"new"}}}'"#,
733 );
734 let params = ThreadResumeParams {
735 thread_id: "thr_1".to_string(),
736 ..Default::default()
737 };
738 let err = client.thread_resume(¶ms).await.unwrap_err();
739
740 assert!(matches!(
741 &err,
742 Error::JsonRpc { code: -32600, message, data: Some(_) } if message == "provider mismatch"
743 ));
744 assert_eq!(
745 err.model_provider_error(),
746 Some(ModelProviderError::ModelProviderMismatch {
747 model_provider: "old".to_string(),
748 current_model_provider: "new".to_string(),
749 })
750 );
751 }
752
753 #[cfg(unix)]
754 #[tokio::test]
755 async fn account_usage_read_with_sends_thread_id() {
756 let mut client = scripted_client(
758 r#"IFS= read -r req; case "$req" in *'"params":{"threadId":"thr_1"}'*) printf '%s\n' '{"id":1,"result":{"summary":{},"threadUsage":{"threadId":"thr_1","estimatedUsageCreditsMicros":5,"nativeUsageUsdMicros":1200,"groups":[]}}}' ;; *) printf '%s\n' '{"id":1,"error":{"code":-1,"message":"unexpected params"}}' ;; esac"#,
759 );
760 let usage = client
761 .account_usage_read_with(&GetAccountTokenUsageParams {
762 thread_id: Some("thr_1".to_string()),
763 })
764 .await
765 .expect("thread usage");
766 let thread = usage.thread_usage.expect("thread_usage");
767 assert_eq!(thread.thread_id, "thr_1");
768 assert_eq!(thread.native_usage_usd_micros, Some(1200));
769 }
770
771 #[cfg(unix)]
772 #[tokio::test]
773 async fn account_usage_read_sends_empty_params() {
774 let mut client = scripted_client(
775 r#"IFS= read -r req; case "$req" in *'"params":{}'*) printf '%s\n' '{"id":1,"result":{"summary":{}}}' ;; *) printf '%s\n' '{"id":1,"error":{"code":-1,"message":"unexpected params"}}' ;; esac"#,
776 );
777 let usage = client.account_usage_read().await.expect("account usage");
778 assert!(usage.thread_usage.is_none());
779 }
780
781 #[cfg(unix)]
782 #[tokio::test]
783 async fn cancelled_next_message_resumes_partial_frame_exactly_once() {
784 const PARTIAL: &[u8] = br#"{"method":"test/first","params":{"part":"#;
785 let mut client = scripted_client(
786 r#"printf '%s' '{"method":"test/first","params":{"part":'; IFS= read -r release; printf '%s\n' '1}}'; printf '%s\n' '{"method":"test/second","params":{}}'"#,
787 );
788
789 assert_eq!(
790 client
791 .reader
792 .fill_buf()
793 .await
794 .expect("buffer partial frame"),
795 PARTIAL
796 );
797 let mut pending_read = Box::pin(client.next_message());
798 tokio::select! {
799 biased;
800 result = &mut pending_read => panic!("partial frame completed unexpectedly: {result:?}"),
801 _ = async {} => {}
802 }
803 drop(pending_read);
804 assert!(!client.inbound_frame.is_empty());
807 assert!(PARTIAL.starts_with(&client.inbound_frame));
808 client
809 .writer
810 .write_all(b"release\n")
811 .await
812 .expect("release remaining frame");
813 client.writer.flush().await.expect("flush release");
814
815 let first = client
816 .next_message()
817 .await
818 .expect("resume first frame")
819 .expect("first message");
820 let second = client
821 .next_message()
822 .await
823 .expect("read second frame")
824 .expect("second message");
825
826 assert_eq!(unknown_method(first), "test/first");
827 assert_eq!(unknown_method(second), "test/second");
828 assert!(client.next_message().await.expect("read EOF").is_none());
829 }
830
831 #[cfg(unix)]
832 #[tokio::test]
833 async fn cancelled_request_preserves_shared_decoder_framing() {
834 const PARTIAL: &[u8] = br#"{"id":1,"result":{"abandoned":"#;
835 let mut client = scripted_client(
836 r#"printf '%s' '{"id":1,"result":{"abandoned":'; IFS= read -r first; IFS= read -r release; printf '%s\n' 'true}}' '{"method":"test/between","params":{}}'; IFS= read -r second; printf '%s\n' '{"id":2,"result":{"ok":true}}' '{"method":"test/after","params":{}}'"#,
837 );
838
839 assert_eq!(
840 client
841 .reader
842 .fill_buf()
843 .await
844 .expect("buffer partial response"),
845 PARTIAL
846 );
847 let params = serde_json::json!({});
848 let mut pending_request =
849 Box::pin(client.request::<_, serde_json::Value>("test/abandoned", ¶ms));
850 tokio::select! {
851 biased;
852 result = &mut pending_request => panic!("partial response completed unexpectedly: {result:?}"),
853 _ = async {} => {}
854 }
855 drop(pending_request);
856 assert!(!client.inbound_frame.is_empty());
859 assert!(PARTIAL.starts_with(&client.inbound_frame));
860 client
861 .writer
862 .write_all(b"release\n")
863 .await
864 .expect("release remaining response");
865 client.writer.flush().await.expect("flush release");
866
867 let response: serde_json::Value = client
868 .request("test/resumed", &serde_json::json!({}))
869 .await
870 .expect("second request should resume the shared decoder");
871 assert_eq!(response, serde_json::json!({"ok": true}));
872
873 let between = client
874 .next_message()
875 .await
876 .expect("read buffered notification")
877 .expect("between message");
878 let after = client
879 .next_message()
880 .await
881 .expect("read trailing notification")
882 .expect("after message");
883 assert_eq!(unknown_method(between), "test/between");
884 assert_eq!(unknown_method(after), "test/after");
885 assert!(client.next_message().await.expect("read EOF").is_none());
886 }
887
888 #[cfg(unix)]
889 #[tokio::test]
890 async fn next_message_resumes_notification_partially_read_by_cancelled_request() {
891 const PARTIAL: &[u8] = br#"{"method":"test/during-request","params":{"part":"#;
892 let mut client = scripted_client(
893 r#"printf '%s' '{"method":"test/during-request","params":{"part":'; IFS= read -r request; IFS= read -r release; printf '%s\n' '1}}' '{"id":1,"result":{}}'"#,
894 );
895
896 assert_eq!(
897 client
898 .reader
899 .fill_buf()
900 .await
901 .expect("buffer partial notification"),
902 PARTIAL
903 );
904 let params = serde_json::json!({});
905 let mut pending_request =
906 Box::pin(client.request::<_, serde_json::Value>("test/abandoned", ¶ms));
907 tokio::select! {
908 biased;
909 result = &mut pending_request => panic!("partial notification completed unexpectedly: {result:?}"),
910 _ = async {} => {}
911 }
912 drop(pending_request);
913 assert!(!client.inbound_frame.is_empty());
916 assert!(PARTIAL.starts_with(&client.inbound_frame));
917 client
918 .writer
919 .write_all(b"release\n")
920 .await
921 .expect("release remaining notification");
922 client.writer.flush().await.expect("flush release");
923
924 let notification = client
925 .next_message()
926 .await
927 .expect("resume partial notification")
928 .expect("notification");
929 assert_eq!(unknown_method(notification), "test/during-request");
930 assert!(client.next_message().await.expect("read EOF").is_none());
931 }
932
933 #[cfg(unix)]
934 #[tokio::test]
935 async fn request_resumes_notification_partially_read_by_cancelled_next_message() {
936 const PARTIAL: &[u8] = br#"{"method":"test/before-request","params":{"part":"#;
937 let mut client = scripted_client(
938 r#"printf '%s' '{"method":"test/before-request","params":{"part":'; IFS= read -r release; printf '%s\n' '1}}'; IFS= read -r request; printf '%s\n' '{"id":1,"result":{"ok":true}}'"#,
939 );
940
941 assert_eq!(
942 client
943 .reader
944 .fill_buf()
945 .await
946 .expect("buffer partial notification"),
947 PARTIAL
948 );
949 let mut pending_read = Box::pin(client.next_message());
950 tokio::select! {
951 biased;
952 result = &mut pending_read => panic!("partial notification completed unexpectedly: {result:?}"),
953 _ = async {} => {}
954 }
955 drop(pending_read);
956 assert!(!client.inbound_frame.is_empty());
959 assert!(PARTIAL.starts_with(&client.inbound_frame));
960 client
961 .writer
962 .write_all(b"release\n")
963 .await
964 .expect("release remaining notification");
965 client.writer.flush().await.expect("flush release");
966
967 let response: serde_json::Value = client
968 .request("test/resumed", &serde_json::json!({}))
969 .await
970 .expect("request should resume the shared decoder");
971 assert_eq!(response, serde_json::json!({"ok": true}));
972
973 let notification = client
974 .next_message()
975 .await
976 .expect("read buffered notification")
977 .expect("notification");
978 assert_eq!(unknown_method(notification), "test/before-request");
979 assert!(client.next_message().await.expect("read EOF").is_none());
980 }
981
982 #[cfg(unix)]
983 #[tokio::test]
984 async fn request_directly_resumes_response_partially_read_by_cancelled_next_message() {
985 const PARTIAL: &[u8] = br#"{"id":1,"result":{"ok":"#;
986 let mut client = scripted_client(
989 r#"printf '%s' '{"id":1,"result":{"ok":'; IFS= read -r request; printf '%s\n' 'true}}'"#,
990 );
991
992 assert_eq!(
993 client
994 .reader
995 .fill_buf()
996 .await
997 .expect("buffer partial response"),
998 PARTIAL
999 );
1000 let mut pending_read = Box::pin(client.next_message());
1001 tokio::select! {
1002 biased;
1003 result = &mut pending_read => panic!("partial response completed unexpectedly: {result:?}"),
1004 _ = async {} => {}
1005 }
1006 drop(pending_read);
1007 assert!(!client.inbound_frame.is_empty());
1010 assert!(PARTIAL.starts_with(&client.inbound_frame));
1011 assert!(client.buffered.is_empty());
1012
1013 let response: serde_json::Value = client
1014 .request("test/resumed", &serde_json::json!({}))
1015 .await
1016 .expect("request should directly resume the partial response");
1017 assert_eq!(response, serde_json::json!({"ok": true}));
1018 assert!(client.buffered.is_empty());
1019 assert!(client.next_message().await.expect("read EOF").is_none());
1020 }
1021}