mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Add a multiplexed stdio transport to the exec server (#65115)
## Why Plain stdio serves one JSON-RPC connection and shuts down when it closes, so clients cannot run concurrent sessions or reconnect to resume a detached session over the same stdin/stdout pair. ## What changed Add `--listen stdio-mux` to serve multiple independent newline-delimited JSON-RPC connections over one HTTP/2 connection on stdin and stdout. Each `CONNECT` stream to `rpc.local` carries one JSON-RPC connection. A client can half-close the request to detach, wait for response EOF, then open a fresh stream and initialize with `resumeSessionId` before the session expires. ## Testing Add tests for concurrent sessions, immediate resume after response EOF, session expiry, and recovery after a stream reset while another stream stays usable. Cover shutdown with a full input queue and verify that a failed stdio write unblocks response senders. GitOrigin-RevId: cdb9638f8b69671a50f44e3eca4dd9059f5bdcd1
This commit is contained in:
Generated
+3
@@ -3464,7 +3464,10 @@ dependencies = [
|
||||
"ctor 0.6.3",
|
||||
"dirs",
|
||||
"futures",
|
||||
"h2",
|
||||
"http 1.4.0",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"libc",
|
||||
"notify",
|
||||
"opentelemetry",
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ Options:
|
||||
|
||||
--listen <URL>
|
||||
Transport endpoint URL. Supported values: `ws://IP:PORT` (default),
|
||||
`stdio`, `stdio://`
|
||||
`stdio`, `stdio://`, `stdio-mux`
|
||||
|
||||
--ws-auth <MODE>
|
||||
Authentication mode for incoming WebSocket connections
|
||||
|
||||
@@ -67,7 +67,7 @@ pub struct ExecServerCommand {
|
||||
)]
|
||||
request_dispatch_mode: codex_exec_server::RequestDispatchMode,
|
||||
|
||||
/// Transport endpoint URL. Supported values: `ws://IP:PORT` (default), `stdio`, `stdio://`.
|
||||
/// Transport endpoint URL. Supported values: `ws://IP:PORT` (default), `stdio`, `stdio://`, `stdio-mux`.
|
||||
#[arg(long = "listen", value_name = "URL")]
|
||||
listen: Option<String>,
|
||||
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ Options:
|
||||
|
||||
--listen <URL>
|
||||
Transport endpoint URL. Supported values: `ws://IP:PORT` (default),
|
||||
`stdio`, `stdio://`
|
||||
`stdio`, `stdio://`, `stdio-mux`
|
||||
|
||||
--ws-auth <MODE>
|
||||
Authentication mode for incoming WebSocket connections
|
||||
|
||||
@@ -50,6 +50,8 @@ codex-websocket-client = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
http = { workspace = true }
|
||||
hyper = { workspace = true }
|
||||
hyper-util = { workspace = true }
|
||||
notify = { workspace = true }
|
||||
opentelemetry = { workspace = true }
|
||||
prost = "0.14.3"
|
||||
@@ -95,6 +97,7 @@ windows-sys = { workspace = true, features = [
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
h2 = "0.4.19"
|
||||
anyhow = { workspace = true }
|
||||
codex-exec-server-test-support = { workspace = true }
|
||||
codex-test-binary-support = { workspace = true }
|
||||
|
||||
@@ -287,6 +287,14 @@ impl JsonRpcConnection {
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
Self::from_stdio_with_disconnect(reader, writer, connection_label).0
|
||||
}
|
||||
|
||||
pub(crate) fn from_stdio_with_disconnect(
|
||||
reader: impl AsyncRead + Unpin + Send + 'static,
|
||||
writer: impl AsyncWrite + Unpin + Send + 'static,
|
||||
connection_label: String,
|
||||
) -> (Self, watch::Sender<bool>) {
|
||||
Self::from_stdio_with_max_message_len(
|
||||
reader,
|
||||
writer,
|
||||
@@ -308,6 +316,7 @@ impl JsonRpcConnection {
|
||||
MAX_STDIO_JSONRPC_MESSAGE_LEN,
|
||||
Some(MAX_CLIENT_INBOUND_REQUEST_LEN),
|
||||
)
|
||||
.0
|
||||
}
|
||||
|
||||
fn from_stdio_with_max_message_len<R, W>(
|
||||
@@ -316,7 +325,7 @@ impl JsonRpcConnection {
|
||||
connection_label: String,
|
||||
max_message_len: usize,
|
||||
max_inbound_request_len: Option<usize>,
|
||||
) -> Self
|
||||
) -> (Self, watch::Sender<bool>)
|
||||
where
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
@@ -442,10 +451,13 @@ impl JsonRpcConnection {
|
||||
}
|
||||
});
|
||||
|
||||
let disconnect = disconnected_tx.clone();
|
||||
let writer_task = tokio::spawn(async move {
|
||||
let mut writer = BufWriter::new(writer);
|
||||
while let Some(message) = outgoing_rx.recv().await {
|
||||
if let Err(err) = write_jsonrpc_line_message(&mut writer, &message).await {
|
||||
// Unblock response senders before enqueueing disconnect on a full input queue.
|
||||
outgoing_rx.close();
|
||||
send_disconnected(
|
||||
&incoming_tx,
|
||||
&disconnected_tx,
|
||||
@@ -459,13 +471,14 @@ impl JsonRpcConnection {
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
let connection = Self {
|
||||
outgoing_tx,
|
||||
incoming_rx,
|
||||
disconnected_rx,
|
||||
task_handles: vec![reader_task, writer_task],
|
||||
transport: JsonRpcTransport::Plain,
|
||||
}
|
||||
};
|
||||
(connection, disconnect)
|
||||
}
|
||||
|
||||
pub(crate) fn from_websocket<T, E>(stream: T, connection_label: String) -> Self
|
||||
@@ -831,6 +844,26 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_stdio_write_closes_outbound_even_when_inbound_is_full() -> anyhow::Result<()> {
|
||||
let message = test_jsonrpc_message();
|
||||
let input = format!("{}\n", serde_json::to_string(&message)?).repeat(CHANNEL_CAPACITY);
|
||||
let (writer, peer) = tokio::io::duplex(/*max_buf_size*/ 1);
|
||||
drop(peer);
|
||||
let mut connection = JsonRpcConnection::from_stdio(
|
||||
std::io::Cursor::new(input),
|
||||
writer,
|
||||
"test stdio peer".into(),
|
||||
);
|
||||
|
||||
// The reader signals EOF after enqueueing every message.
|
||||
timeout(Duration::from_secs(1), connection.disconnected_rx.changed()).await??;
|
||||
assert_eq!(connection.incoming_rx.len(), CHANNEL_CAPACITY);
|
||||
connection.outgoing_tx.send(message).await?;
|
||||
timeout(Duration::from_secs(1), connection.outgoing_tx.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdio_connection_accepts_message_at_size_limit() -> anyhow::Result<()> {
|
||||
let message = test_jsonrpc_message();
|
||||
@@ -840,7 +873,7 @@ mod tests {
|
||||
for line_ending in [b"\n".as_slice(), b"\r\n".as_slice()] {
|
||||
let (reader, mut peer) =
|
||||
tokio::io::duplex(max_message_len.saturating_add(line_ending.len()));
|
||||
let mut connection = JsonRpcConnection::from_stdio_with_max_message_len(
|
||||
let (mut connection, _) = JsonRpcConnection::from_stdio_with_max_message_len(
|
||||
reader,
|
||||
tokio::io::sink(),
|
||||
"test stdio peer".to_string(),
|
||||
@@ -871,7 +904,7 @@ mod tests {
|
||||
async fn stdio_connection_rejects_overlong_unterminated_message() -> anyhow::Result<()> {
|
||||
let max_message_len: usize = 32;
|
||||
let (reader, mut peer) = tokio::io::duplex(max_message_len.saturating_add(1));
|
||||
let mut connection = JsonRpcConnection::from_stdio_with_max_message_len(
|
||||
let (mut connection, _) = JsonRpcConnection::from_stdio_with_max_message_len(
|
||||
reader,
|
||||
tokio::io::sink(),
|
||||
"hostile stdio peer".to_string(),
|
||||
|
||||
@@ -7,6 +7,7 @@ mod registry;
|
||||
mod release_version;
|
||||
mod request_dispatcher;
|
||||
mod session_registry;
|
||||
mod stdio_mux;
|
||||
mod transport;
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Serve each HTTP/2 CONNECT stream as an independent stdio connection.
|
||||
//! Half-closing the request detaches the session. After response EOF,
|
||||
//! the client can resume the session on a fresh stream.
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::future::ready;
|
||||
|
||||
use axum::body::Body;
|
||||
use hyper::Method;
|
||||
use hyper::Request;
|
||||
use hyper::Response;
|
||||
use hyper::StatusCode;
|
||||
use hyper::body::Incoming;
|
||||
use hyper::server::conn::http2::Builder;
|
||||
use hyper::service::service_fn;
|
||||
use hyper_util::rt::TokioExecutor;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
use super::ConnectionProcessor;
|
||||
use crate::connection::JsonRpcConnection;
|
||||
use crate::telemetry::ConnectionTransport;
|
||||
|
||||
pub(super) async fn run(
|
||||
reader: impl AsyncRead + Unpin + Send + 'static,
|
||||
writer: impl AsyncWrite + Unpin + Send + 'static,
|
||||
processor: &ConnectionProcessor,
|
||||
) -> Result<(), hyper::Error> {
|
||||
let tasks = TaskTracker::new();
|
||||
let physical_disconnect = CancellationToken::new();
|
||||
let service = service_fn(|mut request: Request<Incoming>| {
|
||||
let mut response = Response::new(Body::empty());
|
||||
if request.method() != Method::CONNECT || request.uri().host() != Some("rpc.local") {
|
||||
*response.status_mut() = StatusCode::BAD_REQUEST;
|
||||
return ready(Ok::<_, Infallible>(response));
|
||||
}
|
||||
let upgrade = hyper::upgrade::on(&mut request);
|
||||
let owner = processor.clone();
|
||||
let physical_disconnect = physical_disconnect.clone();
|
||||
tasks.spawn(async move {
|
||||
let Some(Ok(upgraded)) = physical_disconnect.run_until_cancelled(upgrade).await else {
|
||||
return;
|
||||
};
|
||||
let (reader, writer) = tokio::io::split(TokioIo::new(upgraded));
|
||||
let (connection, disconnected_tx) = JsonRpcConnection::from_stdio_with_disconnect(
|
||||
reader,
|
||||
writer,
|
||||
"stdio CONNECT".into(),
|
||||
);
|
||||
// On request EOF, run_connection detaches before it stops the stdio writer.
|
||||
let handler = owner.run_connection(connection, ConnectionTransport::Stdio);
|
||||
tokio::pin!(handler);
|
||||
tokio::select! {
|
||||
_ = &mut handler => {}
|
||||
_ = physical_disconnect.cancelled() => {
|
||||
// A full input queue can prevent the reader from observing EOF.
|
||||
let _ = disconnected_tx.send(true);
|
||||
handler.await;
|
||||
}
|
||||
}
|
||||
});
|
||||
ready(Ok(response))
|
||||
});
|
||||
let outcome = Builder::new(TokioExecutor::new())
|
||||
.serve_connection(TokioIo::new(tokio::io::join(reader, writer)), service)
|
||||
.await;
|
||||
physical_disconnect.cancel();
|
||||
tasks.close();
|
||||
tasks.wait().await;
|
||||
outcome
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "stdio_mux_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Exercises CONNECT tunnels and the native session registry over one duplex stream.
|
||||
#![cfg(test)]
|
||||
|
||||
use std::fmt::Write;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::connection::CHANNEL_CAPACITY;
|
||||
use crate::rpc::SESSION_ALREADY_ATTACHED_ERROR_CODE;
|
||||
use crate::server::transport::StdioMode;
|
||||
use crate::server::transport::run_stdio;
|
||||
use bytes::Bytes;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
struct Peer {
|
||||
client: h2::client::SendRequest<Bytes>,
|
||||
driver: AbortOnDropHandle<Result<(), h2::Error>>,
|
||||
worker: JoinHandle<Result<(), hyper::Error>>,
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
async fn start() -> Self {
|
||||
let runtime_paths = ExecServerRuntimeOptions::new(
|
||||
std::env::current_exe().unwrap(),
|
||||
/*codex_linux_sandbox_exe*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let processor = ConnectionProcessor::new(runtime_paths);
|
||||
let (server, peer) = tokio::io::duplex(/*max_buf_size*/ 8192);
|
||||
let (reader, writer) = tokio::io::split(server);
|
||||
let worker = tokio::spawn(run_stdio(reader, writer, StdioMode::Multiplexed, processor));
|
||||
let (client, driver) = h2::client::handshake(peer).await.unwrap();
|
||||
Self {
|
||||
client,
|
||||
worker,
|
||||
driver: AbortOnDropHandle::new(tokio::spawn(driver)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn open(&self) -> Tunnel {
|
||||
let request = Request::connect("rpc.local").body(()).unwrap();
|
||||
let (response, input) = self
|
||||
.client
|
||||
.clone()
|
||||
.ready()
|
||||
.await
|
||||
.unwrap()
|
||||
.send_request(request, /*end_of_stream*/ false)
|
||||
.unwrap();
|
||||
let response = response.await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
Tunnel {
|
||||
input,
|
||||
output: response.into_body(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn stop(self) {
|
||||
drop(self.driver);
|
||||
// Physical EOF (including abrupt disconnect) must release every handler.
|
||||
let _ = timeout(Duration::from_secs(5), self.worker)
|
||||
.await
|
||||
.expect("all handlers should finish promptly after physical EOF")
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
struct Tunnel {
|
||||
input: h2::SendStream<Bytes>,
|
||||
output: h2::RecvStream,
|
||||
}
|
||||
|
||||
impl Tunnel {
|
||||
fn send(&mut self, message: Value) {
|
||||
self.input
|
||||
.send_data(format!("{message}\n").into(), /*end_of_stream*/ false)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn response(&mut self) -> Value {
|
||||
let mut line = Vec::new();
|
||||
while !line.ends_with(b"\n") {
|
||||
let part = self.output.data().await.unwrap().unwrap();
|
||||
line.extend_from_slice(&part);
|
||||
self.output
|
||||
.flow_control()
|
||||
.release_capacity(part.len())
|
||||
.unwrap();
|
||||
}
|
||||
serde_json::from_slice(&line).unwrap()
|
||||
}
|
||||
|
||||
async fn initialize(&mut self, resume_id: Option<&str>) -> Value {
|
||||
self.send(json!({
|
||||
"id": 1, "method": "initialize",
|
||||
"params": {"clientName": "test", "resumeSessionId": resume_id},
|
||||
}));
|
||||
let response = self.response().await;
|
||||
if response.get("result").is_some() {
|
||||
self.send(json!({"method": "initialized"}));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
async fn session(&mut self) -> String {
|
||||
self.initialize(/*resume_id*/ None).await["result"]["sessionId"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
async fn detach(mut self) {
|
||||
self.input
|
||||
.send_data(Bytes::new(), /*end_of_stream*/ true)
|
||||
.unwrap();
|
||||
while let Some(part) = self.output.data().await {
|
||||
assert!(part.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn response_eof_allows_immediate_resume_among_concurrent_sessions_then_expiry() {
|
||||
let peer = Peer::start().await;
|
||||
peer.open().await.detach().await; // readiness probe
|
||||
let mut a = peer.open().await;
|
||||
let mut b = peer.open().await;
|
||||
let id = a.session().await;
|
||||
let attached = b.initialize(Some(&id)).await;
|
||||
assert_eq!(
|
||||
attached["error"]["code"],
|
||||
SESSION_ALREADY_ATTACHED_ERROR_CODE
|
||||
);
|
||||
assert_ne!(b.session().await, id);
|
||||
a.detach().await;
|
||||
let mut a = peer.open().await;
|
||||
let resumed = a.initialize(Some(&id)).await;
|
||||
assert_eq!(resumed["result"]["sessionId"], id);
|
||||
a.detach().await;
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
let mut a = peer.open().await;
|
||||
let expired = a.initialize(Some(&id)).await;
|
||||
assert_eq!(
|
||||
expired["error"]["message"],
|
||||
format!("unknown session id {id}")
|
||||
);
|
||||
assert_ne!(a.session().await, id);
|
||||
peer.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_allows_resume_and_keeps_an_initialized_sibling_usable() {
|
||||
let peer = Peer::start().await;
|
||||
let mut a = peer.open().await;
|
||||
let mut b = peer.open().await;
|
||||
let id = a.session().await;
|
||||
b.session().await;
|
||||
a.input.send_reset(h2::Reason::CANCEL);
|
||||
|
||||
let mut replacement = peer.open().await;
|
||||
// RST_STREAM has no detach acknowledgement. Retry while the old handler is attached.
|
||||
let resumed = timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let response = replacement.initialize(Some(&id)).await;
|
||||
if response["error"]["code"] != SESSION_ALREADY_ATTACHED_ERROR_CODE {
|
||||
break response;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("reset should release the session");
|
||||
assert_eq!(resumed["result"]["sessionId"], id);
|
||||
b.send(json!({"id": 2, "method": "environment/status"}));
|
||||
assert_eq!(
|
||||
b.response().await,
|
||||
json!({"id": 2, "result": {"status": "ready"}})
|
||||
);
|
||||
peer.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn physical_eof_interrupts_pending_read_with_full_input_queue() {
|
||||
let peer = Peer::start().await;
|
||||
let mut tunnel = peer.open().await;
|
||||
tunnel.session().await;
|
||||
let argv = if cfg!(windows) {
|
||||
vec!["cmd.exe", "/D", "/C", "set /p line="]
|
||||
} else {
|
||||
vec!["/bin/sh", "-c", "IFS= read -r line"]
|
||||
};
|
||||
tunnel.send(json!({
|
||||
"id": 2, "method": "process/start",
|
||||
"params": {
|
||||
"processId": "blocked", "argv": argv, "tty": false, "pipeStdin": true,
|
||||
"env": {"PATH": std::env::var("PATH").unwrap_or_default()},
|
||||
"cwd": PathUri::from_host_native_path(std::env::current_dir().unwrap()).unwrap(),
|
||||
},
|
||||
}));
|
||||
assert_eq!(tunnel.response().await["result"]["processId"], "blocked");
|
||||
|
||||
// The status reply acknowledges the DATA frame containing the long read and its backlog.
|
||||
let status = json!({"id": 3, "method": "environment/status"});
|
||||
let read = json!({
|
||||
"id": 4, "method": "process/read", "params": {"processId": "blocked", "waitMs": 60_000},
|
||||
});
|
||||
let mut batch = format!("{status}\n{read}\n");
|
||||
for offset in 0..=CHANNEL_CAPACITY {
|
||||
let request = json!({"id": 5 + offset, "method": "environment/status"});
|
||||
writeln!(batch, "{request}").unwrap();
|
||||
}
|
||||
tunnel
|
||||
.input
|
||||
.send_data(batch.into(), /*end_of_stream*/ false)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
tunnel.response().await,
|
||||
json!({"id": 3, "result": {"status": "ready"}})
|
||||
);
|
||||
peer.stop().await;
|
||||
}
|
||||
@@ -57,7 +57,13 @@ pub const DEFAULT_LISTEN_URL: &str = "ws://127.0.0.1:0";
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub(crate) enum ExecServerListenTransport {
|
||||
WebSocket(SocketAddr),
|
||||
Stdio,
|
||||
Stdio(StdioMode),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub(crate) enum StdioMode {
|
||||
Plain,
|
||||
Multiplexed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
@@ -71,7 +77,7 @@ impl std::fmt::Display for ExecServerListenUrlParseError {
|
||||
match self {
|
||||
ExecServerListenUrlParseError::UnsupportedListenUrl(listen_url) => write!(
|
||||
f,
|
||||
"unsupported --listen URL `{listen_url}`; expected `ws://IP:PORT` or `stdio`"
|
||||
"unsupported --listen URL `{listen_url}`; expected `ws://IP:PORT`, `stdio`, or `stdio-mux`"
|
||||
),
|
||||
ExecServerListenUrlParseError::InvalidWebSocketListenUrl(listen_url) => write!(
|
||||
f,
|
||||
@@ -86,8 +92,11 @@ impl std::error::Error for ExecServerListenUrlParseError {}
|
||||
pub(crate) fn parse_listen_url(
|
||||
listen_url: &str,
|
||||
) -> Result<ExecServerListenTransport, ExecServerListenUrlParseError> {
|
||||
if listen_url == "stdio-mux" {
|
||||
return Ok(ExecServerListenTransport::Stdio(StdioMode::Multiplexed));
|
||||
}
|
||||
if matches!(listen_url, "stdio" | "stdio://") {
|
||||
return Ok(ExecServerListenTransport::Stdio);
|
||||
return Ok(ExecServerListenTransport::Stdio(StdioMode::Plain));
|
||||
}
|
||||
|
||||
if let Some(socket_addr) = listen_url.strip_prefix("ws://") {
|
||||
@@ -124,7 +133,7 @@ pub(crate) async fn run_transport(
|
||||
)
|
||||
.await
|
||||
}
|
||||
ExecServerListenTransport::Stdio => {
|
||||
ExecServerListenTransport::Stdio(mode) => {
|
||||
if websocket_auth.config.is_some() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
@@ -132,62 +141,38 @@ pub(crate) async fn run_transport(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
run_stdio_connection(
|
||||
let processor = ConnectionProcessor::new_with_telemetry(
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
)
|
||||
.await
|
||||
);
|
||||
run_stdio(io::stdin(), io::stdout(), mode, processor).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_stdio_connection(
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
run_stdio_connection_with_io(
|
||||
io::stdin(),
|
||||
io::stdout(),
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_stdio_connection_with_io<R, W>(
|
||||
reader: R,
|
||||
writer: W,
|
||||
runtime_paths: ExecServerRuntimeOptions,
|
||||
telemetry: ExecServerTelemetry,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_dispatch_mode: RequestDispatchMode,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
|
||||
where
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let processor = ConnectionProcessor::new_with_telemetry(
|
||||
runtime_paths,
|
||||
telemetry,
|
||||
http_client_factory,
|
||||
request_dispatch_mode,
|
||||
);
|
||||
tracing::info!("codex-exec-server listening on stdio");
|
||||
processor
|
||||
.run_connection(
|
||||
JsonRpcConnection::from_stdio(reader, writer, "exec-server stdio".to_string()),
|
||||
ConnectionTransport::Stdio,
|
||||
)
|
||||
.await;
|
||||
// Stdio serves exactly one connection, so detached sessions cannot be resumed.
|
||||
pub(super) async fn run_stdio(
|
||||
reader: impl AsyncRead + Unpin + Send + 'static,
|
||||
writer: impl AsyncWrite + Unpin + Send + 'static,
|
||||
mode: StdioMode,
|
||||
processor: ConnectionProcessor,
|
||||
) -> Result<(), hyper::Error> {
|
||||
info!("codex-exec-server listening on stdio");
|
||||
let result = match mode {
|
||||
StdioMode::Plain => {
|
||||
let connection =
|
||||
JsonRpcConnection::from_stdio(reader, writer, "exec-server stdio".into());
|
||||
processor
|
||||
.run_connection(connection, ConnectionTransport::Stdio)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
StdioMode::Multiplexed => super::stdio_mux::run(reader, writer, &processor).await,
|
||||
};
|
||||
processor.shutdown().await;
|
||||
Ok(())
|
||||
result
|
||||
}
|
||||
|
||||
async fn run_websocket_listener(
|
||||
|
||||
@@ -15,14 +15,15 @@ use tokio::time::timeout;
|
||||
|
||||
use super::DEFAULT_LISTEN_URL;
|
||||
use super::ExecServerListenTransport;
|
||||
use super::StdioMode;
|
||||
use super::parse_listen_url;
|
||||
use super::run_stdio_connection_with_io;
|
||||
use super::run_stdio;
|
||||
use crate::ExecServerRuntimeOptions;
|
||||
use crate::protocol::INITIALIZE_METHOD;
|
||||
use crate::protocol::INITIALIZED_METHOD;
|
||||
use crate::protocol::InitializeParams;
|
||||
use crate::protocol::InitializeResponse;
|
||||
use crate::server::RequestDispatchMode;
|
||||
use crate::server::ConnectionProcessor;
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_default_websocket_url() {
|
||||
@@ -40,33 +41,35 @@ fn parse_listen_url_accepts_default_websocket_url() {
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_stdio() {
|
||||
let transport = parse_listen_url("stdio").expect("stdio listen URL should parse");
|
||||
assert_eq!(transport, ExecServerListenTransport::Stdio);
|
||||
assert_eq!(
|
||||
transport,
|
||||
ExecServerListenTransport::Stdio(StdioMode::Plain)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_stdio_url() {
|
||||
let transport = parse_listen_url("stdio://").expect("stdio listen URL should parse");
|
||||
assert_eq!(transport, ExecServerListenTransport::Stdio);
|
||||
assert_eq!(
|
||||
transport,
|
||||
ExecServerListenTransport::Stdio(StdioMode::Plain)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdio_listen_transport_serves_initialize() {
|
||||
let transport = parse_listen_url("stdio").expect("stdio listen URL should parse");
|
||||
let ExecServerListenTransport::Stdio = transport else {
|
||||
let ExecServerListenTransport::Stdio(mode) = transport else {
|
||||
panic!("expected stdio listen transport, got {transport:?}");
|
||||
};
|
||||
|
||||
let (mut client_writer, server_reader) = duplex(1 << 20);
|
||||
let (server_writer, client_reader) = duplex(1 << 20);
|
||||
let server_task = tokio::spawn(run_stdio_connection_with_io(
|
||||
let server_task = tokio::spawn(run_stdio(
|
||||
server_reader,
|
||||
server_writer,
|
||||
test_runtime_paths(),
|
||||
crate::ExecServerTelemetry::default(),
|
||||
codex_http_client::HttpClientFactory::new(
|
||||
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
RequestDispatchMode::Inline,
|
||||
mode,
|
||||
ConnectionProcessor::new(test_runtime_paths()),
|
||||
));
|
||||
let mut client_lines = BufReader::new(client_reader).lines();
|
||||
|
||||
@@ -147,7 +150,7 @@ fn parse_listen_url_rejects_unsupported_url() {
|
||||
parse_listen_url("http://127.0.0.1:1234").expect_err("unsupported scheme should fail");
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"unsupported --listen URL `http://127.0.0.1:1234`; expected `ws://IP:PORT` or `stdio`"
|
||||
"unsupported --listen URL `http://127.0.0.1:1234`; expected `ws://IP:PORT`, `stdio`, or `stdio-mux`"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user