mirror of
https://github.com/openai/codex.git
synced 2026-12-06 01:10:58 +00:00
telemetry(exec-server): trace RPC transport
This commit is contained in:
@@ -10,6 +10,7 @@ use std::time::Duration;
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use codex_exec_server_protocol::JSONRPCNotification;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
use serde_json::Value;
|
||||
@@ -162,6 +163,7 @@ pub(crate) struct SessionState {
|
||||
ordered_events: StdMutex<OrderedSessionEvents>,
|
||||
recoverable: AtomicBool,
|
||||
next_write_id: AtomicU64,
|
||||
trace_context: Option<W3cTraceContext>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -846,6 +848,7 @@ impl SessionState {
|
||||
ordered_events: StdMutex::new(OrderedSessionEvents::default()),
|
||||
recoverable: AtomicBool::new(recoverable),
|
||||
next_write_id: AtomicU64::new(1),
|
||||
trace_context: codex_otel::current_span_w3c_trace_context(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1157,6 +1160,7 @@ async fn handle_server_notification(
|
||||
chunk: params.chunk,
|
||||
}));
|
||||
if published_closed {
|
||||
record_closed_published(&session, ¶ms.process_id);
|
||||
inner.remove_session_if(¶ms.process_id, &session);
|
||||
}
|
||||
}
|
||||
@@ -1172,6 +1176,7 @@ async fn handle_server_notification(
|
||||
sandbox_denied: params.sandbox_denied,
|
||||
});
|
||||
if published_closed {
|
||||
record_closed_published(&session, ¶ms.process_id);
|
||||
inner.remove_session_if(¶ms.process_id, &session);
|
||||
}
|
||||
}
|
||||
@@ -1180,6 +1185,18 @@ async fn handle_server_notification(
|
||||
let params: ExecClosedNotification =
|
||||
serde_json::from_value(notification.params.unwrap_or(Value::Null))?;
|
||||
if let Some(session) = inner.get_session(¶ms.process_id) {
|
||||
let received_span = tracing::info_span!(
|
||||
"exec_server.client.closed_notification_received",
|
||||
process_id = %params.process_id,
|
||||
seq = params.seq,
|
||||
);
|
||||
if let Some(trace_context) = session.trace_context.as_ref() {
|
||||
let _ = codex_otel::set_parent_from_w3c_trace_context(
|
||||
&received_span,
|
||||
trace_context,
|
||||
);
|
||||
}
|
||||
received_span.in_scope(|| {});
|
||||
session.note_change(params.seq);
|
||||
// Closed is terminal, but it can arrive before tail output or
|
||||
// exited. Keep routing this process until the ordered publisher
|
||||
@@ -1187,6 +1204,7 @@ async fn handle_server_notification(
|
||||
let published_closed =
|
||||
session.publish_ordered_event(ExecProcessEvent::Closed { seq: params.seq });
|
||||
if published_closed {
|
||||
record_closed_published(&session, ¶ms.process_id);
|
||||
inner.remove_session_if(¶ms.process_id, &session);
|
||||
}
|
||||
}
|
||||
@@ -1203,6 +1221,17 @@ async fn handle_server_notification(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn record_closed_published(session: &SessionState, process_id: &ProcessId) {
|
||||
let published_span = tracing::info_span!(
|
||||
"exec_server.client.closed_notification_published",
|
||||
process_id = %process_id,
|
||||
);
|
||||
if let Some(trace_context) = session.trace_context.as_ref() {
|
||||
let _ = codex_otel::set_parent_from_w3c_trace_context(&published_span, trace_context);
|
||||
}
|
||||
published_span.in_scope(|| {});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_exec_server_protocol::JSONRPCMessage;
|
||||
|
||||
@@ -9,6 +9,7 @@ use tokio::sync::mpsc;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::sleep;
|
||||
use tokio::time::timeout_at;
|
||||
use tracing::Instrument;
|
||||
|
||||
use super::ConnectionStatus;
|
||||
use super::ExecServerClient;
|
||||
@@ -502,8 +503,43 @@ impl ExecServerClient {
|
||||
return;
|
||||
};
|
||||
match event {
|
||||
RpcClientEvent::Notification(notification) => {
|
||||
if let Err(error) = handle_server_notification(&inner, notification).await {
|
||||
RpcClientEvent::Notification {
|
||||
notification,
|
||||
queued_at,
|
||||
trace,
|
||||
} => {
|
||||
let process_id = notification
|
||||
.params
|
||||
.as_ref()
|
||||
.and_then(|params| params.get("processId"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("");
|
||||
let seq = notification
|
||||
.params
|
||||
.as_ref()
|
||||
.and_then(|params| params.get("seq"))
|
||||
.and_then(serde_json::Value::as_u64);
|
||||
let span = tracing::info_span!(
|
||||
"exec_server.client.notification_event_dequeued",
|
||||
method = notification.method,
|
||||
process_id,
|
||||
seq,
|
||||
queue_wait_ms = queued_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
if let Some(trace) = trace.as_ref() {
|
||||
let _ = codex_otel::set_parent_from_w3c_trace_context(&span, trace);
|
||||
} else if !process_id.is_empty()
|
||||
&& let Some(session) =
|
||||
inner.get_session(&crate::ProcessId::from(process_id))
|
||||
&& let Some(session_trace) = session.trace_context.as_ref()
|
||||
{
|
||||
let _ =
|
||||
codex_otel::set_parent_from_w3c_trace_context(&span, session_trace);
|
||||
}
|
||||
if let Err(error) = handle_server_notification(&inner, notification)
|
||||
.instrument(span)
|
||||
.await
|
||||
{
|
||||
rpc_client.close_transport().await;
|
||||
inner.request_recovery(
|
||||
rpc_client,
|
||||
|
||||
@@ -4,10 +4,12 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::extract::ws::Message as AxumWebSocketMessage;
|
||||
use axum::extract::ws::WebSocket as AxumWebSocket;
|
||||
use codex_exec_server_protocol::JSONRPCMessage;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use futures::Sink;
|
||||
use futures::SinkExt;
|
||||
use futures::Stream;
|
||||
@@ -38,8 +40,19 @@ pub(crate) const WEBSOCKET_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum JsonRpcConnectionEvent {
|
||||
Message(JSONRPCMessage),
|
||||
MalformedMessage { reason: String },
|
||||
Disconnected { reason: Option<String> },
|
||||
// Constructed by the stacked Noise transport change.
|
||||
#[allow(dead_code)]
|
||||
TracedMessage {
|
||||
message: JSONRPCMessage,
|
||||
trace: Option<W3cTraceContext>,
|
||||
queued_at: Instant,
|
||||
},
|
||||
MalformedMessage {
|
||||
reason: String,
|
||||
},
|
||||
Disconnected {
|
||||
reason: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -55,7 +55,7 @@ use crate::protocol::WriteParams;
|
||||
use crate::protocol::WriteResponse;
|
||||
use crate::protocol::WriteStatus;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::rpc::RpcServerOutboundMessage;
|
||||
use crate::rpc::RpcServerOutboundEnvelope;
|
||||
use crate::rpc::internal_error;
|
||||
use crate::rpc::invalid_params;
|
||||
use crate::rpc::invalid_request;
|
||||
@@ -169,7 +169,7 @@ impl LocalProcess {
|
||||
|
||||
fn with_discarded_notifications(runtime_paths: Option<ExecServerRuntimePaths>) -> Self {
|
||||
let (outgoing_tx, mut outgoing_rx) =
|
||||
mpsc::channel::<RpcServerOutboundMessage>(NOTIFICATION_CHANNEL_CAPACITY);
|
||||
mpsc::channel::<RpcServerOutboundEnvelope>(NOTIFICATION_CHANNEL_CAPACITY);
|
||||
tokio::spawn(async move { while outgoing_rx.recv().await.is_some() {} });
|
||||
Self::with_runtime_paths(
|
||||
RpcNotificationSender::new(outgoing_tx),
|
||||
|
||||
+305
-41
@@ -6,6 +6,7 @@ use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_exec_server_protocol::JSONRPCError;
|
||||
use codex_exec_server_protocol::JSONRPCErrorError;
|
||||
@@ -14,6 +15,7 @@ use codex_exec_server_protocol::JSONRPCNotification;
|
||||
use codex_exec_server_protocol::JSONRPCRequest;
|
||||
use codex_exec_server_protocol::JSONRPCResponse;
|
||||
use codex_exec_server_protocol::RequestId;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
@@ -23,6 +25,9 @@ use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
use tracing::Instrument;
|
||||
use tracing::Span;
|
||||
use tracing::field;
|
||||
|
||||
use crate::connection::JsonRpcConnection;
|
||||
use crate::connection::JsonRpcConnectionEvent;
|
||||
@@ -42,7 +47,11 @@ pub(crate) enum RpcCallError {
|
||||
TimedOut { method: String, timeout: Duration },
|
||||
}
|
||||
|
||||
type PendingRequest = oneshot::Sender<Result<Value, RpcCallError>>;
|
||||
struct PendingRequest {
|
||||
response_tx: oneshot::Sender<Result<Value, RpcCallError>>,
|
||||
method: String,
|
||||
trace: Option<W3cTraceContext>,
|
||||
}
|
||||
type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
|
||||
type RequestRoute<S> = Box<
|
||||
dyn Fn(Arc<S>, JSONRPCRequest) -> BoxFuture<Option<RpcServerOutboundMessage>> + Send + Sync,
|
||||
@@ -55,10 +64,29 @@ enum RpcCallTimeout {
|
||||
After(Duration),
|
||||
}
|
||||
|
||||
fn rpc_call_span(method: &str) -> Span {
|
||||
tracing::info_span!(
|
||||
"exec_server.rpc.call",
|
||||
method,
|
||||
request_id = field::Empty,
|
||||
pending_registered_ms = field::Empty,
|
||||
request_serialized_ms = field::Empty,
|
||||
request_enqueued_ms = field::Empty,
|
||||
response_received_ms = field::Empty,
|
||||
response_decoded_ms = field::Empty,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RpcClientEvent {
|
||||
Notification(JSONRPCNotification),
|
||||
Disconnected { reason: Option<String> },
|
||||
Notification {
|
||||
notification: JSONRPCNotification,
|
||||
queued_at: Instant,
|
||||
trace: Option<W3cTraceContext>,
|
||||
},
|
||||
Disconnected {
|
||||
reason: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -74,13 +102,40 @@ pub(crate) enum RpcServerOutboundMessage {
|
||||
Notification(JSONRPCNotification),
|
||||
}
|
||||
|
||||
/// Carries executor-local timing and trace state across the server outbound queue.
|
||||
///
|
||||
/// The metadata is deliberately not serialized onto the JSON-RPC wire. Noise
|
||||
/// transport correlation uses the originating request ID or process ID instead.
|
||||
pub(crate) struct RpcServerOutboundEnvelope {
|
||||
pub(crate) message: RpcServerOutboundMessage,
|
||||
pub(crate) queued_at: Instant,
|
||||
pub(crate) trace: Option<W3cTraceContext>,
|
||||
}
|
||||
|
||||
impl RpcServerOutboundEnvelope {
|
||||
pub(crate) fn from_current_span(message: RpcServerOutboundMessage) -> Self {
|
||||
Self::with_trace(message, codex_otel::current_span_w3c_trace_context())
|
||||
}
|
||||
|
||||
pub(crate) fn with_trace(
|
||||
message: RpcServerOutboundMessage,
|
||||
trace: Option<W3cTraceContext>,
|
||||
) -> Self {
|
||||
Self {
|
||||
message,
|
||||
queued_at: Instant::now(),
|
||||
trace,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RpcNotificationSender {
|
||||
outgoing_tx: mpsc::Sender<RpcServerOutboundMessage>,
|
||||
outgoing_tx: mpsc::Sender<RpcServerOutboundEnvelope>,
|
||||
}
|
||||
|
||||
impl RpcNotificationSender {
|
||||
pub(crate) fn new(outgoing_tx: mpsc::Sender<RpcServerOutboundMessage>) -> Self {
|
||||
pub(crate) fn new(outgoing_tx: mpsc::Sender<RpcServerOutboundEnvelope>) -> Self {
|
||||
Self { outgoing_tx }
|
||||
}
|
||||
|
||||
@@ -89,10 +144,19 @@ impl RpcNotificationSender {
|
||||
request_id: RequestId,
|
||||
result: Value,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
self.outgoing_tx
|
||||
.send(RpcServerOutboundMessage::Response { request_id, result })
|
||||
let permit = self
|
||||
.outgoing_tx
|
||||
.reserve()
|
||||
.instrument(tracing::info_span!(
|
||||
"exec_server.rpc_server.outbound_queue_enqueue",
|
||||
message_kind = "response",
|
||||
))
|
||||
.await
|
||||
.map_err(|_| internal_error("RPC connection closed while sending response".into()))
|
||||
.map_err(|_| internal_error("RPC connection closed while sending response".into()))?;
|
||||
permit.send(RpcServerOutboundEnvelope::from_current_span(
|
||||
RpcServerOutboundMessage::Response { request_id, result },
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn notify<P: Serialize>(
|
||||
@@ -100,16 +164,28 @@ impl RpcNotificationSender {
|
||||
method: &str,
|
||||
params: &P,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let params = serde_json::to_value(params).map_err(|err| internal_error(err.to_string()))?;
|
||||
self.outgoing_tx
|
||||
.send(RpcServerOutboundMessage::Notification(
|
||||
JSONRPCNotification {
|
||||
method: method.to_string(),
|
||||
params: Some(params),
|
||||
},
|
||||
let params = tracing::info_span!("exec_server.rpc_server.notification_serialize", method,)
|
||||
.in_scope(|| serde_json::to_value(params))
|
||||
.map_err(|err| internal_error(err.to_string()))?;
|
||||
let permit = self
|
||||
.outgoing_tx
|
||||
.reserve()
|
||||
.instrument(tracing::info_span!(
|
||||
"exec_server.rpc_server.outbound_queue_enqueue",
|
||||
message_kind = "notification",
|
||||
method,
|
||||
))
|
||||
.await
|
||||
.map_err(|_| internal_error("RPC connection closed while sending notification".into()))
|
||||
.map_err(|_| {
|
||||
internal_error("RPC connection closed while sending notification".into())
|
||||
})?;
|
||||
permit.send(RpcServerOutboundEnvelope::from_current_span(
|
||||
RpcServerOutboundMessage::Notification(JSONRPCNotification {
|
||||
method: method.to_string(),
|
||||
params: Some(params),
|
||||
}),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,8 +345,30 @@ impl RpcClient {
|
||||
};
|
||||
match event {
|
||||
JsonRpcConnectionEvent::Message(message) => {
|
||||
let reader_span = rpc_reader_message_span(&message, None, None);
|
||||
if let Err(err) =
|
||||
handle_server_message(&pending_for_reader, &event_tx, message).await
|
||||
handle_server_message(&pending_for_reader, &event_tx, message, None)
|
||||
.instrument(reader_span)
|
||||
.await
|
||||
{
|
||||
let _ = err;
|
||||
break None;
|
||||
}
|
||||
}
|
||||
JsonRpcConnectionEvent::TracedMessage {
|
||||
message,
|
||||
trace,
|
||||
queued_at,
|
||||
} => {
|
||||
let reader_span = rpc_reader_message_span(
|
||||
&message,
|
||||
trace.as_ref(),
|
||||
Some(queued_at.elapsed()),
|
||||
);
|
||||
if let Err(err) =
|
||||
handle_server_message(&pending_for_reader, &event_tx, message, trace)
|
||||
.instrument(reader_span)
|
||||
.await
|
||||
{
|
||||
let _ = err;
|
||||
break None;
|
||||
@@ -357,7 +455,9 @@ impl RpcClient {
|
||||
P: Serialize,
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
self.call_inner(method, params, RpcCallTimeout::None).await
|
||||
self.call_inner(method, params, RpcCallTimeout::None)
|
||||
.instrument(rpc_call_span(method))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn call_with_timeout<P, T>(
|
||||
@@ -371,6 +471,7 @@ impl RpcClient {
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
self.call_inner(method, params, RpcCallTimeout::After(call_timeout))
|
||||
.instrument(rpc_call_span(method))
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -384,40 +485,71 @@ impl RpcClient {
|
||||
P: Serialize,
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
let request_id = RequestId::Integer(self.next_request_id.fetch_add(1, Ordering::SeqCst));
|
||||
let call_started_at = Instant::now();
|
||||
let request_number = self.next_request_id.fetch_add(1, Ordering::SeqCst);
|
||||
Span::current().record("request_id", request_number);
|
||||
let request_id = RequestId::Integer(request_number);
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
let trace = codex_otel::current_span_w3c_trace_context();
|
||||
{
|
||||
let mut pending = self.pending.lock().await;
|
||||
let mut pending = self
|
||||
.pending
|
||||
.lock()
|
||||
.instrument(tracing::info_span!("exec_server.rpc.pending_registration"))
|
||||
.await;
|
||||
// Registering the pending request and checking disconnect must be
|
||||
// atomic with the reader's drain_pending path. Otherwise a call
|
||||
// can sneak in after the drain and wait forever.
|
||||
if self.closed.load(Ordering::Acquire) || *self.disconnected_rx.borrow() {
|
||||
return Err(RpcCallError::Closed);
|
||||
}
|
||||
pending.insert(request_id.clone(), response_tx);
|
||||
pending.insert(
|
||||
request_id.clone(),
|
||||
PendingRequest {
|
||||
response_tx,
|
||||
method: method.to_string(),
|
||||
trace: trace.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
Span::current().record(
|
||||
"pending_registered_ms",
|
||||
call_started_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
|
||||
let params = match serde_json::to_value(params) {
|
||||
let params = match tracing::info_span!("exec_server.rpc.serialize_params")
|
||||
.in_scope(|| serde_json::to_value(params))
|
||||
{
|
||||
Ok(params) => params,
|
||||
Err(err) => {
|
||||
self.pending.lock().await.remove(&request_id);
|
||||
return Err(RpcCallError::Json(err));
|
||||
}
|
||||
};
|
||||
Span::current().record(
|
||||
"request_serialized_ms",
|
||||
call_started_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
let message = JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: request_id.clone(),
|
||||
method: method.to_string(),
|
||||
params: Some(params),
|
||||
trace,
|
||||
});
|
||||
if self
|
||||
.write_tx
|
||||
.send(JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: request_id.clone(),
|
||||
method: method.to_string(),
|
||||
params: Some(params),
|
||||
trace: codex_otel::current_span_w3c_trace_context(),
|
||||
}))
|
||||
.send(message)
|
||||
.instrument(tracing::info_span!("exec_server.rpc.enqueue_request"))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
self.pending.lock().await.remove(&request_id);
|
||||
return Err(RpcCallError::Closed);
|
||||
}
|
||||
Span::current().record(
|
||||
"request_enqueued_ms",
|
||||
call_started_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
|
||||
// Do not race in-flight requests directly against the transport-close
|
||||
// watch value. The connection reader receives JSON-RPC messages and
|
||||
@@ -425,9 +557,12 @@ impl RpcClient {
|
||||
// still-pending requests. Awaiting this receiver preserves that order:
|
||||
// responses already read before EOF still win, and truly pending calls
|
||||
// are failed once the reader observes the disconnect.
|
||||
let response_wait =
|
||||
response_rx.instrument(tracing::info_span!("exec_server.rpc.await_response"));
|
||||
let response = match call_timeout {
|
||||
RpcCallTimeout::None => response_rx.await,
|
||||
RpcCallTimeout::After(call_timeout) => match timeout(call_timeout, response_rx).await {
|
||||
RpcCallTimeout::None => response_wait.await,
|
||||
RpcCallTimeout::After(call_timeout) => match timeout(call_timeout, response_wait).await
|
||||
{
|
||||
Ok(response) => response,
|
||||
Err(_) => {
|
||||
self.pending.lock().await.remove(&request_id);
|
||||
@@ -438,12 +573,23 @@ impl RpcClient {
|
||||
}
|
||||
},
|
||||
};
|
||||
Span::current().record(
|
||||
"response_received_ms",
|
||||
call_started_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
let result: Result<Value, RpcCallError> = response.map_err(|_| RpcCallError::Closed)?;
|
||||
let response = match result {
|
||||
Ok(response) => response,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
serde_json::from_value(response).map_err(RpcCallError::Json)
|
||||
let decoded = tracing::info_span!("exec_server.rpc.deserialize_response")
|
||||
.in_scope(|| serde_json::from_value(response))
|
||||
.map_err(RpcCallError::Json);
|
||||
Span::current().record(
|
||||
"response_decoded_ms",
|
||||
call_started_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
decoded
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -567,22 +713,31 @@ async fn handle_server_message(
|
||||
pending: &Mutex<HashMap<RequestId, PendingRequest>>,
|
||||
event_tx: &mpsc::Sender<RpcClientEvent>,
|
||||
message: JSONRPCMessage,
|
||||
trace: Option<W3cTraceContext>,
|
||||
) -> Result<(), String> {
|
||||
match message {
|
||||
JSONRPCMessage::Response(JSONRPCResponse { id, result }) => {
|
||||
if let Some(pending) = pending.lock().await.remove(&id) {
|
||||
let _ = pending.send(Ok(result));
|
||||
}
|
||||
dispatch_response(pending, id, Ok(result), "response", trace).await;
|
||||
}
|
||||
JSONRPCMessage::Error(JSONRPCError { id, error }) => {
|
||||
if let Some(pending) = pending.lock().await.remove(&id) {
|
||||
let _ = pending.send(Err(RpcCallError::Server(error)));
|
||||
}
|
||||
dispatch_response(
|
||||
pending,
|
||||
id,
|
||||
Err(RpcCallError::Server(error)),
|
||||
"error",
|
||||
trace,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
JSONRPCMessage::Notification(notification) => {
|
||||
let _ = event_tx
|
||||
.send(RpcClientEvent::Notification(notification))
|
||||
.await;
|
||||
let span = notification_dispatch_span(¬ification);
|
||||
if let Ok(permit) = event_tx.reserve().instrument(span).await {
|
||||
permit.send(RpcClientEvent::Notification {
|
||||
notification,
|
||||
queued_at: Instant::now(),
|
||||
trace,
|
||||
});
|
||||
}
|
||||
}
|
||||
JSONRPCMessage::Request(request) => {
|
||||
return Err(format!(
|
||||
@@ -595,6 +750,115 @@ async fn handle_server_message(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn dispatch_response(
|
||||
pending: &Mutex<HashMap<RequestId, PendingRequest>>,
|
||||
id: RequestId,
|
||||
result: Result<Value, RpcCallError>,
|
||||
message_kind: &'static str,
|
||||
received_trace: Option<W3cTraceContext>,
|
||||
) {
|
||||
let lookup_started_at = Instant::now();
|
||||
let pending = pending
|
||||
.lock()
|
||||
.instrument(tracing::info_span!(
|
||||
"exec_server.rpc.response_pending_lookup",
|
||||
request_id = %id,
|
||||
))
|
||||
.await
|
||||
.remove(&id);
|
||||
let Some(pending) = pending else {
|
||||
return;
|
||||
};
|
||||
let span = tracing::info_span!(
|
||||
"exec_server.rpc.response_dispatch",
|
||||
message_kind,
|
||||
method = pending.method,
|
||||
request_id = %id,
|
||||
pending_lookup_ms = lookup_started_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
if let Some(trace) = received_trace.as_ref().or(pending.trace.as_ref()) {
|
||||
let _ = codex_otel::set_parent_from_w3c_trace_context(&span, trace);
|
||||
}
|
||||
span.in_scope(|| {
|
||||
let _ = pending.response_tx.send(result);
|
||||
});
|
||||
}
|
||||
|
||||
fn rpc_reader_message_span(
|
||||
message: &JSONRPCMessage,
|
||||
trace: Option<&W3cTraceContext>,
|
||||
queue_wait: Option<std::time::Duration>,
|
||||
) -> Span {
|
||||
let (message_kind, method, request_id, process_id, seq) = message_trace_fields(message);
|
||||
let span = tracing::info_span!(
|
||||
"exec_server.rpc.reader_message_dequeued",
|
||||
message_kind,
|
||||
method,
|
||||
request_id,
|
||||
process_id,
|
||||
seq,
|
||||
queue_wait_ms = queue_wait.map(|wait| wait.as_secs_f64() * 1_000.0),
|
||||
);
|
||||
if let Some(trace) = trace {
|
||||
let _ = codex_otel::set_parent_from_w3c_trace_context(&span, trace);
|
||||
}
|
||||
span
|
||||
}
|
||||
|
||||
fn notification_dispatch_span(notification: &JSONRPCNotification) -> Span {
|
||||
let process_id = notification
|
||||
.params
|
||||
.as_ref()
|
||||
.and_then(|params| params.get("processId"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
let seq = notification
|
||||
.params
|
||||
.as_ref()
|
||||
.and_then(|params| params.get("seq"))
|
||||
.and_then(Value::as_u64);
|
||||
tracing::info_span!(
|
||||
"exec_server.rpc.notification_event_enqueue",
|
||||
method = notification.method,
|
||||
process_id,
|
||||
seq,
|
||||
)
|
||||
}
|
||||
|
||||
fn message_trace_fields(message: &JSONRPCMessage) -> (&str, &str, String, &str, Option<u64>) {
|
||||
let (message_kind, method, request_id, payload) = match message {
|
||||
JSONRPCMessage::Request(request) => (
|
||||
"request",
|
||||
request.method.as_str(),
|
||||
request.id.to_string(),
|
||||
request.params.as_ref(),
|
||||
),
|
||||
JSONRPCMessage::Notification(notification) => (
|
||||
"notification",
|
||||
notification.method.as_str(),
|
||||
String::new(),
|
||||
notification.params.as_ref(),
|
||||
),
|
||||
JSONRPCMessage::Response(response) => (
|
||||
"response",
|
||||
"",
|
||||
response.id.to_string(),
|
||||
Some(&response.result),
|
||||
),
|
||||
JSONRPCMessage::Error(error) => {
|
||||
("error", "", error.id.to_string(), error.error.data.as_ref())
|
||||
}
|
||||
};
|
||||
let process_id = payload
|
||||
.and_then(|payload| payload.get("processId"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
let seq = payload
|
||||
.and_then(|payload| payload.get("seq"))
|
||||
.and_then(Value::as_u64);
|
||||
(message_kind, method, request_id, process_id, seq)
|
||||
}
|
||||
|
||||
async fn drain_pending(pending: &Mutex<HashMap<RequestId, PendingRequest>>) {
|
||||
let pending = {
|
||||
let mut pending = pending.lock().await;
|
||||
@@ -604,7 +868,7 @@ async fn drain_pending(pending: &Mutex<HashMap<RequestId, PendingRequest>>) {
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for pending in pending {
|
||||
let _ = pending.send(Err(RpcCallError::Closed));
|
||||
let _ = pending.response_tx.send(Err(RpcCallError::Closed));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::connection::CHANNEL_CAPACITY;
|
||||
use crate::connection::JsonRpcConnection;
|
||||
use crate::connection::JsonRpcConnectionEvent;
|
||||
use crate::rpc::RpcNotificationSender;
|
||||
use crate::rpc::RpcServerOutboundEnvelope;
|
||||
use crate::rpc::RpcServerOutboundMessage;
|
||||
use crate::rpc::encode_server_message;
|
||||
use crate::rpc::invalid_request;
|
||||
@@ -82,7 +83,7 @@ async fn run_connection(
|
||||
transport: _transport,
|
||||
} = connection;
|
||||
let (outgoing_tx, mut outgoing_rx) =
|
||||
mpsc::channel::<RpcServerOutboundMessage>(CHANNEL_CAPACITY);
|
||||
mpsc::channel::<RpcServerOutboundEnvelope>(CHANNEL_CAPACITY);
|
||||
let notifications = RpcNotificationSender::new(outgoing_tx.clone());
|
||||
let handler = Arc::new(ExecServerHandler::new(
|
||||
session_registry,
|
||||
@@ -91,15 +92,26 @@ async fn run_connection(
|
||||
));
|
||||
|
||||
let outbound_task = tokio::spawn(async move {
|
||||
while let Some(message) = outgoing_rx.recv().await {
|
||||
let json_message = match encode_server_message(message) {
|
||||
while let Some(envelope) = outgoing_rx.recv().await {
|
||||
let outbound_span = server_outbound_span(&envelope);
|
||||
let json_message = match outbound_span.in_scope(|| {
|
||||
tracing::info_span!("exec_server.rpc_server.build_jsonrpc_envelope")
|
||||
.in_scope(|| encode_server_message(envelope.message))
|
||||
}) {
|
||||
Ok(json_message) => json_message,
|
||||
Err(err) => {
|
||||
warn!("failed to serialize exec-server outbound message: {err}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
if json_outgoing_tx.send(json_message).await.is_err() {
|
||||
let transport_enqueue_span = outbound_span
|
||||
.in_scope(|| tracing::info_span!("exec_server.rpc_server.transport_queue_enqueue"));
|
||||
if json_outgoing_tx
|
||||
.send(json_message)
|
||||
.instrument(transport_enqueue_span)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -114,19 +126,27 @@ async fn run_connection(
|
||||
match event {
|
||||
JsonRpcConnectionEvent::MalformedMessage { reason } => {
|
||||
warn!("ignoring malformed exec-server message: {reason}");
|
||||
if outgoing_tx
|
||||
.send(RpcServerOutboundMessage::Error {
|
||||
let permit = outgoing_tx
|
||||
.reserve()
|
||||
.instrument(tracing::info_span!(
|
||||
"exec_server.rpc_server.outbound_queue_enqueue",
|
||||
message_kind = "error",
|
||||
))
|
||||
.await;
|
||||
let Ok(permit) = permit else {
|
||||
break;
|
||||
};
|
||||
permit.send(RpcServerOutboundEnvelope::from_current_span(
|
||||
RpcServerOutboundMessage::Error {
|
||||
request_id: codex_exec_server_protocol::RequestId::Integer(-1),
|
||||
error: invalid_request(reason),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
},
|
||||
));
|
||||
}
|
||||
JsonRpcConnectionEvent::Message(message) => match message {
|
||||
JsonRpcConnectionEvent::Message(message)
|
||||
| JsonRpcConnectionEvent::TracedMessage { message, .. } => match message {
|
||||
codex_exec_server_protocol::JSONRPCMessage::Request(request) => {
|
||||
record_request_dequeued(&request);
|
||||
let request_started_at = Instant::now();
|
||||
if let Some((method, route)) = router.request_route(request.method.as_str()) {
|
||||
let request_span = request_span(method, &request);
|
||||
@@ -144,16 +164,29 @@ async fn run_connection(
|
||||
}
|
||||
};
|
||||
let result = request_result(&message);
|
||||
if let Some(message) = message
|
||||
&& outgoing_tx.send(message).await.is_err()
|
||||
{
|
||||
request_span.record("result", "disconnected");
|
||||
telemetry.request_completed(
|
||||
method,
|
||||
"disconnected",
|
||||
request_started_at.elapsed(),
|
||||
);
|
||||
break;
|
||||
let request_trace = codex_otel::span_w3c_trace_context(&request_span);
|
||||
if let Some(message) = message {
|
||||
let enqueue_span = request_span.in_scope(|| {
|
||||
tracing::info_span!(
|
||||
"exec_server.rpc_server.outbound_queue_enqueue",
|
||||
message_kind = "response",
|
||||
method,
|
||||
)
|
||||
});
|
||||
let permit = outgoing_tx.reserve().instrument(enqueue_span).await;
|
||||
let Ok(permit) = permit else {
|
||||
request_span.record("result", "disconnected");
|
||||
telemetry.request_completed(
|
||||
method,
|
||||
"disconnected",
|
||||
request_started_at.elapsed(),
|
||||
);
|
||||
break;
|
||||
};
|
||||
permit.send(RpcServerOutboundEnvelope::with_trace(
|
||||
message,
|
||||
request_trace,
|
||||
));
|
||||
}
|
||||
request_span.record("result", result);
|
||||
telemetry.request_completed(method, result, request_started_at.elapsed());
|
||||
@@ -161,17 +194,18 @@ async fn run_connection(
|
||||
} else {
|
||||
let method = "unknown";
|
||||
let request_span = request_span(method, &request);
|
||||
if outgoing_tx
|
||||
.send(RpcServerOutboundMessage::Error {
|
||||
request_id: request.id,
|
||||
error: method_not_found(format!(
|
||||
"exec-server stub does not implement `{}` yet",
|
||||
request.method
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
let request_trace = codex_otel::span_w3c_trace_context(&request_span);
|
||||
let permit = outgoing_tx
|
||||
.reserve()
|
||||
.instrument(request_span.in_scope(|| {
|
||||
tracing::info_span!(
|
||||
"exec_server.rpc_server.outbound_queue_enqueue",
|
||||
message_kind = "error",
|
||||
method,
|
||||
)
|
||||
}))
|
||||
.await;
|
||||
let Ok(permit) = permit else {
|
||||
request_span.record("result", "disconnected");
|
||||
telemetry.request_completed(
|
||||
method,
|
||||
@@ -179,7 +213,17 @@ async fn run_connection(
|
||||
request_started_at.elapsed(),
|
||||
);
|
||||
break;
|
||||
}
|
||||
};
|
||||
permit.send(RpcServerOutboundEnvelope::with_trace(
|
||||
RpcServerOutboundMessage::Error {
|
||||
request_id: request.id,
|
||||
error: method_not_found(format!(
|
||||
"exec-server stub does not implement `{}` yet",
|
||||
request.method
|
||||
)),
|
||||
},
|
||||
request_trace,
|
||||
));
|
||||
request_span.record("result", "error");
|
||||
telemetry.request_completed(method, "error", request_started_at.elapsed());
|
||||
}
|
||||
@@ -241,6 +285,61 @@ async fn run_connection(
|
||||
let _ = outbound_task.await;
|
||||
}
|
||||
|
||||
fn server_outbound_span(envelope: &RpcServerOutboundEnvelope) -> tracing::Span {
|
||||
let (message_kind, method, request_id, process_id, seq) = match &envelope.message {
|
||||
RpcServerOutboundMessage::Response { request_id, .. } => {
|
||||
("response", "", request_id.to_string(), "", None)
|
||||
}
|
||||
RpcServerOutboundMessage::Error { request_id, .. } => {
|
||||
("error", "", request_id.to_string(), "", None)
|
||||
}
|
||||
RpcServerOutboundMessage::Notification(notification) => {
|
||||
let process_id = notification
|
||||
.params
|
||||
.as_ref()
|
||||
.and_then(|params| params.get("processId"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("");
|
||||
let seq = notification
|
||||
.params
|
||||
.as_ref()
|
||||
.and_then(|params| params.get("seq"))
|
||||
.and_then(serde_json::Value::as_u64);
|
||||
(
|
||||
"notification",
|
||||
notification.method.as_str(),
|
||||
String::new(),
|
||||
process_id,
|
||||
seq,
|
||||
)
|
||||
}
|
||||
};
|
||||
let span = tracing::info_span!(
|
||||
"exec_server.rpc_server.outbound_queue_dequeued",
|
||||
message_kind,
|
||||
method,
|
||||
request_id,
|
||||
process_id,
|
||||
seq,
|
||||
queue_wait_ms = envelope.queued_at.elapsed().as_secs_f64() * 1_000.0,
|
||||
);
|
||||
if let Some(trace) = envelope.trace.as_ref() {
|
||||
let _ = codex_otel::set_parent_from_w3c_trace_context(&span, trace);
|
||||
}
|
||||
span
|
||||
}
|
||||
|
||||
fn record_request_dequeued(request: &codex_exec_server_protocol::JSONRPCRequest) {
|
||||
let method = request.method.as_str();
|
||||
let span = tracing::info_span!("exec_server.processor.request_dequeued", method,);
|
||||
if let Some(trace) = &request.trace
|
||||
&& !codex_otel::set_parent_from_w3c_trace_context(&span, trace)
|
||||
{
|
||||
warn!(method, "ignoring invalid inbound exec-server trace carrier");
|
||||
}
|
||||
span.in_scope(|| {});
|
||||
}
|
||||
|
||||
fn request_span(
|
||||
span_name: &str,
|
||||
request: &codex_exec_server_protocol::JSONRPCRequest,
|
||||
@@ -302,6 +401,7 @@ mod tests {
|
||||
use tracing_subscriber::filter::filter_fn;
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
use super::record_request_dequeued;
|
||||
use super::request_span;
|
||||
use super::run_connection;
|
||||
use crate::ExecServerRuntimePaths;
|
||||
@@ -351,6 +451,7 @@ mod tests {
|
||||
params: None,
|
||||
trace: Some(trace),
|
||||
};
|
||||
record_request_dequeued(&request);
|
||||
let request_span = request_span("unknown", &request);
|
||||
request_span.in_scope(|| {});
|
||||
drop(request_span);
|
||||
@@ -372,6 +473,12 @@ mod tests {
|
||||
);
|
||||
assert_eq!(request_span.span_context.trace_id(), trace_id);
|
||||
assert_eq!(request_span.parent_span_id, parent_span_id);
|
||||
let dequeued_span = spans
|
||||
.iter()
|
||||
.find(|span| span.name.as_ref() == "exec_server.processor.request_dequeued")
|
||||
.expect("request dequeued span");
|
||||
assert_eq!(dequeued_span.span_context.trace_id(), trace_id);
|
||||
assert_eq!(dequeued_span.parent_span_id, parent_span_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in New Issue
Block a user