#![allow(dead_code)]
use std::{
borrow::Cow,
fmt,
hash::{BuildHasher as _, Hasher as _},
sync::Arc,
time::{Duration, SystemTime},
};
use bytes::Bytes;
use http::{
header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, RETRY_AFTER, USER_AGENT},
HeaderMap, HeaderName, HeaderValue, Method, StatusCode,
};
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS, NON_ALPHANUMERIC};
use serde::de::DeserializeOwned;
use crate::api::{
auth_schemes::{base64, OAuthUse, Security, SyncFuture},
middleware::{BoxError, Next, Request as MiddlewareRequest, Response},
upload::{Multipart, RequestBody},
Call, EventStream, RequestOptions, SseEvent, Upload,
};
use crate::{error::Error, Configuration};
const IDEMPOTENCY_KEY: &str = "idempotency-key";
const AUTO_IDEMPOTENCY_KEY: bool = false;
const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);
#[derive(Debug)]
#[non_exhaustive]
pub(crate) enum Failure {
Request(BoxError),
Timeout,
Transport(BoxError),
Decode(BoxError),
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Request(error) => write!(f, "invalid request: {error}"),
Self::Timeout => f.write_str("request timed out"),
Self::Transport(error) => write!(f, "transport error: {error}"),
Self::Decode(error) => write!(f, "unexpected response body: {error}"),
}
}
}
impl std::error::Error for Failure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Request(error) | Self::Transport(error) | Self::Decode(error) => Some(&**error),
Self::Timeout => None,
}
}
}
pub(crate) fn request_error(error: impl Into<BoxError>) -> Error {
Error::generic(Failure::Request(error.into()))
}
pub(crate) fn transport_error(error: impl Into<BoxError>) -> Error {
Error::generic(Failure::Transport(error.into()))
}
pub(crate) fn decode_error(error: impl Into<BoxError>) -> Error {
Error::generic(Failure::Decode(error.into()))
}
pub(crate) enum ResponseBody {
Buffered(Bytes),
Events(Option<hyper::body::Incoming>, Bytes),
}
impl ResponseBody {
fn bytes(self) -> Result<Bytes, Error> {
match self {
Self::Buffered(bytes) => Ok(bytes),
Self::Events(..) => Err(decode_error("expected a buffered body")),
}
}
}
pub(crate) struct Received {
pub(crate) status: StatusCode,
pub(crate) headers: HeaderMap,
pub(crate) body: ResponseBody,
}
fn json<T: DeserializeOwned>(body: ResponseBody) -> Result<T, Error> {
serde_json::from_slice(&body.bytes()?).map_err(decode_error)
}
fn json_or_none<T: DeserializeOwned>(body: ResponseBody) -> Result<Option<T>, Error> {
let bytes = body.bytes()?;
if bytes.trim_ascii().is_empty() {
return Ok(None);
}
serde_json::from_slice::<Option<T>>(&bytes).map_err(decode_error)
}
fn empty(body: ResponseBody) -> Result<(), Error> {
body.bytes().map(drop)
}
fn text(body: ResponseBody) -> Result<String, Error> {
String::from_utf8(body.bytes()?.into()).map_err(decode_error)
}
fn events(body: ResponseBody) -> Result<EventStream, Error> {
match body {
ResponseBody::Events(body, buffered) => Ok(EventStream::new(body, buffered)),
ResponseBody::Buffered(_) => Err(decode_error("expected an event stream")),
}
}
fn typed_events<E: DeserializeOwned>(body: ResponseBody) -> Result<EventStream<E>, Error> {
events(body).map(EventStream::typed)
}
enum Attempt {
Done(StatusCode, HeaderMap, ResponseBody),
Status(StatusCode, HeaderMap, Bytes),
Failed(Failure),
}
impl Attempt {
fn retryable(&self) -> bool {
match self {
Self::Done(..) | Self::Failed(Failure::Request(_) | Failure::Decode(_)) => false,
Self::Failed(Failure::Timeout | Failure::Transport(_)) => true,
Self::Status(status, ..) => {
matches!(status.as_u16(), 408 | 429) || status.is_server_error()
}
}
}
fn retry_after(&self) -> Option<Duration> {
let Self::Status(_, headers, _) = self else {
return None;
};
let header = |name: &str| headers.get(name)?.to_str().ok();
let delay = if let Some(ms) = header("retry-after-ms") {
Duration::try_from_secs_f64(ms.trim().parse::<f64>().ok()? / 1000.0).ok()?
} else {
let value = header(RETRY_AFTER.as_str())?.trim();
match value.parse::<u64>() {
Ok(seconds) => Duration::from_secs(seconds),
Err(_) => httpdate(value)?.duration_since(SystemTime::now()).ok()?,
}
};
(delay <= MAX_RETRY_AFTER).then_some(delay)
}
fn into_error(self) -> Error {
match self {
Self::Done(..) => unreachable!("a successful attempt is not an error"),
Self::Status(status, headers, body) => Error::from_response(status, headers, body),
Self::Failed(failure) => Error::generic(failure),
}
}
}
pub(crate) struct Request {
method: Method,
path: Cow<'static, str>,
query_params: Vec<(String, String)>,
path_params: Vec<(&'static str, String)>,
encoded_path_params: Vec<(&'static str, String)>,
headers: HeaderMap,
cookies: Vec<(String, String)>,
serialized_body: Option<Bytes>,
body_is_form: bool,
upload: Option<Upload>,
upload_content_type: &'static str,
multipart: Option<Multipart>,
error: Option<Error>,
security: Option<Security>,
overrides: HeaderMap,
#[allow(clippy::option_option)]
timeout: Option<Option<Duration>>,
max_retries: Option<u32>,
retry_safe: bool,
}
impl Request {
pub fn new(method: Method, path: &'static str) -> Self {
Request {
method,
path: Cow::Borrowed(path),
query_params: Vec::new(),
path_params: Vec::new(),
encoded_path_params: Vec::new(),
headers: HeaderMap::new(),
cookies: Vec::new(),
serialized_body: None,
body_is_form: false,
upload: None,
upload_content_type: "application/octet-stream",
multipart: None,
error: None,
security: None,
overrides: HeaderMap::new(),
timeout: None,
max_retries: None,
retry_safe: false,
}
}
pub fn with_options(mut self, options: &RequestOptions) -> Self {
for (name, value) in &options.headers {
match header(name, value) {
Ok((name, value)) => {
self.overrides.append(name, value);
}
Err(error) => self.fail(error),
}
}
if let Some(key) = &options.idempotency_key {
match header(IDEMPOTENCY_KEY, key) {
Ok((name, value)) => {
self.headers.insert(name, value);
}
Err(error) => self.fail(error),
}
}
self.timeout = options.timeout.or(self.timeout);
self.max_retries = options.max_retries.or(self.max_retries);
self
}
fn fail(&mut self, error: impl Into<BoxError>) {
self.error.get_or_insert_with(|| request_error(error));
}
pub fn with_body_param<T: serde::Serialize>(mut self, param: T) -> Self {
match serde_json::to_vec(¶m) {
Ok(body) => self.serialized_body = Some(body.into()),
Err(error) => self.fail(error),
}
self
}
pub fn with_optional_body_param<T: serde::Serialize>(self, param: Option<T>) -> Self {
match param {
Some(body) => self.with_body_param(body),
None => self,
}
}
pub fn with_body_property(mut self, name: &str, value: impl Into<serde_json::Value>) -> Self {
let body = self.serialized_body.as_deref().unwrap_or(b"{}");
match serde_json::from_slice::<serde_json::Value>(body) {
Ok(serde_json::Value::Object(mut object)) => {
object.insert(name.to_owned(), value.into());
self.with_body_param(object)
}
Ok(_) => {
self.fail("the body is not a JSON object");
self
}
Err(error) => {
self.fail(error);
self
}
}
}
pub fn with_form_body_param<T: serde::Serialize>(
mut self,
param: T,
deep_object: &[&str],
unexploded: &[&str],
) -> Self {
match serde_json::to_value(¶m) {
Ok(serde_json::Value::Object(fields)) => {
let mut pairs = Vec::new();
for (name, value) in &fields {
let deep = deep_object.contains(&name.as_str());
let explode = !unexploded.contains(&name.as_str());
encode_param(name, value, deep, explode, &mut pairs);
}
let mut form = url::form_urlencoded::Serializer::new(String::new());
form.extend_pairs(pairs);
self.serialized_body = Some(form.finish().into());
}
Ok(serde_json::Value::Null) => return self,
Ok(_) => self.fail("a form body must be an object"),
Err(error) => self.fail(error),
}
self.body_is_form = true;
self
}
pub fn with_upload_body(mut self, body: Option<Upload>, content_type: &'static str) -> Self {
self.upload = body;
self.upload_content_type = content_type;
self
}
pub fn with_multipart_body(mut self, body: Result<Option<Multipart>, Error>) -> Self {
match body {
Ok(body) => self.multipart = body,
Err(error) => {
self.error.get_or_insert(error);
}
}
self
}
fn with_authorization(mut self, value: String) -> Self {
match HeaderValue::try_from(value) {
Ok(mut value) => {
value.set_sensitive(true);
self.headers.insert(AUTHORIZATION, value);
}
Err(error) => self.fail(error),
}
self
}
pub fn with_security(mut self, security: Security) -> Self {
self.security = Some(security);
self
}
pub fn with_header_param(mut self, name: &'static str, value: &impl QueryParamValue) -> Self {
match header(name, &value.encode()) {
Ok((name, value)) => {
self.headers.insert(name, value);
}
Err(error) => self.fail(error),
}
self
}
pub fn with_json_header_param<T: serde::Serialize>(
mut self,
name: &'static str,
value: Option<T>,
) -> Self {
match value.map(|value| serde_json::to_string(&value)).transpose() {
Ok(Some(json)) => return self.with_header_param(name, &json),
Ok(None) => {}
Err(error) => self.fail(error),
}
self
}
pub fn with_optional_header_param(
self,
name: &'static str,
value: Option<impl QueryParamValue>,
) -> Self {
match value {
Some(value) => self.with_header_param(name, &value),
None => self,
}
}
pub fn with_cookie_param(mut self, name: &'static str, value: &impl QueryParamValue) -> Self {
self.cookies.push((name.to_owned(), value.encode()));
self
}
pub fn with_optional_cookie_param(
self,
name: &'static str,
value: Option<impl QueryParamValue>,
) -> Self {
match value {
Some(value) => self.with_cookie_param(name, &value),
None => self,
}
}
pub fn with_query_param(mut self, name: &'static str, param: &impl QueryParamValue) -> Self {
self.query_params.push((name.to_owned(), param.encode()));
self
}
pub fn with_structured_query_param<T: serde::Serialize>(
mut self,
name: &'static str,
param: Option<T>,
deep_object: bool,
explode: bool,
) -> Self {
match param.map(serde_json::to_value).transpose() {
Ok(Some(value)) => {
encode_param(name, &value, deep_object, explode, &mut self.query_params);
}
Ok(None) => {}
Err(error) => self.fail(error),
}
self
}
pub fn with_delimited_query_param<T: serde::Serialize>(
mut self,
name: &'static str,
param: Option<T>,
delimiter: &str,
) -> Self {
match param.map(serde_json::to_value).transpose() {
Ok(Some(serde_json::Value::Array(items))) => {
let joined = items
.iter()
.filter_map(scalar_text)
.collect::<Vec<_>>()
.join(delimiter);
if !joined.is_empty() {
self.query_params.push((name.to_owned(), joined));
}
}
Ok(_) => {}
Err(error) => self.fail(error),
}
self
}
pub fn with_json_query_param<T: serde::Serialize>(
mut self,
name: &'static str,
param: Option<T>,
) -> Self {
match param.map(|param| serde_json::to_string(¶m)).transpose() {
Ok(Some(json)) => self.query_params.push((name.to_owned(), json)),
Ok(None) => {}
Err(error) => self.fail(error),
}
self
}
pub fn with_optional_query_param(
self,
name: &'static str,
param: Option<impl QueryParamValue>,
) -> Self {
match param {
Some(value) => self.with_query_param(name, &value),
None => self,
}
}
pub fn with_exploded_query_param<T: QueryParamValue>(
mut self,
name: &'static str,
values: Vec<T>,
) -> Self {
for value in values {
self.query_params.push((name.to_owned(), value.encode()));
}
self
}
pub fn with_optional_exploded_query_param<T: QueryParamValue>(
self,
name: &'static str,
values: Option<Vec<T>>,
) -> Self {
match values {
Some(values) => self.with_exploded_query_param(name, values),
None => self,
}
}
pub fn with_path_param(mut self, name: &'static str, value: impl fmt::Display) -> Self {
self.path_params.push((name, value.to_string()));
self
}
pub fn with_styled_path_param<T: serde::Serialize>(
mut self,
name: &'static str,
value: T,
style: &str,
explode: bool,
) -> Self {
match serde_json::to_value(value) {
Ok(value) => self
.encoded_path_params
.push((name, encode_path_param(name, &value, style, explode))),
Err(error) => self.fail(error),
}
self
}
pub fn json<T: DeserializeOwned + Send + 'static>(self, cfg: &Arc<Configuration>) -> Call<T> {
Call::new(self, cfg.clone(), json::<T>, false)
}
pub fn json_or_none<T: DeserializeOwned + Send + 'static>(
self,
cfg: &Arc<Configuration>,
) -> Call<Option<T>> {
Call::new(self, cfg.clone(), json_or_none::<T>, false)
}
pub fn empty(self, cfg: &Arc<Configuration>) -> Call<()> {
Call::new(self, cfg.clone(), empty, false)
}
pub fn binary(self, cfg: &Arc<Configuration>) -> Call<Bytes> {
Call::new(self, cfg.clone(), ResponseBody::bytes, false)
}
pub fn text(self, cfg: &Arc<Configuration>) -> Call<String> {
Call::new(self, cfg.clone(), text, false)
}
pub fn events(self, cfg: &Arc<Configuration>) -> Call<EventStream<SseEvent>> {
Call::new(self.accepting_events(), cfg.clone(), events, true)
}
pub fn typed_events<E: DeserializeOwned + Send + 'static>(
self,
cfg: &Arc<Configuration>,
) -> Call<EventStream<E>> {
Call::new(
self.accepting_events(),
cfg.clone(),
typed_events::<E>,
true,
)
}
fn accepting_events(mut self) -> Self {
self.headers.insert(
http::header::ACCEPT,
HeaderValue::from_static("text/event-stream"),
);
self
}
pub(crate) async fn send(
mut self,
conf: &Configuration,
event_stream: bool,
) -> Result<Received, Error> {
if let Some(error) = self.error.take() {
return Err(error);
}
let token = conf
.bearer_access_token
.as_deref()
.filter(|t| !t.is_empty());
let mut oauth = match conf.credentials.oauth_scheme(self.security, token) {
Some((url, scope)) => Some(oauth_token(conf, url, scope).await?),
None => None,
};
let auth = conf
.credentials
.apply(
self.security,
token,
oauth.as_ref().map(|used| used.token.as_str()),
)
.await?;
self.query_params.extend(
auth.query
.into_iter()
.map(|(name, value)| (name.to_owned(), value)),
);
for (name, value) in &conf.headers {
match header(name, value) {
Ok((name, value))
if !self.overrides.contains_key(&name) && !self.headers.contains_key(&name) =>
{
self.overrides.append(name, value);
}
Ok(_) => {}
Err(error) => return Err(request_error(error)),
}
}
for (name, value) in auth.headers {
let name = HeaderName::from_bytes(name.as_bytes()).map_err(request_error)?;
let mut value = HeaderValue::try_from(value).map_err(request_error)?;
value.set_sensitive(true);
self.headers.insert(name, value);
}
let mut cookie = self
.cookies
.iter()
.map(|(name, value)| format!("{name}={}", utf8_percent_encode(value, COOKIE_VALUE)))
.collect::<Vec<_>>();
cookie.extend(
auth.cookies.iter().map(|(name, value)| {
format!("{name}={}", utf8_percent_encode(value, API_KEY_COOKIE))
}),
);
for value in self.overrides.get_all("cookie") {
cookie.push(String::from_utf8_lossy(value.as_bytes()).into_owned());
}
self.overrides.remove("cookie");
if !cookie.is_empty() {
let mut value = HeaderValue::try_from(cookie.join("; ")).map_err(request_error)?;
value.set_sensitive(true);
self.headers.insert("cookie", value);
}
for name in self.overrides.keys() {
self.headers.remove(name);
}
for (name, value) in &self.overrides {
self.headers.append(name, value.clone());
}
if AUTO_IDEMPOTENCY_KEY
&& self.method == Method::POST
&& !self.headers.contains_key(IDEMPOTENCY_KEY)
{
let key = format!("auto_{:016x}{:016x}", random(), random());
self.headers.insert(
IDEMPOTENCY_KEY,
HeaderValue::try_from(key).map_err(request_error)?,
);
}
self.headers
.insert("meteroid-req-id", HeaderValue::from(random()));
let idempotent = self.retry_safe
|| self.method.is_idempotent()
|| self.headers.contains_key(IDEMPOTENCY_KEY);
let replayable = self.upload.as_ref().is_none_or(Upload::replayable)
&& self.multipart.as_ref().is_none_or(Multipart::replayable);
let max_retries = self.max_retries.unwrap_or(conf.max_retries) as usize;
let mut retries = 0;
let mut renewed = false;
loop {
let attempt = self.attempt(conf, event_stream).await;
if let Attempt::Done(status, headers, body) = attempt {
return Ok(Received {
status,
headers,
body,
});
}
if let (Attempt::Status(StatusCode::UNAUTHORIZED, ..), Some(used), false, true) =
(&attempt, &oauth, renewed, replayable)
{
let sent = self.headers.get(AUTHORIZATION).map(HeaderValue::as_bytes);
if sent == Some(format!("Bearer {}", used.token).as_bytes()) {
renewed = true;
if let Some(client) = &conf.credentials.oauth {
client.invalidate(&used.key, &used.token).await;
}
let fresh = oauth_token(conf, used.url, used.scope).await?;
let mut value = HeaderValue::try_from(format!("Bearer {}", fresh.token))
.map_err(request_error)?;
value.set_sensitive(true);
self.headers.insert(AUTHORIZATION, value);
oauth = Some(fresh);
continue;
}
}
if !(idempotent && replayable && attempt.retryable()) || retries >= max_retries {
return Err(attempt.into_error());
}
let delay = attempt.retry_after().unwrap_or_else(|| backoff(retries));
tokio::time::sleep(delay).await;
retries += 1;
self.headers
.insert("meteroid-retry-count", HeaderValue::from(retries));
}
}
async fn attempt(&mut self, conf: &Configuration, event_stream: bool) -> Attempt {
let mut request = match self.build_request(conf) {
Ok(request) => request,
Err(error) => return Attempt::Failed(Failure::Request(error)),
};
let exchange = async {
let body = request.body_mut().validate_empty().await;
body.map_err(|error| Failure::Request(error.into()))?;
let response = Next::new(&conf.middleware, &*conf.client)
.run(MiddlewareRequest(request))
.await
.map_err(Failure::Transport)?;
let status = response.status();
if status.is_success() && event_stream {
return open_event_stream(response);
}
let (status, headers, body) =
response.into_parts().await.map_err(Failure::Transport)?;
Ok(if status.is_success() {
Attempt::Done(status, headers, ResponseBody::Buffered(body))
} else {
Attempt::Status(status, headers, body)
})
};
let result = match self.timeout.unwrap_or(conf.timeout) {
Some(timeout) => tokio::time::timeout(timeout, exchange)
.await
.unwrap_or(Err(Failure::Timeout)),
None => exchange.await,
};
result.unwrap_or_else(Attempt::Failed)
}
fn build_request(
&mut self,
conf: &Configuration,
) -> Result<http::Request<RequestBody>, BoxError> {
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%');
let mut path = self.path.to_string();
for (name, value) in &self.path_params {
if value == "." || value == ".." {
return Err(format!(
"path parameter `{name}` is `{value}`, which the URL would resolve away"
)
.into());
}
let value = utf8_percent_encode(value, PATH_SEGMENT).to_string();
path = path.replace(&format!("{{{name}}}"), &value);
}
for (name, value) in &self.encoded_path_params {
path = path.replace(&format!("{{{name}}}"), value);
}
let mut uri = if path.contains("://") {
path.clone()
} else {
format!("{}{path}", conf.base_path.trim_end_matches('/'))
};
if !self.query_params.is_empty() {
let mut query = url::form_urlencoded::Serializer::new(String::new());
for (name, value) in &self.query_params {
query.append_pair(name, value);
}
uri.push(if path.contains('?') { '&' } else { '?' });
uri.push_str(&query.finish());
}
let (body, content_type) = if let Some(form) = &mut self.multipart {
(form.body()?, Some(form.content_type()))
} else if let Some(upload) = &mut self.upload {
(upload.body()?, Some(self.upload_content_type.to_owned()))
} else if let Some(body) = &self.serialized_body {
let content_type = if self.body_is_form {
"application/x-www-form-urlencoded"
} else {
"application/json"
};
(
Upload::bytes(body.clone()).body()?,
Some(content_type.to_owned()),
)
} else {
(RequestBody::empty(), None)
};
let length = body.length();
let mut request = http::Request::builder()
.method(self.method.clone())
.uri(uri)
.body(body)?;
let headers = request.headers_mut();
if let Some(content_type) = content_type {
headers.insert(CONTENT_TYPE, HeaderValue::try_from(content_type)?);
if let Some(length) = length {
headers.insert(CONTENT_LENGTH, length.into());
}
}
if let Some(user_agent) = &conf.user_agent {
headers.insert(USER_AGENT, HeaderValue::try_from(user_agent)?);
}
for name in self.headers.keys() {
headers.remove(name);
}
for (name, value) in &self.headers {
headers.append(name, value.clone());
}
Ok(request)
}
}
fn oauth_token<'a>(
conf: &'a Configuration,
url: &'static str,
scope: &'static str,
) -> SyncFuture<'a, Result<OAuthUse, Error>> {
SyncFuture::new(async move {
let client = conf
.credentials
.oauth
.as_ref()
.ok_or_else(|| request_error("no OAuth2 client credentials"))?;
let endpoint = token_endpoint(&conf.base_path, url);
let key = format!("{endpoint}\n{scope}");
let fetch = SyncFuture::new(fetch_token(conf, endpoint, scope));
let token = client.token(&key, fetch).await?;
Ok(OAuthUse {
url,
scope,
key,
token,
})
})
}
fn token_endpoint(base_path: &str, token_url: &str) -> String {
if token_url.contains("://") {
return token_url.to_owned();
}
let base = base_path.trim_end_matches('/');
if token_url.starts_with('/') {
if let Ok(parsed) = url::Url::parse(base) {
return format!("{}{token_url}", parsed.origin().ascii_serialization());
}
return format!("{base}{token_url}");
}
format!("{base}/{token_url}")
}
async fn fetch_token(
conf: &Configuration,
endpoint: String,
scope: &str,
) -> Result<(String, Option<Duration>), Error> {
#[derive(serde::Deserialize)]
struct Grant {
access_token: String,
#[serde(default)]
expires_in: Option<serde_json::Value>,
}
let client = conf
.credentials
.oauth
.as_ref()
.ok_or_else(|| request_error("no OAuth2 client credentials"))?;
let mut form = serde_json::Map::new();
form.insert("grant_type".to_owned(), "client_credentials".into());
if !scope.is_empty() {
form.insert("scope".to_owned(), scope.into());
}
let mut request = Request::new(Method::POST, "").with_security(&[]);
request.path = Cow::Owned(endpoint);
request.retry_safe = true;
if client.in_body {
form.insert("client_id".to_owned(), client.client_id.clone().into());
form.insert(
"client_secret".to_owned(),
client.client_secret.clone().into(),
);
} else {
let encode = |value: &str| {
url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
};
let credentials = format!(
"{}:{}",
encode(&client.client_id),
encode(&client.client_secret)
);
request = request.with_authorization(format!("Basic {}", base64(credentials.as_bytes())));
}
request = request.with_form_body_param(serde_json::Value::Object(form), &[], &[]);
let received = request.send(conf, false).await?;
let grant: Grant = serde_json::from_slice(&received.body.bytes()?).map_err(decode_error)?;
if grant.access_token.is_empty() {
return Err(decode_error(
"the token endpoint answered without an access_token",
));
}
let seconds = match grant.expires_in {
Some(serde_json::Value::Number(number)) => number.as_f64(),
Some(serde_json::Value::String(text)) => text.trim().parse::<f64>().ok(),
_ => None,
};
let lifetime = seconds.and_then(|seconds| Duration::try_from_secs_f64(seconds.max(0.0)).ok());
Ok((grant.access_token, lifetime))
}
const COOKIE_VALUE: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
const API_KEY_COOKIE: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b',').add(b';').add(b'\\');
fn header(name: &str, value: &str) -> Result<(HeaderName, HeaderValue), BoxError> {
Ok((
HeaderName::from_bytes(name.as_bytes())?,
HeaderValue::try_from(value)?,
))
}
fn open_event_stream(response: Response) -> Result<Attempt, Failure> {
let content_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.unwrap_or_default()
.trim();
if !content_type.eq_ignore_ascii_case("text/event-stream") {
return Err(Failure::Decode(
format!("expected a text/event-stream response, got `{content_type}`").into(),
));
}
let (status, headers) = (response.status(), response.headers().clone());
let (body, buffered) = response.into_events();
Ok(Attempt::Done(
status,
headers,
ResponseBody::Events(body, buffered),
))
}
fn backoff(retries: usize) -> Duration {
let exponent = u32::try_from(retries).unwrap_or(u32::MAX);
let delay = Duration::from_millis(500) * 2u32.saturating_pow(exponent);
let jitter = 1.0 - f64::from(u16::try_from(random() % 1000).unwrap_or_default()) / 4000.0;
delay.min(Duration::from_secs(8)).mul_f64(jitter)
}
pub(crate) fn random() -> u64 {
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u128(
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos(),
);
hasher.finish()
}
fn httpdate(value: &str) -> Option<SystemTime> {
let mut parts = value.split_whitespace().skip(1);
let day: u64 = parts.next()?.parse().ok()?;
let month = parts.next()?;
let month = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
]
.iter()
.position(|m| *m == month)? as u64
+ 1;
let year: u64 = parts.next()?.parse().ok()?;
let mut time = parts.next()?.split(':').map(|n| n.parse::<u64>().ok());
let (h, m, s) = (time.next()??, time.next()??, time.next()??);
let (y, mo) = if month <= 2 {
(year - 1, month + 9)
} else {
(year, month - 3)
};
let era = y / 400;
let yoe = y - era * 400;
let doy = (153 * mo + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = (era * 146_097 + doe).checked_sub(719_468)?;
let seconds = days * 86_400 + h * 3600 + m * 60 + s;
Some(SystemTime::UNIX_EPOCH + Duration::from_secs(seconds))
}
fn scalar_text(value: &serde_json::Value) -> Option<String> {
match value {
serde_json::Value::String(s) => Some(s.clone()),
serde_json::Value::Bool(b) => Some(b.to_string()),
serde_json::Value::Number(n) => Some(n.to_string()),
_ => None,
}
}
fn encode_param(
name: &str,
value: &serde_json::Value,
deep_object: bool,
explode: bool,
out: &mut Vec<(String, String)>,
) {
let nested = |v: &serde_json::Value| v.is_object() || v.is_array();
match value {
serde_json::Value::Array(items) if !deep_object && !items.iter().any(nested) => {
let texts = items.iter().filter_map(scalar_text);
if explode {
out.extend(texts.map(|text| (name.to_owned(), text)));
} else {
let joined = texts.collect::<Vec<_>>().join(",");
if !joined.is_empty() {
out.push((name.to_owned(), joined));
}
}
}
value => flatten_param(name.to_owned(), value, out),
}
}
fn flatten_param(prefix: String, value: &serde_json::Value, out: &mut Vec<(String, String)>) {
match value {
serde_json::Value::Object(fields) => {
for (key, value) in fields {
flatten_param(format!("{prefix}[{key}]"), value, out);
}
}
serde_json::Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
if item.is_object() || item.is_array() {
flatten_param(format!("{prefix}[{index}]"), item, out);
} else if let Some(text) = scalar_text(item) {
out.push((format!("{prefix}[]"), text));
}
}
}
value => out.extend(scalar_text(value).map(|text| (prefix, text))),
}
}
fn encode_path_param(name: &str, value: &serde_json::Value, style: &str, explode: bool) -> String {
const UNRESERVED: &AsciiSet = &percent_encoding::NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
let encode = |text: &str| utf8_percent_encode(text, UNRESERVED).to_string();
let text = |value: &serde_json::Value| match value {
serde_json::Value::Null => String::new(),
serde_json::Value::Array(_) | serde_json::Value::Object(_) => value.to_string(),
value => scalar_text(value).unwrap_or_default(),
};
if style == "json" {
return encode(&value.to_string());
}
let name = encode(name);
let (head, separator) = match style {
"label" => (".", "."),
"matrix" => (";", ";"),
_ => ("", ","),
};
let encoded = match value {
serde_json::Value::Array(items) => {
let values: Vec<String> = items.iter().map(|item| encode(&text(item))).collect();
match (style, explode) {
("matrix", true) => values.iter().map(|v| format!(";{name}={v}")).collect(),
("matrix", false) => format!(";{name}={}", values.join(",")),
(_, explode) => {
format!(
"{head}{}",
values.join(if explode { separator } else { "," })
)
}
}
}
serde_json::Value::Object(fields) => {
let pairs: Vec<(String, String)> = fields
.iter()
.map(|(key, value)| (encode(key), encode(&text(value))))
.collect();
let flat = || {
let flat: Vec<&str> = pairs
.iter()
.flat_map(|(k, v)| [k.as_str(), v.as_str()])
.collect();
flat.join(",")
};
match (style, explode) {
("matrix", true) => pairs.iter().map(|(k, v)| format!(";{k}={v}")).collect(),
("matrix", false) => format!(";{name}={}", flat()),
(_, true) => {
let pairs: Vec<String> =
pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
format!("{head}{}", pairs.join(separator))
}
(_, false) => format!("{head}{}", flat()),
}
}
scalar => {
let value = encode(&text(scalar));
match style {
"label" => format!(".{value}"),
"matrix" if value.is_empty() => format!(";{name}"),
"matrix" => format!(";{name}={value}"),
_ => value,
}
}
};
if encoded == "." || encoded == ".." {
return encoded.replace('.', "%2E");
}
encoded
}
pub(crate) trait QueryParamValue {
fn encode(&self) -> String;
}
macro_rules! impl_query_param_value {
($($ty:ty),*) => {
$(impl QueryParamValue for $ty {
fn encode(&self) -> String {
self.to_string()
}
})*
};
}
impl_query_param_value!(
bool,
i16,
u16,
i32,
u32,
i64,
u64,
f32,
f64,
String,
&str,
uuid::Uuid
);
impl QueryParamValue for rust_decimal::Decimal {
fn encode(&self) -> String {
self.to_string()
}
}
impl<T: QueryParamValue> QueryParamValue for Vec<T> {
fn encode(&self) -> String {
self.iter().map(T::encode).collect::<Vec<_>>().join(",")
}
}
#[cfg(test)]
mod wire_tests {
use super::*;
#[test]
fn api_key_cookie_keeps_cookie_octets() {
let sent = |key: &str| utf8_percent_encode(key, API_KEY_COOKIE).to_string();
assert_eq!(sent("abc/def+ghi=="), "abc/def+ghi==");
assert_eq!(sent("a b,c;d\"e\\f"), "a%20b%2Cc%3Bd%22e%5Cf");
assert_eq!(sent("caf\u{e9}"), "caf%C3%A9");
}
#[test]
fn styled_path_params_never_become_dot_segments() {
let encode = |value: &str, style: &str| {
encode_path_param(
"id",
&serde_json::Value::String(value.to_owned()),
style,
false,
)
};
assert_eq!(encode("", "label"), "%2E");
assert_eq!(encode(".", "label"), "%2E%2E");
assert_eq!(encode("..", "simple"), "%2E%2E");
assert_eq!(encode("a", "label"), ".a");
}
}