Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ keywords = ["clevercloud", "sdk", "logging", "metrics", "jsonschemas"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
chrono = { version = "^0.4.40", features = ["serde"] }
oauth10a = { version = "^2.1.1", default-features = false, features = [
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have to publish a version here

base64 = { version = "^0.22.1", optional = true }
chrono = { version = "^0.4.41", features = ["serde"] }
oauth10a = { path = "../oauth10a-rust", default-features = false, features = [
"client",
"sse",
] }
log = { version = "^0.4.26", optional = true }
log = { version = "^0.4.27", optional = true }
rand_core = { version = "^0.9.3", features = ["os_rng"], optional = true }
schemars = { version = "^0.8.22", features = [
"chrono",
"indexmap1",
Expand All @@ -30,11 +33,17 @@ serde_repr = "^0.1.20"
serde_json = "^1.0.140"
thiserror = "^2.0.12"
tracing = { version = "^0.1.41", optional = true }
uuid = { version = "^1.16.0", features = ["serde", "v4"] }
uuid = { version = "^1.17.0", features = ["serde", "v4"] }
x25519-dalek = { version = "^2.0.1", features = [
"zeroize",
"static_secrets",
], optional = true }
zeroize = { version = "^1.8.1", optional = true }

[features]
default = ["logging"]
default = ["logging", "network-group"]
jsonschemas = ["schemars"]
logging = ["oauth10a/logging", "tracing/log-always", "log"]
metrics = ["oauth10a/metrics"]
tracing = ["oauth10a/tracing", "dep:tracing"]
network-group = ["dep:base64", "x25519-dalek", "zeroize", "rand_core"]
83 changes: 41 additions & 42 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//! # Clever-Cloud Sdk
//!
//! This module provides a client and structures to interact with clever-cloud
//! api.
//! This module provides a client and structures to interact with Clever Cloud API.
use std::fmt::Debug;
use core::fmt;

use ::oauth10a::client::{Execute, reqwest::IntoUrl};
use serde::{Deserialize, Serialize, de::DeserializeOwned};

use crate::oauth10a::{
Client as OAuthClient, ClientError, Request, RestClient,
Client as OAuthClient, ClientError, RestClient,
reqwest::{self, Method},
};

Expand Down Expand Up @@ -46,7 +46,7 @@ pub fn default_consumer_secret() -> String {
// -----------------------------------------------------------------------------
// Credentials structure

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(untagged)]
pub enum Credentials {
OAuth1 {
Expand All @@ -71,6 +71,16 @@ pub enum Credentials {
},
}

impl fmt::Debug for Credentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OAuth1 { .. } => f.write_str("OAuth1"),
Self::Basic { .. } => f.write_str("Basic"),
Self::Bearer { .. } => f.write_str("Bearer"),
}
}
}

impl Default for Credentials {
#[tracing::instrument(skip_all)]
fn default() -> Self {
Expand Down Expand Up @@ -208,80 +218,69 @@ pub struct Client {
endpoint: String,
}

impl Request for Client {
impl Execute for Client {
type Error = ClientError;

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn execute(
&self,
request: reqwest::Request,
) -> impl Future<Output = Result<reqwest::Response, Self::Error>> + Send + 'static {
self.inner.execute(request)
}
}

impl<X: IntoUrl + Send + fmt::Debug> RestClient<X> for Client {
fn request<T, U>(
&self,
method: &Method,
endpoint: &str,
endpoint: X,
payload: &T,
) -> impl Future<Output = Result<U, Self::Error>>
) -> impl Future<Output = Result<U, Self::Error>> + Send
where
T: Serialize + Debug + Send + Sync,
U: DeserializeOwned + Debug + Send + Sync,
T: ?Sized + Serialize + fmt::Debug + Send + Sync,
U: DeserializeOwned + fmt::Debug + Send + Sync,
{
self.inner.request(method, endpoint, payload)
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn execute(
&self,
request: reqwest::Request,
) -> impl Future<Output = Result<reqwest::Response, Self::Error>> {
self.inner.execute(request)
}
}

impl RestClient for Client {
type Error = ClientError;

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn get<T>(&self, endpoint: &str) -> impl Future<Output = Result<T, Self::Error>>
fn get<T>(&self, endpoint: X) -> impl Future<Output = Result<T, Self::Error>>
where
T: DeserializeOwned + Debug + Send + Sync,
T: DeserializeOwned + fmt::Debug + Send + Sync,
{
self.inner.get(endpoint)
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn post<T, U>(
&self,
endpoint: &str,
payload: &T,
) -> impl Future<Output = Result<U, Self::Error>>
fn post<T, U>(&self, endpoint: X, payload: &T) -> impl Future<Output = Result<U, Self::Error>>
where
T: Serialize + Debug + Send + Sync,
U: DeserializeOwned + Debug + Send + Sync,
T: Serialize + fmt::Debug + Send + Sync + ?Sized,
U: DeserializeOwned + fmt::Debug + Send + Sync,
{
self.inner.post(endpoint, payload)
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn put<T, U>(&self, endpoint: &str, payload: &T) -> impl Future<Output = Result<U, Self::Error>>
fn put<T, U>(&self, endpoint: X, payload: &T) -> impl Future<Output = Result<U, Self::Error>>
where
T: Serialize + Debug + Send + Sync,
U: DeserializeOwned + Debug + Send + Sync,
T: Serialize + fmt::Debug + Send + Sync + ?Sized,
U: DeserializeOwned + fmt::Debug + Send + Sync,
{
self.inner.put(endpoint, payload)
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn patch<T, U>(
&self,
endpoint: &str,
payload: &T,
) -> impl Future<Output = Result<U, Self::Error>>
fn patch<T, U>(&self, endpoint: X, payload: &T) -> impl Future<Output = Result<U, Self::Error>>
where
T: Serialize + Debug + Send + Sync,
U: DeserializeOwned + Debug + Send + Sync,
T: Serialize + fmt::Debug + Send + Sync + ?Sized,
U: DeserializeOwned + fmt::Debug + Send + Sync,
{
self.inner.patch(endpoint, payload)
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn delete(&self, endpoint: &str) -> impl Future<Output = Result<(), Self::Error>> {
fn delete(&self, endpoint: X) -> impl Future<Output = Result<(), Self::Error>> {
self.inner.delete(endpoint)
}
}
Expand Down
25 changes: 25 additions & 0 deletions src/v2/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use core::{error::Error, fmt};

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseError {
#[serde(rename = "id")]
pub id: u32,
#[serde(rename = "message")]
pub message: String,
#[serde(rename = "type")]
pub kind: String,
}

impl fmt::Display for ResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"got response {} ({}), {}",
self.kind, self.id, self.message
)
}
}

impl Error for ResponseError {}
1 change: 1 addition & 0 deletions src/v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
//! This module expose resources under the version 2 of the Clever-Cloud Api.

pub mod addon;
pub mod error;
pub mod myself;
pub mod plan;
2 changes: 1 addition & 1 deletion src/v4/functions/deployments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{
use chrono::{DateTime, Utc};
use log::{Level, debug, log_enabled};
use oauth10a::client::{
ClientError, Request, RestClient,
ClientError, Execute, RestClient,
reqwest::{
self, Body, Method,
header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue},
Expand Down
103 changes: 103 additions & 0 deletions src/v4/http_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
use oauth10a::client::reqwest::StatusCode;
use serde::{Deserialize, Serialize};

pub type HttpOutput = (StatusCode, HttpError);

mod http_error_context {
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct Empty;

#[derive(Debug, Deserialize, Serialize)]
pub struct FieldError {
#[serde(rename = "value")]
value: String,
#[serde(rename = "reason")]
reason: Option<String>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Field {
#[serde(rename = "name")]
name: String,
#[serde(rename = "error")]
error: FieldError,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct GatewayError {
#[serde(rename = "originalStatus")]
original_status: i32,
#[serde(rename = "originalBody")]
original_body: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Input {
#[serde(rename = "names")]
names: Vec<String>,
}

type MapFieldError = HashMap<String, FieldError>;

#[derive(Debug, Deserialize, Serialize)]
pub struct MultipleFields {
#[serde(rename = "fields")]
fields: MapFieldError,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Resource {
#[serde(rename = "kind")]
kind: String,
#[serde(rename = "name")]
name: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Operation {
#[serde(rename = "operation")]
operation: String,
#[serde(rename = "kind")]
kind: String,
#[serde(rename = "name")]
name: Option<String>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Selector {
#[serde(rename = "path")]
path: Vec<String>,
}
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HttpErrorContext {
Empty(http_error_context::Empty),
Field(http_error_context::Field),
Gateway(http_error_context::GatewayError),
Input(http_error_context::Input),
MultipleFields(http_error_context::MultipleFields),
Operation(http_error_context::Operation),
Resource(http_error_context::Resource),
Selector(http_error_context::Selector),
}

#[derive(Debug, Deserialize, Serialize)]
pub struct HttpError {
#[serde(rename = "apiRequestId")]
pub api_request_id: String,
#[serde(rename = "code")]
pub code: String,
#[serde(rename = "context")]
pub context: HttpErrorContext,
#[serde(rename = "error")]
pub error: String,
}

// TODO: unit tests
// maybe use https://github.com/Orange-OpenSource/hurl or something
3 changes: 3 additions & 0 deletions src/v4/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@
pub mod addon_provider;
pub mod functions;
pub mod http_error;
#[cfg(feature = "network-group")]
pub mod network_group;
pub mod products;
32 changes: 32 additions & 0 deletions src/v4/network_group/delete.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use oauth10a::client::{ClientError, RestClient};
use tracing::debug;

use crate::Client;

use super::{OwnerId, network_group_id::NetworkGroupId, peer::PeerId};

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("failed to delete for owner '{0}', network group '{1}', peer id '{2}', {0}")]
Delete(String, NetworkGroupId, PeerId, ClientError),
}

pub async fn delete(
client: &Client,
owner_id: &OwnerId,
ng_id: &NetworkGroupId,
peer_id: PeerId,
) -> Result<(), Error> {
let endpoint = format!(
"{}/v4/networkgroups/organisations/{owner_id}/networkgroups/{ng_id}/external-peers/{peer_id}",
client.endpoint,
);

#[cfg(feature = "tracing")]
debug!("execute a request to delete peer from Network Group, endpoint: '{endpoint}'");

client
.delete(&endpoint)
.await
.map_err(|e| Error::Delete(owner_id.to_owned(), *ng_id, peer_id, e))
}
15 changes: 15 additions & 0 deletions src/v4/network_group/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//! # Network Group module
//!
//! This module provide structures and helpers to interact with Clever Cloud's
//! Network Group API.
pub type MemberId = String;

pub type OwnerId = String;

pub mod delete;
pub mod network_group_id;
pub mod peer;
pub mod wannabe_external_peer;
pub mod wireguard;
pub mod wireguard_configuration;
Loading
Loading