use futures_util::{Stream, StreamExt};
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
pub trait Transport: Send + Sync {
fn send(
&self,
request: HttpRequest,
) -> impl Future<Output = Result<HttpResponse, Error>> + Send;
}
pub type ResponseStream<T> = Pin<Box<dyn Stream<Item = Result<T, Error>> + Send>>;
pub trait StreamTransport: Transport {
fn stream(
&self,
request: HttpRequest,
) -> impl Future<Output = Result<ResponseStream<serde_json::Value>, Error>> + Send;
}
impl<T: StreamTransport> Client<T> {
pub async fn stream<R: DeserializeOwned + Send + 'static>(
&self,
request: HttpRequest,
) -> Result<ResponseStream<R>, Error> {
let stream = self.transport.stream(request).await?;
Ok(Box::pin(stream.map(|item| {
serde_json::from_value(item?).map_err(|e| Error::Decode(e.to_string()))
})))
}
pub async fn invoke_stream(
&self,
method_id: &str,
args: serde_json::Value,
) -> Result<ResponseStream<serde_json::Value>, Error> {
let spec = crate::methods::method(method_id)
.ok_or_else(|| Error::InvalidArgument(format!("unknown method `{method_id}`")))?;
self.stream(spec.request(args)?).await
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HttpRequest {
pub method: &'static str,
pub path: String,
pub query: Vec<(String, String)>,
pub body: Option<serde_json::Value>,
pub mutation: bool,
pub origin: Option<&'static str>,
pub effect_ids: bool,
}
#[derive(Debug, Clone)]
pub struct HttpResponse {
pub status: u16,
pub request_id: Option<String>,
pub body: Vec<u8>,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Api {
code: crate::common::ErrorCode,
status: u16,
retryable: bool,
effect: Option<crate::common::ErrorEffect>,
detail: String,
request_id: Option<String>,
problem: Box<crate::common::ProblemDetails>,
},
Transport(String),
Decode(String),
InvalidArgument(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Api {
code,
status,
detail,
..
} => write!(f, "{status} {}: {detail}", code.as_str()),
Error::Transport(e) => write!(f, "transport: {e}"),
Error::Decode(e) => write!(f, "decode: {e}"),
Error::InvalidArgument(e) => write!(f, "invalid argument: {e}"),
}
}
}
impl std::error::Error for Error {}
impl Error {
fn from_problem(
problem: crate::common::ProblemDetails,
status: u16,
request_id: Option<String>,
) -> Self {
Error::Api {
code: crate::common::ErrorCode::from_wire(&problem.code),
status: if problem.status > 0 {
problem.status as u16
} else {
status
},
retryable: problem.retryable,
effect: problem.effect.clone(),
detail: problem.detail.clone(),
request_id: request_id
.or_else(|| Some(problem.instance.clone()).filter(|s| !s.is_empty())),
problem: Box::new(problem),
}
}
}
#[cfg(feature = "http")]
pub struct Client<T = HttpTransport> {
transport: T,
}
#[cfg(not(feature = "http"))]
pub struct Client<T> {
transport: T,
}
#[cfg(feature = "http")]
impl Client<HttpTransport> {
pub fn from_env() -> Result<Self, Error> {
Ok(Self::new(HttpTransport::from_env()?))
}
pub fn with_api_key(api_key: impl Into<String>) -> Result<Self, Error> {
Ok(Self::new(
HttpTransport::builder().api_key(api_key).build()?,
))
}
pub fn with_deadline(&self, deadline: std::time::Instant) -> Self {
Self::new(self.transport.with_deadline(deadline))
}
}
impl<T: Transport> Client<T> {
pub fn new(transport: T) -> Self {
Self { transport }
}
pub async fn invoke(
&self,
method_id: &str,
args: serde_json::Value,
) -> Result<serde_json::Value, Error> {
let spec = crate::methods::method(method_id)
.ok_or_else(|| Error::InvalidArgument(format!("unknown method `{method_id}`")))?;
if spec.server_streaming {
return Err(Error::InvalidArgument(
"use invoke_stream for a server-streaming method".into(),
));
}
self.call(spec.request(args)?).await
}
pub fn transport(&self) -> &T {
&self.transport
}
pub async fn call<R: DeserializeOwned>(&self, request: HttpRequest) -> Result<R, Error> {
let response = self.transport.send(request).await?;
if response.status >= 400 {
let raw: serde_json::Value = serde_json::from_slice(&response.body).unwrap_or_default();
let problem = if raw.get("error").is_none()
&& (raw.get("code").is_some() || raw.get("title").is_some())
{
serde_json::from_value::<crate::common::ProblemDetails>(raw).map_err(|e| {
Error::Decode(format!(
"HTTP {} without a problem body: {e}",
response.status
))
})?
} else {
protocol_problem(&raw, response.status)
};
return Err(Error::from_problem(
problem,
response.status,
response.request_id,
));
}
let body: &[u8] = if response.body.is_empty() {
b"{}"
} else {
&response.body
};
serde_json::from_slice(body).map_err(|e| Error::Decode(e.to_string()))
}
}
pub struct Operation<'a, T, R> {
client: &'a Client<T>,
pub operation: crate::common::Operation,
response: PhantomData<R>,
}
impl<'a, T: Transport, R: DeserializeOwned> Operation<'a, T, R> {
pub fn new(client: &'a Client<T>, operation: crate::common::Operation) -> Self {
Self {
client,
operation,
response: PhantomData,
}
}
pub async fn wait(mut self) -> Result<R, Error> {
while !self.operation.done {
self.operation = self
.client
.call(HttpRequest {
method: "POST",
path: format!("/v1/{}:wait", self.operation.name),
query: vec![("timeout".into(), "60s".into())],
body: Some(serde_json::Value::Object(Default::default())),
mutation: false,
origin: None,
effect_ids: false,
})
.await?;
}
if let Some(problem) = self.operation.error.take() {
let status = problem.status.max(0) as u16;
return Err(Error::from_problem(problem, status, None));
}
let mut value = self
.operation
.response
.take()
.unwrap_or_else(|| serde_json::json!({}));
if let serde_json::Value::Object(map) = &mut value {
map.remove("@type");
}
serde_json::from_value(value).map_err(|e| Error::Decode(e.to_string()))
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Empty {}
pub fn path_param(value: &str, pattern: &str, field: &str) -> Result<String, Error> {
let got: Vec<&str> = value.split('/').collect();
let ok = pattern.split('|').any(|p| {
let want: Vec<&str> = p.split('/').collect();
got.len() == want.len()
&& got
.iter()
.zip(&want)
.all(|(g, w)| if *w == "*" { !g.is_empty() } else { g == w })
});
if ok {
Ok(value.to_string())
} else {
Err(Error::InvalidArgument(format!(
"`{field}` must match {}, got {value:?}",
pattern.replace('|', " or ")
)))
}
}
pub fn protocol_param(value: &str, many: bool, field: &str) -> Result<String, Error> {
let segments: Vec<&str> = value.split('/').collect();
if segments.iter().any(|s| s.is_empty()) || (!many && segments.len() > 1) {
let want = if many {
"non-empty `/`-separated segments"
} else {
"one non-empty segment"
};
return Err(Error::InvalidArgument(format!(
"`{field}` must be {want}, got {value:?}"
)));
}
Ok(segments
.iter()
.map(|s| {
s.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
(b as char).to_string()
}
_ => format!("%{b:02X}"),
})
.collect::<String>()
})
.collect::<Vec<_>>()
.join("/"))
}
fn protocol_problem(raw: &serde_json::Value, status: u16) -> crate::common::ProblemDetails {
let text =
|v: Option<&serde_json::Value>| v.and_then(|v| v.as_str()).unwrap_or_default().to_string();
let (own, message) = match raw.get("error") {
Some(e) if e.is_object() => {
let mut message = text(e.get("message"));
if message.is_empty() {
message = text(e.get("status").and_then(|s| s.get("message")));
}
(text(e.get("code")), message)
}
e => (text(raw.get("code")), text(e)),
};
let code = match status {
400 => "INVALID_FIELD",
401 => "UNAUTHENTICATED",
403 => "PERMISSION_DENIED",
404 => "RESOURCE_NOT_FOUND",
409 | 412 => "ETAG_MISMATCH",
429 => "RATE_LIMITED",
503 => "UNAVAILABLE",
_ => "INTERNAL",
};
let detail = match (own.is_empty(), message.is_empty()) {
(false, false) => format!("{own}: {message}"),
(false, true) => own,
(true, _) => message,
};
serde_json::from_value(serde_json::json!({
"code": code,
"title": if detail.is_empty() { code.to_string() } else { detail.clone() },
"detail": detail,
"status": status,
"retryable": matches!(status, 429 | 502 | 503 | 504),
}))
.unwrap_or_default()
}
pub fn body<B: Serialize>(value: &B) -> Result<serde_json::Value, Error> {
match serde_json::to_value(value).map_err(|e| Error::InvalidArgument(e.to_string()))? {
serde_json::Value::Null => Ok(serde_json::Value::Object(Default::default())),
v => Ok(v),
}
}
pub fn body_without<B: Serialize>(
value: &B,
path_fields: &[&str],
) -> Result<serde_json::Value, Error> {
let mut v = body(value)?;
if let serde_json::Value::Object(map) = &mut v {
for f in path_fields {
map.remove(*f);
}
}
Ok(v)
}
#[derive(Debug, Default)]
pub struct Query(pub Vec<(String, String)>);
impl Query {
pub fn push<V: QueryValue + ?Sized>(&mut self, key: &str, value: &V) {
if let Some(v) = value.query_value() {
self.0.push((key.to_string(), v));
}
}
}
pub trait QueryValue {
fn query_value(&self) -> Option<String>;
}
impl QueryValue for String {
fn query_value(&self) -> Option<String> {
(!self.is_empty()).then(|| self.clone())
}
}
impl QueryValue for bool {
fn query_value(&self) -> Option<String> {
self.then(|| "true".to_string())
}
}
impl QueryValue for i32 {
fn query_value(&self) -> Option<String> {
(*self != 0).then(|| self.to_string())
}
}
impl QueryValue for u32 {
fn query_value(&self) -> Option<String> {
(*self != 0).then(|| self.to_string())
}
}
impl QueryValue for u64 {
fn query_value(&self) -> Option<String> {
(*self != 0).then(|| self.to_string())
}
}
impl QueryValue for i64 {
fn query_value(&self) -> Option<String> {
(*self != 0).then(|| self.to_string())
}
}
impl<V: QueryValue> QueryValue for Option<V> {
fn query_value(&self) -> Option<String> {
self.as_ref().and_then(QueryValue::query_value)
}
}
pub fn is_default<V: Default + PartialEq>(v: &V) -> bool {
*v == V::default()
}
pub mod int64 {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer, T: std::fmt::Display>(v: &T, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(v)
}
pub fn deserialize<'de, D, T>(d: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: std::str::FromStr + Deserialize<'de>,
T::Err: std::fmt::Display,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw<T> {
S(String),
N(T),
}
match Raw::<T>::deserialize(d)? {
Raw::S(s) => s.parse().map_err(serde::de::Error::custom),
Raw::N(n) => Ok(n),
}
}
}
pub mod opt_int64 {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer, T: std::fmt::Display>(
v: &Option<T>,
s: S,
) -> Result<S::Ok, S::Error> {
match v {
Some(v) => s.collect_str(v),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: std::str::FromStr + Deserialize<'de>,
T::Err: std::fmt::Display,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw<T> {
S(String),
N(T),
}
match Option::<Raw<T>>::deserialize(d)? {
Some(Raw::S(s)) => s.parse().map(Some).map_err(serde::de::Error::custom),
Some(Raw::N(n)) => Ok(Some(n)),
None => Ok(None),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MethodSpec {
pub id: &'static str,
pub http_method: &'static str,
pub template: &'static str,
pub path_params: &'static [(&'static str, &'static str)],
pub query_params: &'static [&'static str],
pub body: Option<&'static str>,
pub long_running: bool,
pub server_streaming: bool,
pub effect: &'static str,
pub permission: &'static str,
pub origin: Option<&'static str>,
pub effect_ids: bool,
}
impl MethodSpec {
pub fn request(&self, args: serde_json::Value) -> Result<HttpRequest, Error> {
let serde_json::Value::Object(args) = args else {
return Err(Error::InvalidArgument(format!(
"{}: arguments must be a JSON object",
self.id
)));
};
let mut path = self.template.to_string();
for (field, pattern) in self.path_params {
let value = lookup(&args, field)
.and_then(|v| v.as_str())
.unwrap_or_default();
let value = match self.origin {
Some(_) => protocol_param(value, *pattern == "**", field)?,
None => path_param(value, pattern, field)?,
};
let primary = pattern.split('|').next().unwrap_or_default();
let var = if primary == "*" {
format!("{{{field}}}")
} else {
format!("{{{field}={primary}}}")
};
path = path.replace(&var, &value);
}
let mut query = Vec::new();
for q in self.query_params {
match args.get(*q) {
None | Some(serde_json::Value::Null) => {}
Some(serde_json::Value::String(s)) if s.is_empty() => {}
Some(serde_json::Value::Bool(false)) => {}
Some(serde_json::Value::String(s)) => query.push((q.to_string(), s.clone())),
Some(serde_json::Value::Number(n)) if n.as_f64() != Some(0.0) => {
query.push((q.to_string(), n.to_string()))
}
Some(serde_json::Value::Number(_)) => {}
Some(serde_json::Value::Bool(true)) => query.push((q.to_string(), "true".into())),
Some(other) => {
return Err(Error::InvalidArgument(format!(
"{}: query parameter `{q}` must be a scalar, got {other}",
self.id
)))
}
}
}
let body = match self.body {
None => None,
Some("*") => {
let mut map = args.clone();
for (field, _) in self.path_params {
map.remove(field.split('.').next().unwrap_or_default());
}
Some(serde_json::Value::Object(map))
}
Some(field) => Some(
args.get(field)
.cloned()
.unwrap_or_else(|| serde_json::json!({})),
),
};
Ok(HttpRequest {
method: self.http_method,
path,
query,
body,
mutation: self.http_method != "GET",
origin: self.origin,
effect_ids: self.effect_ids,
})
}
}
fn lookup<'v>(
args: &'v serde_json::Map<String, serde_json::Value>,
path: &str,
) -> Option<&'v serde_json::Value> {
let mut parts = path.split('.');
let mut cur = args.get(parts.next()?)?;
for p in parts {
cur = cur.get(p)?;
}
Some(cur)
}
#[cfg(feature = "http")]
const DEFAULT_SOCKET_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
#[cfg(feature = "http")]
#[derive(Debug, Clone)]
pub struct HttpTransport {
http: reqwest::Client,
base_url: String,
api_key: Option<String>,
api_version: Option<String>,
timeout: Option<std::time::Duration>,
deadline: Option<std::time::Instant>,
max_retries: u32,
origins: std::collections::BTreeMap<String, String>,
}
#[cfg(feature = "http")]
#[derive(Debug, Clone, Default)]
pub struct HttpTransportBuilder {
base_url: Option<String>,
api_key: Option<String>,
api_version: Option<String>,
timeout: Option<std::time::Duration>,
max_retries: Option<u32>,
origins: std::collections::BTreeMap<String, String>,
http: Option<reqwest::Client>,
}
#[cfg(feature = "http")]
impl HttpTransportBuilder {
pub fn base_url(mut self, url: impl Into<String>) -> Self {
self.base_url = Some(url.into());
self
}
pub fn origin(mut self, default: impl Into<String>, replacement: impl Into<String>) -> Self {
self.origins.insert(default.into(), replacement.into());
self
}
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub fn api_version(mut self, date: impl Into<String>) -> Self {
self.api_version = Some(date.into());
self
}
pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn max_retries(mut self, n: u32) -> Self {
self.max_retries = Some(n);
self
}
pub fn http_client(mut self, client: reqwest::Client) -> Self {
self.http = Some(client);
self
}
pub fn build(self) -> Result<HttpTransport, Error> {
let http = match self.http {
Some(c) => c,
None => reqwest::Client::builder()
.user_agent(concat!("sylphx-rust/", env!("CARGO_PKG_VERSION")))
.connect_timeout(std::time::Duration::from_secs(5))
.timeout(DEFAULT_SOCKET_TIMEOUT)
.build()
.map_err(|e| Error::Transport(e.to_string()))?,
};
Ok(HttpTransport {
http,
base_url: self
.base_url
.filter(|url| !retired_base_url(url))
.unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
.trim_end_matches('/')
.to_string(),
api_key: self.api_key,
api_version: self.api_version,
timeout: self.timeout,
deadline: None,
max_retries: self.max_retries.unwrap_or(3),
origins: self.origins,
})
}
}
pub const DEFAULT_BASE_URL: &str = "https://api.sylphx.com";
pub fn retired_base_url(url: &str) -> bool {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let host = authority
.rsplit('@')
.next()
.unwrap_or_default()
.split(':')
.next()
.unwrap_or_default()
.to_ascii_lowercase();
let retired = host.ends_with(".api.sylphx.com");
if retired {
eprintln!(
"sylphx: ignoring the retired host {host} (per-project hosts are gone); \
calls go to https://api.sylphx.com with SYLPHX_API_KEY"
);
}
retired
}
#[cfg(feature = "http")]
impl HttpTransport {
pub fn builder() -> HttpTransportBuilder {
HttpTransportBuilder::default()
}
pub fn from_env() -> Result<Self, Error> {
for retired in ["SYLPHX_URL", "SYLPHX_SECRET_URL"] {
if std::env::var(retired).is_ok_and(|v| !v.is_empty()) {
eprintln!(
"sylphx: {retired} is retired and ignored; the SDK uses SYLPHX_API_KEY \
and https://api.sylphx.com (and each service's own host)"
);
}
}
let key = std::env::var("SYLPHX_API_KEY")
.ok()
.filter(|k| !k.is_empty())
.ok_or_else(|| Error::InvalidArgument("SYLPHX_API_KEY is not set".into()))?;
let mut b = Self::builder().api_key(key);
if let Some(url) = std::env::var("SYLPHX_BASE_URL")
.ok()
.filter(|u| !u.is_empty())
{
b = b.base_url(url);
}
if let Some(v) = std::env::var("SYLPHX_API_VERSION")
.ok()
.filter(|v| !v.is_empty())
{
b = b.api_version(v);
}
b.build()
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn with_deadline(&self, deadline: std::time::Instant) -> Self {
let mut t = self.clone();
t.deadline = Some(deadline);
t
}
async fn send_once(
&self,
request: &HttpRequest,
effect_id: Option<&str>,
extra: &[(String, String)],
deadline: Option<std::time::Instant>,
) -> Result<(HttpResponse, Option<std::time::Duration>), Error> {
let method = reqwest::Method::from_bytes(request.method.as_bytes())
.map_err(|e| Error::InvalidArgument(e.to_string()))?;
let base = match request.origin {
Some(origin) => self
.origins
.get(origin)
.map(String::as_str)
.unwrap_or(origin)
.trim_end_matches('/'),
None => self.base_url.as_str(),
};
let protocol = request.origin.is_some();
let mut rb = self
.http
.request(method, format!("{base}{}", request.path))
.header(reqwest::header::ACCEPT, "application/json");
if !request.query.is_empty() {
rb = rb.query(&request.query);
}
if let Some(key) = &self.api_key {
rb = rb.bearer_auth(key);
}
if let Some(v) = self.api_version.as_ref().filter(|_| !protocol) {
rb = rb.header("Sylphx-Version", v);
}
if let Some(k) = effect_id {
if !protocol {
rb = rb.header("Idempotency-Key", k);
}
rb = rb.header("Sylphx-Effect-Id", k);
}
for (k, v) in extra
.iter()
.filter(|(k, _)| !k.eq_ignore_ascii_case("idempotency-key"))
{
rb = rb.header(k.as_str(), v.as_str());
}
if let Some(deadline) = deadline {
let left = deadline.saturating_duration_since(std::time::Instant::now());
if left.is_zero() {
return Err(Error::Transport(
"deadline exceeded before the request was sent".into(),
));
}
if !protocol && (self.timeout.is_some() || self.deadline.is_some()) {
rb = rb.header("Sylphx-Request-Timeout", left.as_millis().to_string());
}
}
if let Some(body) = &request.body {
rb = rb.json(body);
}
let exchange = async {
let response = rb
.send()
.await
.map_err(|e| Error::Transport(e.to_string()))?;
let status = response.status().as_u16();
let header = |name: &str| {
response
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
};
let request_id = header("sylphx-request-id");
let retry_after = header("retry-after")
.and_then(|v| v.trim().parse::<u64>().ok())
.map(std::time::Duration::from_secs);
let body = response
.bytes()
.await
.map_err(|e| Error::Transport(e.to_string()))?
.to_vec();
Ok((
HttpResponse {
status,
request_id,
body,
},
retry_after,
))
};
match deadline {
Some(deadline) => tokio::time::timeout_at(deadline.into(), exchange)
.await
.map_err(|_| Error::Transport("request deadline exceeded".into()))?,
None => exchange.await,
}
}
}
#[cfg(feature = "http")]
impl Transport for HttpTransport {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, Error> {
self.send_with_headers(request, &[]).await
}
}
#[cfg(feature = "http")]
impl HttpTransport {
pub async fn send_with_headers(
&self,
request: HttpRequest,
headers: &[(String, String)],
) -> Result<HttpResponse, Error> {
let key = headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("idempotency-key"))
.map(|(_, v)| v.clone())
.or_else(|| {
(request.effect_ids || request.mutation).then(|| uuid::Uuid::now_v7().to_string())
});
let resend = !(request.mutation && request.origin.is_some() && !request.effect_ids);
let deadline = match (self.deadline, self.timeout) {
(Some(d), Some(t)) => Some(d.min(std::time::Instant::now() + t)),
(Some(d), None) => Some(d),
(None, Some(t)) => Some(std::time::Instant::now() + t),
(None, None) => None,
};
let mut attempt = 0u32;
loop {
let result = self
.send_once(&request, key.as_deref(), headers, deadline)
.await;
if resend {
if let Ok((response, after)) = &result {
if in_progress(response) {
let wait = after.unwrap_or(std::time::Duration::from_secs(1));
if deadline.is_some_and(|d| std::time::Instant::now() + wait >= d) {
return result.map(|(r, _)| r);
}
tokio::time::sleep(wait).await;
continue;
}
}
}
let propagation_rejection = result
.as_ref()
.is_ok_and(|(response, _)| key_not_yet_propagated(response));
let retry_after = match &result {
Ok((r, after)) if retryable_status(r) => *after,
Err(Error::Transport(_)) => None,
_ => return result.map(|(r, _)| r),
};
if (!resend && !propagation_rejection) || attempt >= self.max_retries {
return result.map(|(r, _)| r);
}
let wait = retry_after.unwrap_or_else(|| backoff(attempt));
if deadline.is_some_and(|d| std::time::Instant::now() + wait >= d) {
return result.map(|(r, _)| r);
}
tokio::time::sleep(wait).await;
attempt += 1;
}
}
}
#[cfg(feature = "http")]
fn in_progress(response: &HttpResponse) -> bool {
response.status == 409
&& serde_json::from_slice::<serde_json::Value>(&response.body)
.is_ok_and(|v| v["code"] == "IDEMPOTENCY_IN_PROGRESS" && v["retryable"] == true)
}
#[cfg(feature = "http")]
fn key_not_yet_propagated(response: &HttpResponse) -> bool {
if response.status != 401 {
return false;
}
let Ok(raw) = serde_json::from_slice::<serde_json::Value>(&response.body) else {
return false;
};
if raw.get("effect").is_some_and(|effect| effect != "none") {
return false;
}
let error = raw.get("error").filter(|error| error.is_object());
if error.is_some_and(|error| error.get("effect").is_some_and(|effect| effect != "none")) {
return false;
}
let code = error.unwrap_or(&raw).get("code").and_then(|v| v.as_str());
matches!(code, Some("NOT_YET_PROPAGATED" | "key_not_yet_propagated"))
|| (error.is_none()
&& code == Some("UNAUTHENTICATED")
&& raw["detail"] == "The key was refused (key_not_yet_propagated).")
}
#[cfg(feature = "http")]
fn retryable_status(r: &HttpResponse) -> bool {
match r.status {
401 => key_not_yet_propagated(r),
429 | 502 | 503 | 504 => true,
s if s >= 400 => serde_json::from_slice::<serde_json::Value>(&r.body)
.ok()
.and_then(|v| v.get("retryable").and_then(|b| b.as_bool()))
.unwrap_or(false),
_ => false,
}
}
#[cfg(feature = "http")]
fn backoff(attempt: u32) -> std::time::Duration {
let cap = 250u64.saturating_mul(1 << attempt.min(5)).min(8_000);
std::time::Duration::from_millis(fastrand::u64(0..=cap))
}
#[cfg(feature = "http")]
impl StreamTransport for HttpTransport {
async fn stream(
&self,
request: HttpRequest,
) -> Result<ResponseStream<serde_json::Value>, Error> {
let base = request
.origin
.map(|origin| {
self.origins
.get(origin)
.map(String::as_str)
.unwrap_or(origin)
})
.unwrap_or(&self.base_url);
let method = reqwest::Method::from_bytes(request.method.as_bytes())
.map_err(|e| Error::InvalidArgument(e.to_string()))?;
let mut rb = self
.http
.request(method, format!("{base}{}", request.path))
.query(&request.query)
.header("accept", "text/event-stream");
if let Some(key) = &self.api_key {
rb = rb.bearer_auth(key);
}
if let Some(version) = &self.api_version {
rb = rb.header("sylphx-version", version);
}
let response = rb
.send()
.await
.map_err(|e| Error::Transport(e.to_string()))?;
if !response.status().is_success() {
let status = response.status().as_u16();
let problem = response
.json()
.await
.map_err(|e| Error::Decode(e.to_string()))?;
return Err(Error::from_problem(problem, status, None));
}
let chunks = Box::pin(response.bytes_stream());
Ok(Box::pin(futures_util::stream::try_unfold(
(chunks, Vec::new()),
|(mut chunks, mut buffer)| async move {
loop {
if let Some(end) = buffer.windows(2).position(|w| w == b"\n\n") {
let frame = buffer.drain(..end + 2).collect::<Vec<_>>();
let text = std::str::from_utf8(&frame)
.map_err(|e| Error::Decode(e.to_string()))?;
let data = text
.lines()
.filter_map(|line| {
line.strip_prefix("data:")
.map(|s| s.strip_prefix(' ').unwrap_or(s))
})
.collect::<Vec<_>>()
.join("\n");
if !data.is_empty() {
let value = serde_json::from_str(&data)
.map_err(|e| Error::Decode(e.to_string()))?;
return Ok(Some((value, (chunks, buffer))));
}
continue;
}
match chunks.next().await {
Some(Ok(chunk)) => buffer.extend_from_slice(&chunk),
Some(Err(error)) => return Err(Error::Transport(error.to_string())),
None => return Ok(None),
}
}
},
)))
}
}
#[cfg(test)]
mod tests {
use super::protocol_problem;
#[test]
fn protocol_problem_keeps_the_reason_from_status_message() {
let raw = serde_json::json!({
"ok": false,
"error": {
"status": {"code": 6, "message": "commit_not_fully_built", "details": []},
"code": "redeploy_refused"
},
"process": "sylphx-apps-api",
"owner": "sylphx-apps-api/product"
});
let problem = protocol_problem(&raw, 409);
assert_eq!(problem.code, "ETAG_MISMATCH");
assert_eq!(problem.detail, "redeploy_refused: commit_not_fully_built");
}
#[test]
fn protocol_problem_prefers_the_direct_error_message() {
let raw = serde_json::json!({
"error": {
"code": "workspace_not_found",
"message": "no such workspace",
"status": {"message": "must not win"}
}
});
let problem = protocol_problem(&raw, 404);
assert_eq!(problem.detail, "workspace_not_found: no such workspace");
}
#[test]
fn protocol_problem_without_a_message_stays_the_code() {
let raw = serde_json::json!({"error": {"code": "redeploy_refused"}});
let problem = protocol_problem(&raw, 409);
assert_eq!(problem.detail, "redeploy_refused");
}
}