use std::future::Future;
use std::marker::PhantomData;
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;
}
#[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,
}
#[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()?,
))
}
}
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}`")))?;
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 problem: crate::common::ProblemDetails = serde_json::from_slice(&response.body)
.map_err(|e| {
Error::Decode(format!(
"HTTP {} without a problem body: {e}",
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,
})
.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 want: Vec<&str> = pattern.split('/').collect();
let ok = 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 {pattern}, got {value:?}"
)))
}
}
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 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>(v: &i64, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(v)
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw {
S(String),
N(i64),
}
match Raw::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>(v: &Option<i64>, s: S) -> Result<S::Ok, S::Error> {
match v {
Some(v) => s.collect_str(v),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<i64>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw {
S(String),
N(i64),
}
match Option::<Raw>::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 effect: &'static str,
pub permission: &'static str,
}
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 = path_param(value, pattern, field)?;
let var = if *pattern == "*" {
format!("{{{field}}}")
} else {
format!("{{{field}={pattern}}}")
};
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",
})
}
}
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")]
#[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>,
max_retries: u32,
}
#[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>,
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 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")))
.build()
.map_err(|e| Error::Transport(e.to_string()))?,
};
Ok(HttpTransport {
http,
base_url: self
.base_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,
max_retries: self.max_retries.unwrap_or(3),
})
}
}
pub const DEFAULT_BASE_URL: &str = "https://api.sylphx.com";
#[cfg(feature = "http")]
impl HttpTransport {
pub fn builder() -> HttpTransportBuilder {
HttpTransportBuilder::default()
}
pub fn from_env() -> Result<Self, Error> {
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
}
async fn send_once(
&self,
request: &HttpRequest,
idempotency_key: Option<&str>,
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 mut rb = self
.http
.request(method, format!("{}{}", self.base_url, 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 {
rb = rb.header("Sylphx-Version", v);
}
if let Some(k) = idempotency_key {
rb = rb.header("Idempotency-Key", k);
}
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(),
));
}
rb = rb
.timeout(left)
.header("Sylphx-Request-Timeout", left.as_millis().to_string());
}
if let Some(body) = &request.body {
rb = rb.json(body);
}
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,
))
}
}
#[cfg(feature = "http")]
impl Transport for HttpTransport {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, Error> {
let key = request.mutation.then(|| uuid::Uuid::now_v7().to_string());
let deadline = self.timeout.map(|t| std::time::Instant::now() + t);
let mut attempt = 0u32;
loop {
let result = self.send_once(&request, key.as_deref(), deadline).await;
let retry_after = match &result {
Ok((r, after)) if retryable_status(r) => *after,
Err(Error::Transport(_)) => None,
_ => return result.map(|(r, _)| r),
};
if 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 retryable_status(r: &HttpResponse) -> bool {
match r.status {
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))
}