systemprompt_api/services/gateway/protocol/outbound/
mod.rs1pub mod anthropic;
14pub mod gemini;
15pub mod openai_chat;
16pub mod openai_responses;
17pub mod retry;
18
19use std::sync::Arc;
20
21use anyhow::Result;
22use async_trait::async_trait;
23use futures_util::stream::BoxStream;
24use systemprompt_models::services::GatewayRoute;
25use systemprompt_models::services::ai::ModelLimits;
26use thiserror::Error;
27
28use super::canonical::CanonicalRequest;
29use super::canonical_response::{CanonicalEvent, CanonicalResponse};
30
31#[derive(Debug, Error)]
35pub enum UpstreamError {
36 #[error("{provider} returned {status}: {message}")]
37 Status {
38 provider: String,
39 status: u16,
40 message: String,
41 body: bytes::Bytes,
42 retry_after: Option<String>,
43 request_id: Option<String>,
44 },
45 #[error("{provider} request failed: {source}")]
46 Transport {
47 provider: String,
48 #[source]
49 source: reqwest::Error,
50 },
51}
52
53impl UpstreamError {
54 pub async fn from_response(provider: &str, response: reqwest::Response) -> Self {
55 let status = response.status().as_u16();
56 let header = |name: &str| {
57 response
58 .headers()
59 .get(name)
60 .and_then(|v| v.to_str().ok())
61 .map(ToOwned::to_owned)
62 };
63 let retry_after = header("retry-after");
64 let request_id = header("request-id").or_else(|| header("x-request-id"));
65 let body = response.bytes().await.unwrap_or_default();
66 Self::Status {
67 provider: provider.to_owned(),
68 status,
69 message: extract_upstream_message(&String::from_utf8_lossy(&body)),
70 body,
71 retry_after,
72 request_id,
73 }
74 }
75}
76
77pub(in crate::services::gateway) fn http_client() -> &'static reqwest::Client {
78 static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
79 CLIENT.get_or_init(reqwest::Client::new)
80}
81
82pub(in crate::services::gateway) async fn send_checked(
83 provider: &str,
84 req: reqwest::RequestBuilder,
85) -> Result<reqwest::Response> {
86 let policy = retry::current_policy();
87 let (response, _retries) = retry::send_with_retry(provider, req, &policy).await?;
88 Ok(response)
89}
90
91pub fn extract_upstream_message(body: &str) -> String {
92 serde_json::from_str::<serde_json::Value>(body)
93 .ok()
94 .and_then(|v| v["error"]["message"].as_str().map(ToOwned::to_owned))
95 .unwrap_or_else(|| body.chars().take(500).collect())
96}
97
98#[derive(Debug)]
99pub struct OutboundCtx<'a> {
100 pub route: &'a GatewayRoute,
101 pub endpoint: &'a str,
102 pub api_key: &'a str,
103 pub api_key_is_bearer: bool,
104 pub request: &'a CanonicalRequest,
105 pub upstream_model: &'a str,
106 pub model_limits: Option<ModelLimits>,
107 pub forward_headers: &'a [(String, String)],
108 pub raw_body: Option<&'a bytes::Bytes>,
109}
110
111#[expect(
112 missing_debug_implementations,
113 reason = "variants hold streaming bodies that intentionally do not implement Debug"
114)]
115pub enum OutboundOutcome {
116 Buffered(Box<CanonicalResponse>),
117 Streaming(BoxStream<'static, Result<CanonicalEvent, String>>),
118 RawBuffered {
119 body: bytes::Bytes,
120 content_type: Option<String>,
121 canonical: Box<CanonicalResponse>,
122 },
123 RawStreaming {
124 content_type: Option<String>,
125 stream: BoxStream<'static, Result<bytes::Bytes, String>>,
126 },
127}
128
129#[derive(Debug, Clone)]
134pub struct PreparedBody {
135 pub bytes: bytes::Bytes,
136 pub raw_lane: bool,
137}
138
139#[async_trait]
140pub trait OutboundAdapter: Send + Sync {
141 fn build_body(&self, ctx: &OutboundCtx<'_>) -> Result<PreparedBody>;
142
143 async fn send(&self, ctx: OutboundCtx<'_>, body: &PreparedBody) -> Result<OutboundOutcome>;
144}
145
146#[derive(Debug, Clone, Copy)]
147pub struct OutboundAdapterRegistration {
148 pub tag: &'static str,
149 pub factory: fn() -> Arc<dyn OutboundAdapter>,
150}
151
152inventory::collect!(OutboundAdapterRegistration);
153
154const DEFECTIVE_BODY_STATUS: u16 = 502;
155
156pub(in crate::services::gateway) fn reject_defective_body(
157 provider: &str,
158 wire: &str,
159 defect: &systemprompt_models::wire::defect::BodyDefect,
160 body: &bytes::Bytes,
161) -> anyhow::Error {
162 let excerpt: String = String::from_utf8_lossy(body).chars().take(512).collect();
163 tracing::warn!(
164 provider = %provider,
165 wire = %wire,
166 defect = %defect,
167 body = %excerpt,
168 "upstream returned a success status with a body carrying no turn"
169 );
170 anyhow::Error::new(UpstreamError::Status {
171 provider: provider.to_owned(),
172 status: DEFECTIVE_BODY_STATUS,
173 message: format!("{defect}: {excerpt}"),
174 body: body.clone(),
175 retry_after: None,
176 request_id: None,
177 })
178}
179
180pub(in crate::services::gateway) fn reject_unparsable_body(
181 provider: &str,
182 wire: &str,
183 error: &systemprompt_models::wire::error::WireParseError,
184 body: &bytes::Bytes,
185) -> anyhow::Error {
186 let excerpt: String = String::from_utf8_lossy(body).chars().take(512).collect();
187 tracing::error!(
188 provider = %provider,
189 wire = %wire,
190 error = %error,
191 body = %excerpt,
192 "upstream returned a success status with a body that does not parse"
193 );
194 anyhow::Error::new(UpstreamError::Status {
195 provider: provider.to_owned(),
196 status: DEFECTIVE_BODY_STATUS,
197 message: format!("{error}: {excerpt}"),
198 body: body.clone(),
199 retry_after: None,
200 request_id: None,
201 })
202}