Skip to content

Conversation

@vsraccubits
Copy link
Contributor

Add /v1/traces, /v1/metrics, /v1/logs proxy endpoints that forward OTLP data from SDKs to the internal OTEL collector. Routes bypass analytics/blocking middleware to avoid recursive tracing. Includes lightweight Bearer auth, 5MB body limit, and Helm chart config.

Add /v1/traces, /v1/metrics, /v1/logs proxy endpoints that forward
OTLP data from SDKs to the internal OTEL collector. Routes bypass
analytics/blocking middleware to avoid recursive tracing. Includes
lightweight Bearer auth, 5MB body limit, and Helm chart config.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @vsraccubits, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new OTLP telemetry proxy within the budgateway service, enabling SDKs to send OpenTelemetry Protocol (OTLP) traces, metrics, and logs directly to an internal OpenTelemetry collector. The proxy is designed for efficiency and stability, bypassing standard middleware and incorporating its own lightweight authentication and body size limits to ensure secure and performant telemetry ingestion.

Highlights

  • OTLP Telemetry Proxy Endpoints: Implemented new proxy endpoints at /v1/traces, /v1/metrics, and /v1/logs to forward OpenTelemetry Protocol (OTLP) data from SDKs to an internal OTEL collector.
  • Middleware Bypass: Configured the OTLP proxy routes to bypass existing analytics and blocking middleware, as well as the main tracing layer, to prevent recursive tracing and ensure efficient telemetry ingestion.
  • Lightweight Authentication: Introduced a new, lightweight Bearer token authentication mechanism specifically for the telemetry endpoints, which validates API keys without consuming the request body.
  • Body Size Limit: Enforced a 5MB body size limit for incoming OTLP requests to manage payload sizes effectively.
  • Configuration Updates: Added configuration options in Helm charts and the tensorzero.toml file to enable and configure the OTLP proxy, including setting the OTLP HTTP collector endpoint.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • infra/helm/bud/templates/budgateway.yaml
    • Enabled the gateway.otlp_proxy configuration within the Helm template.
  • infra/helm/bud/values.yaml
    • Added the OTEL_EXPORTER_OTLP_HTTP_ENDPOINT environment variable for the OTLP HTTP collector.
  • services/budgateway/config/tensorzero.toml
    • Enabled the gateway.otlp_proxy configuration in the default settings.
  • services/budgateway/gateway/src/main.rs
    • Imported the new require_api_key_telemetry authentication middleware.
    • Defined and conditionally enabled OTLP proxy routes for traces, metrics, and logs.
    • Applied a 5MB body limit and telemetry-specific authentication to OTLP routes.
    • Adjusted router merging logic to ensure OTLP routes bypass analytics, blocking, and tracing middleware.
  • services/budgateway/tensorzero-internal/src/auth.rs
    • Implemented require_api_key_telemetry, a new asynchronous function for lightweight Bearer token validation without consuming the request body.
  • services/budgateway/tensorzero-internal/src/config_parser.rs
    • Defined a new OtlpProxyConfig struct to manage OTLP proxy settings, including an enabled flag and collector endpoint.
    • Integrated OtlpProxyConfig into the GatewayConfig structure.
  • services/budgateway/tensorzero-internal/src/endpoints/mod.rs
    • Declared the new otlp_proxy module.
  • services/budgateway/tensorzero-internal/src/endpoints/otlp_proxy.rs
    • Added a new file containing the otlp_proxy_handler function, responsible for forwarding OTLP requests to the configured collector endpoint.
  • services/budgateway/tensorzero-internal/src/gateway_util.rs
    • Updated test configurations to include the default otlp_proxy settings.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces an OTLP telemetry proxy, a valuable feature for enhancing SDK observability. The implementation is well-structured, adding new endpoints, configuration options, and a dedicated authentication middleware. The routing logic correctly bypasses analytics and blocking middleware, which is crucial for preventing recursive tracing.

I have two main suggestions for improvement:

  1. In auth.rs, I recommend refactoring the API key extraction logic for better readability and to avoid an unnecessary memory allocation.
  2. In otlp_proxy.rs, I suggest streaming the response body from the upstream collector instead of buffering it. This is a more memory-efficient and robust approach for a proxy.

Overall, the changes are solid, and with these refinements, the feature will be even more robust and maintainable.

Comment on lines +439 to +471
pub async fn require_api_key_telemetry(
State(auth): State<Auth>,
request: Request,
next: Next,
) -> Result<Response, Response> {
let key = request
.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.map(|s| {
let s = s.trim();
s.strip_prefix("Bearer ").unwrap_or(s).to_string()
});

let key = match key {
Some(k) => k,
None => {
return Err(auth_error_response(
StatusCode::UNAUTHORIZED,
"Missing authorization header",
))
}
};

if auth.validate_api_key(&key).is_err() {
return Err(auth_error_response(
StatusCode::UNAUTHORIZED,
"Invalid API key",
));
}

Ok(next.run(request).await)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for extracting and validating the API key can be made more idiomatic and efficient. The current implementation involves an extra String allocation and a slightly verbose match statement.

Refactoring this to use ok_or_else and process the &str slice directly will make the code cleaner and avoid the unnecessary allocation, improving performance slightly.

pub async fn require_api_key_telemetry(
    State(auth): State<Auth>,
    request: Request,
    next: Next,
) -> Result<Response, Response> {
    let key = request
        .headers()
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.strip_prefix("Bearer ").unwrap_or(s).trim())
        .ok_or_else(|| {
            auth_error_response(
                StatusCode::UNAUTHORIZED,
                "Missing or invalid authorization header",
            )
        })?;

    if auth.validate_api_key(key).is_err() {
        return Err(auth_error_response(
            StatusCode::UNAUTHORIZED,
            "Invalid API key",
        ));
    }

    Ok(next.run(request).await)
}

Comment on lines +36 to +47
Ok(resp) => {
let status = StatusCode::from_u16(resp.status().as_u16())
.unwrap_or(StatusCode::BAD_GATEWAY);
let resp_headers = resp.headers().clone();
let resp_body = resp.bytes().await.unwrap_or_default();

let mut response = (status, resp_body).into_response();
for (name, value) in resp_headers.iter() {
response.headers_mut().insert(name, value.clone());
}
Ok(response)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation buffers the entire upstream response body in memory using resp.bytes().await before sending it to the client. For a proxy handling potentially large payloads (even with a 5MB limit), it's more memory-efficient and robust to stream the response body directly.

Streaming avoids holding the entire response in memory and handles network interruptions more gracefully. Additionally, the status code handling can be simplified by using resp.status() directly.

        Ok(resp) => {
            let mut response_builder = Response::builder().status(resp.status());

            // Copy headers from the upstream response.
            if let Some(headers) = response_builder.headers_mut() {
                headers.extend(resp.headers().clone());
            }

            // Stream the body from the upstream response.
            let body = Body::from_stream(resp.bytes_stream());

            // It's safe to unwrap here as we've built a valid response.
            Ok(response_builder.body(body).unwrap())
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant