Base: codex-main originale (prima del fork aKode)
This commit is contained in:
17
codex-rs/codex-client/src/lib.rs
Normal file
17
codex-rs/codex-client/src/lib.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
mod provider;
|
||||
mod retry;
|
||||
mod sse;
|
||||
mod telemetry;
|
||||
|
||||
pub use crate::provider::Provider;
|
||||
pub use crate::provider::RetryConfig;
|
||||
pub use crate::retry::RetryOn;
|
||||
pub use crate::retry::RetryOperation;
|
||||
pub use crate::retry::RetryPolicy;
|
||||
pub use crate::retry::backoff;
|
||||
pub use crate::retry::run_with_retry;
|
||||
pub use crate::sse::sse_stream;
|
||||
pub use crate::telemetry::RequestTelemetry;
|
||||
pub use codex_http_client::HttpClient as CodexHttpClient;
|
||||
pub use codex_http_client::RequestBuilder as CodexRequestBuilder;
|
||||
pub use codex_http_client::*;
|
||||
103
codex-rs/codex-client/src/provider.rs
Normal file
103
codex-rs/codex-client/src/provider.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Endpoint configuration and request construction shared by API clients.
|
||||
|
||||
use crate::Request;
|
||||
use crate::RequestCompression;
|
||||
use crate::RetryOn;
|
||||
use crate::RetryPolicy;
|
||||
use http::Method;
|
||||
use http::header::HeaderMap;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
/// High-level retry configuration for a provider.
|
||||
///
|
||||
/// This is converted into a `RetryPolicy` used by `codex-client` to drive
|
||||
/// transport-level retries for both unary and streaming calls.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RetryConfig {
|
||||
pub max_attempts: u64,
|
||||
pub base_delay: Duration,
|
||||
pub retry_429: bool,
|
||||
pub retry_5xx: bool,
|
||||
pub retry_transport: bool,
|
||||
}
|
||||
|
||||
impl RetryConfig {
|
||||
pub fn to_policy(&self) -> RetryPolicy {
|
||||
RetryPolicy {
|
||||
max_attempts: self.max_attempts,
|
||||
base_delay: self.base_delay,
|
||||
retry_on: RetryOn {
|
||||
retry_429: self.retry_429,
|
||||
retry_5xx: self.retry_5xx,
|
||||
retry_transport: self.retry_transport,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP endpoint configuration used to talk to a concrete API deployment.
|
||||
///
|
||||
/// Encapsulates base URL, default headers, query params, retry policy, and
|
||||
/// stream idle timeout, plus helper methods for building requests.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Provider {
|
||||
pub name: String,
|
||||
pub base_url: String,
|
||||
pub query_params: Option<HashMap<String, String>>,
|
||||
pub headers: HeaderMap,
|
||||
pub retry: RetryConfig,
|
||||
pub stream_idle_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Provider {
|
||||
pub fn url_for_path(&self, path: &str) -> String {
|
||||
let base = self.base_url.trim_end_matches('/');
|
||||
let path = path.trim_start_matches('/');
|
||||
let mut url = if path.is_empty() {
|
||||
base.to_string()
|
||||
} else {
|
||||
format!("{base}/{path}")
|
||||
};
|
||||
|
||||
if let Some(params) = &self.query_params
|
||||
&& !params.is_empty()
|
||||
{
|
||||
let qs = params
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
url.push('?');
|
||||
url.push_str(&qs);
|
||||
}
|
||||
|
||||
url
|
||||
}
|
||||
|
||||
pub fn build_request(&self, method: Method, path: &str) -> Request {
|
||||
Request {
|
||||
method,
|
||||
url: self.url_for_path(path),
|
||||
headers: self.headers.clone(),
|
||||
body: None,
|
||||
compression: RequestCompression::None,
|
||||
timeout: None,
|
||||
response_body_limit_bytes: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn websocket_url_for_path(&self, path: &str) -> Result<Url, url::ParseError> {
|
||||
let mut url = Url::parse(&self.url_for_path(path))?;
|
||||
|
||||
let scheme = match url.scheme() {
|
||||
"http" => "ws",
|
||||
"https" => "wss",
|
||||
"ws" | "wss" => return Ok(url),
|
||||
_ => return Ok(url),
|
||||
};
|
||||
let _ = url.set_scheme(scheme);
|
||||
Ok(url)
|
||||
}
|
||||
}
|
||||
118
codex-rs/codex-client/src/retry.rs
Normal file
118
codex-rs/codex-client/src/retry.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
use codex_http_client::Request;
|
||||
use codex_http_client::RetryAfter;
|
||||
use codex_http_client::TransportError;
|
||||
use rand::Rng;
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RetryPolicy {
|
||||
pub max_attempts: u64,
|
||||
pub base_delay: Duration,
|
||||
pub retry_on: RetryOn,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RetryOn {
|
||||
pub retry_429: bool,
|
||||
pub retry_5xx: bool,
|
||||
pub retry_transport: bool,
|
||||
}
|
||||
|
||||
impl RetryOn {
|
||||
pub fn should_retry(&self, err: &TransportError, attempt: u64, max_attempts: u64) -> bool {
|
||||
if attempt >= max_attempts {
|
||||
return false;
|
||||
}
|
||||
match err {
|
||||
TransportError::Http { status, .. } => {
|
||||
(self.retry_429 && status.as_u16() == 429)
|
||||
|| (self.retry_5xx && status.is_server_error())
|
||||
}
|
||||
TransportError::Timeout
|
||||
| TransportError::Connection(_)
|
||||
| TransportError::Network(_) => self.retry_transport,
|
||||
TransportError::Build(_)
|
||||
| TransportError::RetryLimit
|
||||
| TransportError::Policy(_)
|
||||
| TransportError::ResponseTooLarge { .. } => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backoff(base: Duration, attempt: u64) -> Duration {
|
||||
if attempt == 0 {
|
||||
return base;
|
||||
}
|
||||
let exp = 2u64.saturating_pow(attempt as u32 - 1);
|
||||
let millis = base.as_millis() as u64;
|
||||
let raw = millis.saturating_mul(exp);
|
||||
let jitter: f64 = rand::rng().random_range(0.9..1.1);
|
||||
Duration::from_millis((raw as f64 * jitter) as u64)
|
||||
}
|
||||
|
||||
/// Identifies a retry path and its associated trace-event layer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum RetryOperation {
|
||||
HttpRequest,
|
||||
Sampling,
|
||||
RemoteCompactionV2,
|
||||
}
|
||||
|
||||
/// Emits retry telemetry at the caller's source location without adding it to normal OTEL logs.
|
||||
#[macro_export]
|
||||
macro_rules! record_retry {
|
||||
($attempt:expr, $delay:expr, $operation:expr $(,)?) => {{
|
||||
let (layer, operation) = match $operation {
|
||||
$crate::RetryOperation::HttpRequest => ("http", "request"),
|
||||
$crate::RetryOperation::Sampling => ("stream", "sampling"),
|
||||
$crate::RetryOperation::RemoteCompactionV2 => ("stream", "remote_compaction_v2"),
|
||||
};
|
||||
|
||||
::tracing::event!(
|
||||
target: "codex_otel.trace_safe",
|
||||
::tracing::Level::TRACE,
|
||||
event.name = "codex.retry",
|
||||
retry.attempt = $attempt,
|
||||
retry.delay_ms = ($delay).as_millis() as u64,
|
||||
retry.layer = layer,
|
||||
retry.operation = operation,
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
pub async fn run_with_retry<T, F, Fut>(
|
||||
policy: RetryPolicy,
|
||||
mut make_req: impl FnMut() -> Request,
|
||||
op: F,
|
||||
) -> Result<T, TransportError>
|
||||
where
|
||||
F: Fn(Request, u64) -> Fut,
|
||||
Fut: Future<Output = Result<T, TransportError>>,
|
||||
{
|
||||
for attempt in 0..=policy.max_attempts {
|
||||
let req = make_req();
|
||||
match op(req, attempt).await {
|
||||
Ok(resp) => return Ok(resp),
|
||||
Err(err)
|
||||
if policy
|
||||
.retry_on
|
||||
.should_retry(&err, attempt, policy.max_attempts) =>
|
||||
{
|
||||
let retry_attempt = attempt + 1;
|
||||
let retry_after = err.retry_after();
|
||||
let delay = retry_after
|
||||
.map(RetryAfter::remaining_delay)
|
||||
.unwrap_or_else(|| backoff(policy.base_delay, retry_attempt));
|
||||
crate::record_retry!(retry_attempt, delay, RetryOperation::HttpRequest);
|
||||
if let Some(retry_after) = retry_after {
|
||||
tokio::time::sleep_until(retry_after.deadline()).await;
|
||||
} else {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
Err(TransportError::RetryLimit)
|
||||
}
|
||||
48
codex-rs/codex-client/src/sse.rs
Normal file
48
codex-rs/codex-client/src/sse.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use codex_http_client::ByteStream;
|
||||
use codex_http_client::StreamError;
|
||||
use eventsource_stream::Eventsource;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
/// Minimal SSE helper that forwards raw `data:` frames as UTF-8 strings.
|
||||
///
|
||||
/// Errors and idle timeouts are sent as `Err(StreamError)` before the task exits.
|
||||
pub fn sse_stream(
|
||||
stream: ByteStream,
|
||||
idle_timeout: Duration,
|
||||
tx: mpsc::Sender<Result<String, StreamError>>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
let mut stream = stream
|
||||
.map(|res| res.map_err(|e| StreamError::Stream(e.to_string())))
|
||||
.eventsource();
|
||||
|
||||
loop {
|
||||
match timeout(idle_timeout, stream.next()).await {
|
||||
Ok(Some(Ok(ev))) => {
|
||||
if tx.send(Ok(ev.data.clone())).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Ok(Some(Err(e))) => {
|
||||
let _ = tx.send(Err(StreamError::Stream(e.to_string()))).await;
|
||||
return;
|
||||
}
|
||||
Ok(None) => {
|
||||
let _ = tx
|
||||
.send(Err(StreamError::Stream(
|
||||
"stream closed before completion".into(),
|
||||
)))
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = tx.send(Err(StreamError::Timeout)).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
14
codex-rs/codex-client/src/telemetry.rs
Normal file
14
codex-rs/codex-client/src/telemetry.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use codex_http_client::TransportError;
|
||||
use http::StatusCode;
|
||||
use std::time::Duration;
|
||||
|
||||
/// API specific telemetry.
|
||||
pub trait RequestTelemetry: Send + Sync {
|
||||
fn on_request(
|
||||
&self,
|
||||
attempt: u64,
|
||||
status: Option<StatusCode>,
|
||||
error: Option<&TransportError>,
|
||||
duration: Duration,
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user