Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(transport): add error handling for transport operations

Steven Enamakelc610f23ee84c
diff --git a/crates/openhuman-core/src/backend/transport/error.rs b/crates/openhuman-core/src/backend/transport/error.rs
index 869eea9ca2..66e7ab2312 100644
--- a/crates/openhuman-core/src/backend/transport/error.rs
+++ b/crates/openhuman-core/src/backend/transport/error.rs
@@ -1,7 +1,7 @@
//! The error a [`BackendTransport`](super::BackendTransport) returns.
//!
//! This is the core-owned image of the variants the classification code in
-//! [`crate::api::rest`] and `integrations/client/errors.rs` matches on. It
+//! [`crate::backend::error`] and `integrations/client/errors.rs` matches on. It
//! mirrors the vendored SDK's `Error` one-to-one for those arms so a transport
//! built on the SDK maps mechanically, while the core itself never names the
//! SDK type.
diff --git a/crates/openhuman-core/src/backend/transport/mod.rs b/crates/openhuman-core/src/backend/transport/mod.rs
index 02990fc3cf..39c265c734 100644
--- a/crates/openhuman-core/src/backend/transport/mod.rs
+++ b/crates/openhuman-core/src/backend/transport/mod.rs
@@ -3,7 +3,7 @@
//!
//! The core owns the *routes* (`/payments/summary`,
//! `/agent-integrations/...`, `channels/{c}/messages`, ...) and the error
-//! *classification* ([`crate::api::rest`], `integrations/client/errors.rs`).
+//! *classification* ([`crate::backend::error`], `integrations/client/errors.rs`).
//! What it does not own is the HTTP primitive that carries a request with the
//! right credential header shape and route policy. That is a
//! [`BackendTransport`], and the only production implementation lives in the
diff --git a/crates/openhuman-core/src/backend/transport/plain.rs b/crates/openhuman-core/src/backend/transport/plain.rs
index fe339ae4ba..12470dcfe7 100644
--- a/crates/openhuman-core/src/backend/transport/plain.rs
+++ b/crates/openhuman-core/src/backend/transport/plain.rs
@@ -1,5 +1,5 @@
//! Test-only `reqwest` transport so the core's wiremock unit tests exercise
-//! [`BackendOAuthClient`](crate::api::rest::BackendOAuthClient) and
+//! [`BackendClient`](crate::backend::BackendClient) and
//! `IntegrationClient` without any host crate. Never compiled into a
//! production build: [`resolve_backend_transport`](super::resolve_backend_transport)
//! only reaches it under `cfg(test)`.
@@ -17,9 +17,23 @@ use serde_json::Value;
use super::{
compose_url, credential_headers, parse_body_text, unwrap_envelope, BackendRequest,
- BackendTransport, BackendTransportError, TransportProfile,
+ BackendTransport, BackendTransportError, BaseUrlPurpose, TransportProfile,
};
+/// Attribution header the test transport stamps, mirroring the host's.
+pub const TEST_PRODUCT_HEADER: &str = "x-sdk-name";
+/// Product identity the test transport reports and stamps.
+pub const TEST_PRODUCT_IDENTITY: &str = "openhuman";
+/// Base URL for a test that configured none: the discard port on loopback.
+pub const TEST_FALLBACK_BASE_URL: &str = "http://127.0.0.1:9";
+
+fn plain_client() -> reqwest::Client {
+ reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .build()
+ .expect("plain test client")
+}
+
pub struct PlainHttpTransport {
api: reqwest::Client,
integrations: reqwest::Client,
@@ -28,16 +42,12 @@ pub struct PlainHttpTransport {
impl PlainHttpTransport {
pub fn new() -> Self {
Self {
- api: crate::api::headers::build_backend_client(TransportProfile::Api)
- .expect("plain api client"),
- integrations: crate::api::headers::build_backend_client(TransportProfile::Integrations)
- .expect("plain integrations client"),
+ api: plain_client(),
+ integrations: plain_client(),
}
}
- /// A fresh instance. Deliberately *not* cached: tests change the product
- /// identity between calls and expect the next client to carry it, and
- /// building two `reqwest::Client`s is cheap.
+ /// A fresh instance (building two `reqwest::Client`s is cheap).
pub fn fresh() -> Arc<dyn BackendTransport> {
Arc::new(Self::new())
}
@@ -79,12 +89,10 @@ impl Default for PlainHttpTransport {
impl BackendTransport for PlainHttpTransport {
async fn send_json(&self, req: BackendRequest<'_>) -> Result<Value, BackendTransportError> {
let url = compose_url(req.base_url, req.path, req.query)?;
- // Product identity is stamped per request, as the SDK transport does,
- // so a change after this client was built still reaches the wire.
let mut request = self
.client(req.profile)
.request(req.method, url)
- .headers(crate::api::product::product_identity_headers())
+ .header(TEST_PRODUCT_HEADER, TEST_PRODUCT_IDENTITY)
.header(reqwest::header::ACCEPT, "application/json")
.header(CONTENT_TYPE, "application/json");
if let Some(credential) = req.credential {
@@ -105,7 +113,7 @@ impl BackendTransport for PlainHttpTransport {
let mut request = self
.client(req.profile)
.request(Method::POST, url)
- .headers(crate::api::product::product_identity_headers())
+ .header(TEST_PRODUCT_HEADER, TEST_PRODUCT_IDENTITY)
.header(reqwest::header::ACCEPT, "application/json");
if let Some(credential) = req.credential {
request = request.headers(credential_headers(credential)?);
@@ -117,6 +125,20 @@ impl BackendTransport for PlainHttpTransport {
self.client(profile).clone()
}
+ fn base_url(&self, configured: Option<&str>, _purpose: BaseUrlPurpose) -> String {
+ // No defaults here: a test that reaches the backend points
+ // `api_url` at its mock server. The fallback is a discard port so an
+ // unconfigured test can never reach a real host.
+ configured
+ .map(crate::util::url::normalize_backend_api_base_url)
+ .filter(|url| !url.is_empty())
+ .unwrap_or_else(|| TEST_FALLBACK_BASE_URL.to_string())
+ }
+
+ fn product_identity(&self) -> String {
+ TEST_PRODUCT_IDENTITY.to_string()
+ }
+
fn name(&self) -> &'static str {
"plain-test"
}
diff --git a/crates/openhuman-core/src/backend/transport/transport_tests.rs b/crates/openhuman-core/src/backend/transport/transport_tests.rs
index 085eb59c06..e7644fec66 100644
--- a/crates/openhuman-core/src/backend/transport/transport_tests.rs
+++ b/crates/openhuman-core/src/backend/transport/transport_tests.rs
@@ -168,17 +168,11 @@ fn error_status_accessor_only_reports_status_variant() {
#[tokio::test]
async fn plain_transport_sends_attribution_and_credential_headers() {
- let _identity = crate::api::product::product_identity_test_lock();
- crate::api::product::reset_product_identity_for_test();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/teams/me/usage"))
.and(header("authorization", "Bearer jwt.a.b"))
- .and(header(
- crate::api::product::PRODUCT_IDENTITY_HEADER,
- "openhuman",
- ))
- .and(header_exists("x-core-version"))
+ .and(header(plain::TEST_PRODUCT_HEADER, plain::TEST_PRODUCT_IDENTITY))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"success": true,
"data": {"remainingUsd": 4.5}
@@ -277,7 +271,7 @@ async fn backend_client_reports_unavailable_when_transport_returns_unavailable()
let _guard = global_lock().lock().unwrap();
install_backend_transport(Arc::new(Absent));
- let client = crate::api::BackendOAuthClient::new("https://api.example.test").unwrap();
+ let client = crate::backend::BackendClient::new("https://api.example.test").unwrap();
let err = client
.authed_json("jwt", reqwest::Method::GET, "/payments/summary", None)
.await
@@ -285,11 +279,11 @@ async fn backend_client_reports_unavailable_when_transport_returns_unavailable()
clear_backend_transport();
assert!(matches!(
- err.downcast_ref::<crate::api::BackendApiError>(),
- Some(crate::api::BackendApiError::BackendUnavailable { method, path })
+ err.downcast_ref::<crate::backend::BackendApiError>(),
+ Some(crate::backend::BackendApiError::BackendUnavailable { method, path })
if method == "GET" && path == "/payments/summary"
));
- let flat = crate::api::flatten_authed_error(err);
+ let flat = crate::backend::flatten_authed_error(err);
assert!(flat.starts_with(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX));
assert_eq!(
crate::core::observability::expected_error_kind(&flat),