use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::AxiamError;
use crate::client::AxiamClient;
use crate::rest::auth::{CsrfHeaderExt, TenantHeadersExt};
use crate::retry::{Attempt, RetryRunner, ThreadRngJitter, TokioSleeper, parse_retry_after};
use crate::telemetry::{Outcome, TelemetryEvent};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Verb {
Get,
Post,
Put,
Patch,
Delete,
}
impl Verb {
fn as_str(self) -> &'static str {
match self {
Verb::Get => "GET",
Verb::Post => "POST",
Verb::Put => "PUT",
Verb::Patch => "PATCH",
Verb::Delete => "DELETE",
}
}
fn is_read_only(self) -> bool {
matches!(self, Verb::Get)
}
fn apply(self, client: &AxiamClient, url: url::Url) -> reqwest::RequestBuilder {
let http = client.http();
match self {
Verb::Get => http.get(url),
Verb::Post => http.post(url),
Verb::Put => http.put(url),
Verb::Patch => http.patch(url),
Verb::Delete => http.delete(url),
}
}
}
pub(crate) struct Call<'a> {
pub operation: &'static str,
pub verb: Verb,
pub path_template: &'static str,
pub path: String,
pub query: &'a [(&'static str, String)],
}
impl AxiamClient {
pub(crate) async fn management_send<B, R>(
&self,
call: Call<'_>,
body: Option<&B>,
) -> Result<R, AxiamError>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
let raw = self.management_raw(call, body).await?;
serde_json::from_slice(&raw).map_err(|e| AxiamError::Network {
message: format!("failed to parse management response body: {e}"),
source: Some(Box::new(e)),
})
}
pub(crate) async fn management_send_no_content<B>(
&self,
call: Call<'_>,
body: Option<&B>,
) -> Result<(), AxiamError>
where
B: Serialize + ?Sized,
{
self.management_raw(call, body).await.map(|_| ())
}
async fn management_raw<B>(
&self,
call: Call<'_>,
body: Option<&B>,
) -> Result<Vec<u8>, AxiamError>
where
B: Serialize + ?Sized,
{
self.ensure_open()?;
if self.token_manager().cached_access_token().is_none() {
return Err(AxiamError::auth(format!(
"{}: no active session — call login() before using the management API",
call.operation
)));
}
let url = self.management_url(&call.path, call.query)?;
let call = &call;
let url = &url;
let first = if call.verb.is_read_only() {
let runner = RetryRunner {
enabled: self.retry_enabled(),
operation: call.operation,
telemetry: self.telemetry(),
jitter: &ThreadRngJitter,
sleeper: &TokioSleeper,
};
runner
.run(|attempt| async move { self.management_attempt(call, url, body, attempt).await })
.await
} else {
self.management_attempt(call, url, body, 0)
.await
.map_err(|a| a.err)
};
match first {
Ok(bytes) => Ok(bytes),
Err(err @ AxiamError::Auth { .. }) if self.holds_bearer_credential() => Err(err),
Err(AxiamError::Auth { .. }) => {
self.refresh().await?;
self.management_attempt(call, url, body, 1)
.await
.map_err(|a| a.err)
}
Err(other) => Err(other),
}
}
async fn management_attempt<B>(
&self,
call: &Call<'_>,
url: &url::Url,
body: Option<&B>,
attempt: u32,
) -> Result<Vec<u8>, Attempt>
where
B: Serialize + ?Sized,
{
let telemetry = self.telemetry();
let method = call.verb.as_str();
telemetry.emit(TelemetryEvent::RequestStart {
operation: call.operation,
method,
path_template: call.path_template,
attempt,
});
let started = crate::time::Instant::now();
let finish = |status: Option<u16>, outcome: Outcome| {
telemetry.emit(TelemetryEvent::RequestEnd {
operation: call.operation,
method,
path_template: call.path_template,
attempt,
status,
duration: started.elapsed(),
outcome,
});
};
let mut request = call
.verb
.apply(self, url.clone())
.tenant_headers_of(self)
.session_credential_of(self)
.maybe_csrf_header(self);
if let Some(b) = body {
request = request.json(b);
}
let response = match request.send().await {
Ok(r) => r,
Err(e) => {
finish(None, Outcome::Failure);
return Err(Attempt::bare(AxiamError::Network {
message: format!("{} request failed: {e}", call.operation),
source: Some(Box::new(e)),
}));
}
};
let status = response.status().as_u16();
if !response.status().is_success() {
let retry_after = response
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.and_then(parse_retry_after);
let message = response
.text()
.await
.unwrap_or_else(|_| "no response body".to_string());
finish(Some(status), Outcome::Failure);
return Err(Attempt {
err: super::error::from_management_status(call.operation, status, message),
retry_after,
});
}
match response.bytes().await {
Ok(bytes) => {
finish(Some(status), Outcome::Success);
Ok(bytes.to_vec())
}
Err(e) => {
finish(Some(status), Outcome::Failure);
Err(Attempt::bare(AxiamError::Network {
message: format!("failed to read management response body: {e}"),
source: Some(Box::new(e)),
}))
}
}
}
fn management_url(
&self,
path: &str,
query: &[(&'static str, String)],
) -> Result<url::Url, AxiamError> {
let mut url = self.base_url().join(path).map_err(|e| {
AxiamError::network(format!("management path {path} is not a valid URL: {e}"))
})?;
if !query.is_empty() {
let mut pairs = url.query_pairs_mut();
for (k, v) in query {
pairs.append_pair(k, v);
}
}
Ok(url)
}
}