#![doc = "Generated reqwest client with typed errors and streaming bodies."]
use async_trait::async_trait;
use futures::{Stream, TryStreamExt, stream};
use reqwest::{Client, Url};
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use spiral_contract::auth::AuthHeader;
use spiral_contract::call::{CallError, ServiceFailure};
use spiral_contract::error::ErrorEnvelope;
use crate::api::authorization::AuthorizationApi;
use crate::api::authorization::objects::*;
#[derive(Clone)]
pub struct AuthorizationClient {
http: ClientWithMiddleware,
base: Url,
}
impl std::fmt::Debug for AuthorizationClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AuthorizationClient")
.field("base", &self.base)
.finish_non_exhaustive()
}
}
impl AuthorizationClient {
#[expect(
clippy::disallowed_methods,
reason = "Generated clients keep their transport independent of the Spiral application runtime."
)]
pub fn new(base: &str) -> Result<Self, CallError<AuthorizationError>> {
let http = Client::builder()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(std::time::Duration::from_secs(10))
.build()
.map_err(CallError::transport)?;
Self::from_http(base, http)
}
pub fn from_http(base: &str, http: Client) -> Result<Self, CallError<AuthorizationError>> {
Self::from_transport(base, ClientBuilder::new(http).build())
}
pub fn from_transport(
base: &str,
http: ClientWithMiddleware,
) -> Result<Self, CallError<AuthorizationError>> {
let base = Url::parse(base)
.map_err(|_| CallError::<AuthorizationError>::protocol("invalid base URL"))?;
if !matches!(base.scheme(), "http" | "https")
|| base.host_str().is_none()
|| !base.username().is_empty()
|| base.password().is_some()
|| base.query().is_some()
|| base.fragment().is_some()
{
return Err(CallError::<AuthorizationError>::protocol(
"invalid base URL",
));
}
Ok(Self { http, base })
}
pub fn with_transport(mut self, http: ClientWithMiddleware) -> Self {
self.http = http;
self
}
pub fn with_http(mut self, http: Client) -> Self {
self.http = ClientBuilder::new(http).build();
self
}
pub async fn approve_installation_http(
&self,
auth_header: AuthHeader,
installation_id: String,
) -> Result<ReviewResponse, CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("installations");
let segment = installation_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
path.push("approve");
}
let builder = self.http.post(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn grant_role_http(
&self,
auth_header: AuthHeader,
project_id: String,
request: GrantRoleRequest,
) -> Result<GrantResponse, CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("projects");
let segment = project_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
path.push("grants");
}
let builder = self.http.post(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let builder = builder
.header("content-type", "application/json")
.json(&request);
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn list_grants_http(
&self,
auth_header: AuthHeader,
project_id: String,
request: ListGrantsRequest,
) -> Result<GrantPage, CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("projects");
let segment = project_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
path.push("grants");
}
let builder = self.http.get(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let builder = builder.query(&request);
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub fn list_grants_pages<'a>(
&'a self,
auth_header: &'a AuthHeader,
project_id: String,
request: ListGrantsRequest,
) -> impl Stream<Item = Result<GrantPage, CallError<AuthorizationError>>> + 'a {
stream::try_unfold(Some(request), move |request| {
#[allow(
clippy::clone_on_copy,
reason = "Hosts may implement Copy for generated aliases; pagination also supports Clone aliases."
)]
let project_id = project_id.clone();
async move {
let Some(mut request) = request else {
return Ok(None);
};
let page = self
.list_grants_http(auth_header.clone(), project_id, request.clone())
.await?;
let next = page.next_page_token.clone();
if next.as_ref().is_some_and(|token| {
token.is_empty() || Some(token) == request.page_token.as_ref()
}) {
return Err(CallError::<AuthorizationError>::protocol(
"invalid pagination token",
));
}
request.page_token = next;
let next_request = request.page_token.is_some().then_some(request);
Ok(Some((page, next_request)))
}
})
}
pub fn list_grants_items<'a>(
&'a self,
auth_header: &'a AuthHeader,
project_id: String,
request: ListGrantsRequest,
) -> impl Stream<Item = Result<Grant, CallError<AuthorizationError>>> + 'a {
self.list_grants_pages(auth_header, project_id, request)
.map_ok(|page| {
stream::iter(
page.items
.into_iter()
.map(Ok::<_, CallError<AuthorizationError>>),
)
})
.try_flatten()
}
pub async fn read_grant_http(
&self,
auth_header: AuthHeader,
grant_id: String,
) -> Result<Grant, CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("grants");
let segment = grant_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
}
let builder = self.http.get(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn read_installation_http(
&self,
auth_header: AuthHeader,
installation_id: String,
) -> Result<InstallationResponse, CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("installations");
let segment = installation_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
}
let builder = self.http.get(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn reject_installation_http(
&self,
auth_header: AuthHeader,
installation_id: String,
) -> Result<ReviewResponse, CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("installations");
let segment = installation_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
path.push("reject");
}
let builder = self.http.post(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn review_installation_http(
&self,
auth_header: AuthHeader,
installation_id: String,
request: ReviewRequest,
) -> Result<ReviewResponse, CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("installations");
let segment = installation_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
path.push("review");
}
let builder = self.http.post(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let builder = builder
.header("content-type", "application/json")
.json(&request);
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn revoke_grant_http(
&self,
auth_header: AuthHeader,
grant_id: String,
) -> Result<(), CallError<AuthorizationError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthorizationError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authorization");
path.push("grants");
let segment = grant_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthorizationError>::protocol(
"dot path segment",
));
}
path.push(&segment);
}
let builder = self.http.delete(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
async fn send(
&self,
builder: reqwest_middleware::RequestBuilder,
expected_media: &str,
) -> Result<reqwest::Response, CallError<AuthorizationError>> {
let response = builder
.timeout(std::time::Duration::from_secs(60))
.send()
.await
.map_err(CallError::transport)?;
let status = response.status();
if !status.is_success() {
let status = status.as_u16();
let content_type = response
.headers()
.get("content-type")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let (bytes, truncated) = bounded_error_body::<AuthorizationError>(
response,
64 * 1024,
status,
content_type.clone(),
)
.await?;
if truncated {
return Err(CallError::unknown_remote(status, content_type, bytes, true));
}
return match serde_json::from_slice::<ErrorEnvelope>(&bytes) {
Ok(envelope) => Err(CallError::Service(ServiceFailure::remote(status, envelope))),
Err(_) => Err(CallError::unknown_remote(
status,
content_type,
bytes,
false,
)),
};
}
if !media_matches(&response, expected_media) {
return Err(CallError::protocol_response(
status.as_u16(),
"unexpected response media type",
));
}
Ok(response)
}
}
fn media_matches(response: &reqwest::Response, expected: &str) -> bool {
response
.headers()
.get("content-type")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
}
async fn bounded_body(
mut response: reqwest::Response,
limit: usize,
) -> Result<Vec<u8>, CallError<AuthorizationError>> {
let status = response.status().as_u16();
let mut result = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|error| CallError::transport_response(status, error))?
{
if chunk.len() > limit.saturating_sub(result.len()) {
return Err(CallError::protocol_response(
status,
"response exceeds JSON size limit",
));
}
result.extend_from_slice(&chunk);
}
Ok(result)
}
async fn bounded_error_body<E>(
mut response: reqwest::Response,
limit: usize,
status: u16,
content_type: Option<String>,
) -> Result<(Vec<u8>, bool), CallError<E>> {
let mut result = Vec::new();
loop {
let chunk = response.chunk().await.map_err(|error| {
CallError::unreadable_remote(status, content_type.clone(), result.clone(), error)
})?;
let Some(chunk) = chunk else {
return Ok((result, false));
};
let remaining = limit.saturating_sub(result.len());
if chunk.len() > remaining {
result.extend_from_slice(&chunk[..remaining]);
return Ok((result, true));
}
result.extend_from_slice(&chunk);
}
}
#[async_trait]
impl AuthorizationApi for AuthorizationClient {
async fn approve_installation(
&self,
auth_header: AuthHeader,
installation_id: String,
) -> Result<ReviewResponse, CallError<AuthorizationError>> {
let response = Self::approve_installation_http(self, auth_header, installation_id).await?;
Ok(response)
}
async fn grant_role(
&self,
auth_header: AuthHeader,
project_id: String,
request: GrantRoleRequest,
) -> Result<GrantResponse, CallError<AuthorizationError>> {
let response = Self::grant_role_http(self, auth_header, project_id, request).await?;
Ok(response)
}
async fn list_grants(
&self,
auth_header: AuthHeader,
project_id: String,
request: ListGrantsRequest,
) -> Result<GrantPage, CallError<AuthorizationError>> {
let response = Self::list_grants_http(self, auth_header, project_id, request).await?;
Ok(response)
}
async fn read_grant(
&self,
auth_header: AuthHeader,
grant_id: String,
) -> Result<Grant, CallError<AuthorizationError>> {
let response = Self::read_grant_http(self, auth_header, grant_id).await?;
Ok(response)
}
async fn read_installation(
&self,
auth_header: AuthHeader,
installation_id: String,
) -> Result<InstallationResponse, CallError<AuthorizationError>> {
let response = Self::read_installation_http(self, auth_header, installation_id).await?;
Ok(response)
}
async fn reject_installation(
&self,
auth_header: AuthHeader,
installation_id: String,
) -> Result<ReviewResponse, CallError<AuthorizationError>> {
let response = Self::reject_installation_http(self, auth_header, installation_id).await?;
Ok(response)
}
async fn review_installation(
&self,
auth_header: AuthHeader,
installation_id: String,
request: ReviewRequest,
) -> Result<ReviewResponse, CallError<AuthorizationError>> {
let response =
Self::review_installation_http(self, auth_header, installation_id, request).await?;
Ok(response)
}
async fn revoke_grant(
&self,
auth_header: AuthHeader,
grant_id: String,
) -> Result<(), CallError<AuthorizationError>> {
let response = Self::revoke_grant_http(self, auth_header, grant_id).await?;
Ok(response)
}
}