diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 2bd379252a..227ff27150 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2698,6 +2698,18 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "codex-feedback-log-sink" +version = "0.0.0" +dependencies = [ + "codex-state", + "pretty_assertions", + "prost 0.14.3", + "tonic", + "tonic-prost", + "tonic-prost-build", +] + [[package]] name = "codex-file-search" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 648c184ec8..662042bc57 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -14,6 +14,7 @@ members = [ "apply-patch", "arg0", "feedback", + "feedback-log-sink", "features", "install-context", "codex-backend-openapi-models", @@ -145,6 +146,7 @@ codex-execpolicy = { path = "execpolicy" } codex-experimental-api-macros = { path = "codex-experimental-api-macros" } codex-features = { path = "features" } codex-feedback = { path = "feedback" } +codex-feedback-log-sink = { path = "feedback-log-sink" } codex-install-context = { path = "install-context" } codex-file-search = { path = "file-search" } codex-git-utils = { path = "git-utils" } diff --git a/codex-rs/feedback-log-sink/BUILD.bazel b/codex-rs/feedback-log-sink/BUILD.bazel new file mode 100644 index 0000000000..81ad729a31 --- /dev/null +++ b/codex-rs/feedback-log-sink/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "feedback-log-sink", + crate_name = "codex_feedback_log_sink", +) diff --git a/codex-rs/feedback-log-sink/Cargo.toml b/codex-rs/feedback-log-sink/Cargo.toml new file mode 100644 index 0000000000..d5b4b688ff --- /dev/null +++ b/codex-rs/feedback-log-sink/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "codex-feedback-log-sink" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +name = "codex_feedback_log_sink" +path = "src/lib.rs" + +[[example]] +name = "generate-proto" +path = "examples/generate-proto.rs" + +[lints] +workspace = true + +[dependencies] +codex-state = { workspace = true } +prost = "0.14.3" +tonic = { workspace = true } +tonic-prost = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } +tonic-prost-build = { version = "=0.14.3", default-features = false, features = ["transport"] } diff --git a/codex-rs/feedback-log-sink/examples/generate-proto.rs b/codex-rs/feedback-log-sink/examples/generate-proto.rs new file mode 100644 index 0000000000..22c7dc8af9 --- /dev/null +++ b/codex-rs/feedback-log-sink/examples/generate-proto.rs @@ -0,0 +1,19 @@ +use std::path::PathBuf; + +fn main() -> Result<(), Box> { + let Some(proto_dir_arg) = std::env::args().nth(1) else { + eprintln!("Usage: generate-proto "); + std::process::exit(1); + }; + + let proto_dir = PathBuf::from(proto_dir_arg); + let proto_file = proto_dir.join("codex.feedback_log_sink.v1.proto"); + + tonic_prost_build::configure() + .build_client(true) + .build_server(true) + .out_dir(&proto_dir) + .compile_protos(&[proto_file], &[proto_dir])?; + + Ok(()) +} diff --git a/codex-rs/feedback-log-sink/scripts/generate-proto.sh b/codex-rs/feedback-log-sink/scripts/generate-proto.sh new file mode 100755 index 0000000000..5a88b843b5 --- /dev/null +++ b/codex-rs/feedback-log-sink/scripts/generate-proto.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo_root="$(cd "$script_dir/../../.." && pwd)" +proto_dir="$repo_root/codex-rs/feedback-log-sink/src/proto" +generated="$proto_dir/codex.feedback_log_sink.v1.rs" +tmpdir="$(mktemp -d)" + +cleanup() { + rm -rf "$tmpdir" +} +trap cleanup EXIT + +( + cd "$repo_root/codex-rs" + CARGO_TARGET_DIR="$tmpdir/target" cargo run \ + -p codex-feedback-log-sink \ + --example generate-proto \ + -- "$proto_dir" +) + +if ! sed -n '2p' "$generated" | grep -q 'clippy::trivially_copy_pass_by_ref'; then + { + sed -n '1p' "$generated" + printf '#![allow(clippy::trivially_copy_pass_by_ref)]\n' + sed '1d' "$generated" + } > "$tmpdir/generated.rs" + mv "$tmpdir/generated.rs" "$generated" +fi + +rustfmt --edition 2024 "$generated" + +awk ' + NR == 3 && previous ~ /clippy::trivially_copy_pass_by_ref/ && $0 != "" { print "" } + { print; previous = $0 } +' "$generated" > "$tmpdir/formatted.rs" +mv "$tmpdir/formatted.rs" "$generated" diff --git a/codex-rs/feedback-log-sink/src/lib.rs b/codex-rs/feedback-log-sink/src/lib.rs new file mode 100644 index 0000000000..ca2bfecbba --- /dev/null +++ b/codex-rs/feedback-log-sink/src/lib.rs @@ -0,0 +1,133 @@ +//! Remote feedback log sink protocol helpers. + +use codex_state::LogEntry; + +#[path = "proto/codex.feedback_log_sink.v1.rs"] +pub mod proto; + +impl From for proto::FeedbackLogEntry { + fn from(entry: LogEntry) -> Self { + Self { + ts: entry.ts, + ts_nanos: entry.ts_nanos, + level: entry.level, + target: entry.target, + message: entry.message, + feedback_log_body: entry.feedback_log_body, + thread_id: entry.thread_id, + process_uuid: entry.process_uuid, + module_path: entry.module_path, + file: entry.file, + line: entry.line, + } + } +} + +pub fn append_log_batch_request( + entries: Vec, + source_process_uuid: impl Into, +) -> proto::AppendLogBatchRequest { + proto::AppendLogBatchRequest { + entries: entries.into_iter().map(Into::into).collect(), + source_process_uuid: source_process_uuid.into(), + } +} + +#[cfg(test)] +mod tests { + use codex_state::LogEntry; + use pretty_assertions::assert_eq; + + use super::append_log_batch_request; + use super::proto; + + #[test] + fn log_entry_to_proto_preserves_all_fields() { + let entry = populated_log_entry(); + + let actual = proto::FeedbackLogEntry::from(entry); + + assert_eq!(actual, populated_feedback_log_entry()); + } + + #[test] + fn log_entry_to_proto_preserves_absent_optional_fields() { + let entry = LogEntry { + ts: 1700000000, + ts_nanos: 42, + level: "WARN".to_string(), + target: "codex::target".to_string(), + message: None, + feedback_log_body: None, + thread_id: None, + process_uuid: None, + module_path: None, + file: None, + line: None, + }; + + let actual = proto::FeedbackLogEntry::from(entry); + + assert_eq!( + actual, + proto::FeedbackLogEntry { + ts: 1700000000, + ts_nanos: 42, + level: "WARN".to_string(), + target: "codex::target".to_string(), + message: None, + feedback_log_body: None, + thread_id: None, + process_uuid: None, + module_path: None, + file: None, + line: None, + } + ); + } + + #[test] + fn append_log_batch_request_sets_source_process_uuid_and_entries() { + let actual = append_log_batch_request(vec![populated_log_entry()], "source-process"); + + assert_eq!( + actual, + proto::AppendLogBatchRequest { + entries: vec![populated_feedback_log_entry()], + source_process_uuid: "source-process".to_string(), + } + ); + } + + fn populated_log_entry() -> LogEntry { + LogEntry { + ts: 1700000000, + ts_nanos: 123456789, + level: "INFO".to_string(), + target: "codex::feedback".to_string(), + message: Some("captured message".to_string()), + feedback_log_body: Some("structured body".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("process-entry".to_string()), + module_path: Some("codex_state::log_db".to_string()), + file: Some("state/src/log_db.rs".to_string()), + line: Some(123), + } + } + + fn populated_feedback_log_entry() -> proto::FeedbackLogEntry { + proto::FeedbackLogEntry { + ts: 1700000000, + ts_nanos: 123456789, + level: "INFO".to_string(), + target: "codex::feedback".to_string(), + message: Some("captured message".to_string()), + feedback_log_body: Some("structured body".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("process-entry".to_string()), + module_path: Some("codex_state::log_db".to_string()), + file: Some("state/src/log_db.rs".to_string()), + line: Some(123), + } + } +} diff --git a/codex-rs/feedback-log-sink/src/proto/codex.feedback_log_sink.v1.proto b/codex-rs/feedback-log-sink/src/proto/codex.feedback_log_sink.v1.proto new file mode 100644 index 0000000000..5cf0f3ed63 --- /dev/null +++ b/codex-rs/feedback-log-sink/src/proto/codex.feedback_log_sink.v1.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; + +package codex.feedback_log_sink.v1; + +service FeedbackLogSink { + rpc AppendLogBatch(AppendLogBatchRequest) returns (AppendLogBatchResponse); +} + +message AppendLogBatchRequest { + repeated FeedbackLogEntry entries = 1; + string source_process_uuid = 2; +} + +message AppendLogBatchResponse {} + +message FeedbackLogEntry { + int64 ts = 1; + int64 ts_nanos = 2; + string level = 3; + string target = 4; + optional string message = 5; + optional string feedback_log_body = 6; + optional string thread_id = 7; + optional string process_uuid = 8; + optional string module_path = 9; + optional string file = 10; + optional int64 line = 11; +} diff --git a/codex-rs/feedback-log-sink/src/proto/codex.feedback_log_sink.v1.rs b/codex-rs/feedback-log-sink/src/proto/codex.feedback_log_sink.v1.rs new file mode 100644 index 0000000000..594b5decf3 --- /dev/null +++ b/codex-rs/feedback-log-sink/src/proto/codex.feedback_log_sink.v1.rs @@ -0,0 +1,315 @@ +// This file is @generated by prost-build. +#![allow(clippy::trivially_copy_pass_by_ref)] + +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct AppendLogBatchRequest { + #[prost(message, repeated, tag = "1")] + pub entries: ::prost::alloc::vec::Vec, + #[prost(string, tag = "2")] + pub source_process_uuid: ::prost::alloc::string::String, +} +#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] +pub struct AppendLogBatchResponse {} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct FeedbackLogEntry { + #[prost(int64, tag = "1")] + pub ts: i64, + #[prost(int64, tag = "2")] + pub ts_nanos: i64, + #[prost(string, tag = "3")] + pub level: ::prost::alloc::string::String, + #[prost(string, tag = "4")] + pub target: ::prost::alloc::string::String, + #[prost(string, optional, tag = "5")] + pub message: ::core::option::Option<::prost::alloc::string::String>, + #[prost(string, optional, tag = "6")] + pub feedback_log_body: ::core::option::Option<::prost::alloc::string::String>, + #[prost(string, optional, tag = "7")] + pub thread_id: ::core::option::Option<::prost::alloc::string::String>, + #[prost(string, optional, tag = "8")] + pub process_uuid: ::core::option::Option<::prost::alloc::string::String>, + #[prost(string, optional, tag = "9")] + pub module_path: ::core::option::Option<::prost::alloc::string::String>, + #[prost(string, optional, tag = "10")] + pub file: ::core::option::Option<::prost::alloc::string::String>, + #[prost(int64, optional, tag = "11")] + pub line: ::core::option::Option, +} +/// Generated client implementations. +pub mod feedback_log_sink_client { + #![allow( + unused_variables, + dead_code, + missing_docs, + clippy::wildcard_imports, + clippy::let_unit_value + )] + use tonic::codegen::http::Uri; + use tonic::codegen::*; + #[derive(Debug, Clone)] + pub struct FeedbackLogSinkClient { + inner: tonic::client::Grpc, + } + impl FeedbackLogSinkClient { + /// Attempt to create a new client by connecting to a given endpoint. + pub async fn connect(dst: D) -> Result + where + D: TryInto, + D::Error: Into, + { + let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; + Ok(Self::new(conn)) + } + } + impl FeedbackLogSinkClient + where + T: tonic::client::GrpcService, + T::Error: Into, + T::ResponseBody: Body + std::marker::Send + 'static, + ::Error: Into + std::marker::Send, + { + pub fn new(inner: T) -> Self { + let inner = tonic::client::Grpc::new(inner); + Self { inner } + } + pub fn with_origin(inner: T, origin: Uri) -> Self { + let inner = tonic::client::Grpc::with_origin(inner, origin); + Self { inner } + } + pub fn with_interceptor( + inner: T, + interceptor: F, + ) -> FeedbackLogSinkClient> + where + F: tonic::service::Interceptor, + T::ResponseBody: Default, + T: tonic::codegen::Service< + http::Request, + Response = http::Response< + >::ResponseBody, + >, + >, + >>::Error: + Into + std::marker::Send + std::marker::Sync, + { + FeedbackLogSinkClient::new(InterceptedService::new(inner, interceptor)) + } + /// Compress requests with the given encoding. + /// + /// This requires the server to support it otherwise it might respond with an + /// error. + #[must_use] + pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.inner = self.inner.send_compressed(encoding); + self + } + /// Enable decompressing responses. + #[must_use] + pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.inner = self.inner.accept_compressed(encoding); + self + } + /// Limits the maximum size of a decoded message. + /// + /// Default: `4MB` + #[must_use] + pub fn max_decoding_message_size(mut self, limit: usize) -> Self { + self.inner = self.inner.max_decoding_message_size(limit); + self + } + /// Limits the maximum size of an encoded message. + /// + /// Default: `usize::MAX` + #[must_use] + pub fn max_encoding_message_size(mut self, limit: usize) -> Self { + self.inner = self.inner.max_encoding_message_size(limit); + self + } + pub async fn append_log_batch( + &mut self, + request: impl tonic::IntoRequest, + ) -> std::result::Result, tonic::Status> + { + self.inner.ready().await.map_err(|e| { + tonic::Status::unknown(format!("Service was not ready: {}", e.into())) + })?; + let codec = tonic_prost::ProstCodec::default(); + let path = http::uri::PathAndQuery::from_static( + "/codex.feedback_log_sink.v1.FeedbackLogSink/AppendLogBatch", + ); + let mut req = request.into_request(); + req.extensions_mut().insert(GrpcMethod::new( + "codex.feedback_log_sink.v1.FeedbackLogSink", + "AppendLogBatch", + )); + self.inner.unary(req, path, codec).await + } + } +} +/// Generated server implementations. +pub mod feedback_log_sink_server { + #![allow( + unused_variables, + dead_code, + missing_docs, + clippy::wildcard_imports, + clippy::let_unit_value + )] + use tonic::codegen::*; + /// Generated trait containing gRPC methods that should be implemented for use with FeedbackLogSinkServer. + #[async_trait] + pub trait FeedbackLogSink: std::marker::Send + std::marker::Sync + 'static { + async fn append_log_batch( + &self, + request: tonic::Request, + ) -> std::result::Result, tonic::Status>; + } + #[derive(Debug)] + pub struct FeedbackLogSinkServer { + inner: Arc, + accept_compression_encodings: EnabledCompressionEncodings, + send_compression_encodings: EnabledCompressionEncodings, + max_decoding_message_size: Option, + max_encoding_message_size: Option, + } + impl FeedbackLogSinkServer { + pub fn new(inner: T) -> Self { + Self::from_arc(Arc::new(inner)) + } + pub fn from_arc(inner: Arc) -> Self { + Self { + inner, + accept_compression_encodings: Default::default(), + send_compression_encodings: Default::default(), + max_decoding_message_size: None, + max_encoding_message_size: None, + } + } + pub fn with_interceptor(inner: T, interceptor: F) -> InterceptedService + where + F: tonic::service::Interceptor, + { + InterceptedService::new(Self::new(inner), interceptor) + } + /// Enable decompressing requests with the given encoding. + #[must_use] + pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.accept_compression_encodings.enable(encoding); + self + } + /// Compress responses with the given encoding, if the client supports it. + #[must_use] + pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { + self.send_compression_encodings.enable(encoding); + self + } + /// Limits the maximum size of a decoded message. + /// + /// Default: `4MB` + #[must_use] + pub fn max_decoding_message_size(mut self, limit: usize) -> Self { + self.max_decoding_message_size = Some(limit); + self + } + /// Limits the maximum size of an encoded message. + /// + /// Default: `usize::MAX` + #[must_use] + pub fn max_encoding_message_size(mut self, limit: usize) -> Self { + self.max_encoding_message_size = Some(limit); + self + } + } + impl tonic::codegen::Service> for FeedbackLogSinkServer + where + T: FeedbackLogSink, + B: Body + std::marker::Send + 'static, + B::Error: Into + std::marker::Send + 'static, + { + type Response = http::Response; + type Error = std::convert::Infallible; + type Future = BoxFuture; + fn poll_ready( + &mut self, + _cx: &mut Context<'_>, + ) -> Poll> { + Poll::Ready(Ok(())) + } + fn call(&mut self, req: http::Request) -> Self::Future { + match req.uri().path() { + "/codex.feedback_log_sink.v1.FeedbackLogSink/AppendLogBatch" => { + #[allow(non_camel_case_types)] + struct AppendLogBatchSvc(pub Arc); + impl + tonic::server::UnaryService + for AppendLogBatchSvc + { + type Response = super::AppendLogBatchResponse; + type Future = BoxFuture, tonic::Status>; + fn call( + &mut self, + request: tonic::Request, + ) -> Self::Future { + let inner = Arc::clone(&self.0); + let fut = async move { + ::append_log_batch(&inner, request).await + }; + Box::pin(fut) + } + } + let accept_compression_encodings = self.accept_compression_encodings; + let send_compression_encodings = self.send_compression_encodings; + let max_decoding_message_size = self.max_decoding_message_size; + let max_encoding_message_size = self.max_encoding_message_size; + let inner = self.inner.clone(); + let fut = async move { + let method = AppendLogBatchSvc(inner); + let codec = tonic_prost::ProstCodec::default(); + let mut grpc = tonic::server::Grpc::new(codec) + .apply_compression_config( + accept_compression_encodings, + send_compression_encodings, + ) + .apply_max_message_size_config( + max_decoding_message_size, + max_encoding_message_size, + ); + let res = grpc.unary(method, req).await; + Ok(res) + }; + Box::pin(fut) + } + _ => Box::pin(async move { + let mut response = http::Response::new(tonic::body::Body::default()); + let headers = response.headers_mut(); + headers.insert( + tonic::Status::GRPC_STATUS, + (tonic::Code::Unimplemented as i32).into(), + ); + headers.insert( + http::header::CONTENT_TYPE, + tonic::metadata::GRPC_CONTENT_TYPE, + ); + Ok(response) + }), + } + } + } + impl Clone for FeedbackLogSinkServer { + fn clone(&self) -> Self { + let inner = self.inner.clone(); + Self { + inner, + accept_compression_encodings: self.accept_compression_encodings, + send_compression_encodings: self.send_compression_encodings, + max_decoding_message_size: self.max_decoding_message_size, + max_encoding_message_size: self.max_encoding_message_size, + } + } + } + /// Generated gRPC service name + pub const SERVICE_NAME: &str = "codex.feedback_log_sink.v1.FeedbackLogSink"; + impl tonic::server::NamedService for FeedbackLogSinkServer { + const NAME: &'static str = SERVICE_NAME; + } +}