Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trait for async API clients #85

Merged
merged 1 commit into from
Jan 10, 2020
Merged
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
16 changes: 12 additions & 4 deletions cloudflare-e2e-test/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
use clap::{App, AppSettings, Arg};
use cloudflare::framework::{async_api, auth::Credentials, Environment, HttpApiClientConfig};
use cloudflare::framework::{
async_api, async_api::ApiClient, auth::Credentials, Environment, HttpApiClientConfig,
};
use failure::{Error, Fallible};
use std::fmt::Display;
use std::net::{IpAddr, Ipv4Addr};

async fn tests(api_client: &async_api::Client, account_id: &str) -> Fallible<()> {
test_lb_pool(&api_client, &account_id).await?;
async fn tests<ApiClientType: ApiClient>(
api_client: &ApiClientType,
account_id: &str,
) -> Fallible<()> {
test_lb_pool(api_client, &account_id).await?;
println!("Tests passed");
Ok(())
}

async fn test_lb_pool(api_client: &async_api::Client, account_identifier: &str) -> Fallible<()> {
async fn test_lb_pool<ApiClientType: ApiClient>(
api_client: &ApiClientType,
account_identifier: &str,
) -> Fallible<()> {
use cloudflare::endpoints::load_balancing::*;

// Create a pool
Expand Down
1 change: 1 addition & 0 deletions cloudflare/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ categories = ["api-bindings", "web-programming::http-client"]
license = "BSD-3-Clause"

[dependencies]
async-trait = "0.1.22"
chrono = { version = "0.4", features = ["serde"] }
http = "0.1.18"
reqwest = { version = "0.10", features = ["json", "blocking"] }
Expand Down
1 change: 1 addition & 0 deletions cloudflare/src/framework/apiclient.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! This module contains the synchronous (blocking) API client.
use crate::framework::{
endpoint::Endpoint,
response::{ApiResponse, ApiResult},
Expand Down
22 changes: 18 additions & 4 deletions cloudflare/src/framework/async_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,22 @@ use crate::framework::{
response::{ApiResponse, ApiResult},
Environment, HttpApiClientConfig,
};
use async_trait::async_trait;
use reqwest;
use serde::Serialize;

#[async_trait]
pub trait ApiClient {
async fn request<ResultType, QueryType, BodyType>(
&self,
endpoint: &(dyn Endpoint<ResultType, QueryType, BodyType> + Send + Sync),
) -> ApiResponse<ResultType>
where
ResultType: ApiResult,
QueryType: Serialize,
BodyType: Serialize;
}

/// A Cloudflare API client that makes requests asynchronously.
pub struct Client {
environment: Environment,
Expand Down Expand Up @@ -42,12 +55,13 @@ impl Client {
http_client,
})
}
}

// Currently, futures/async fns aren't supported in traits, and won't be for a while.
// So unlike ApiClient/HttpApiClient, there's no trait with the request method.
pub async fn request<ResultType, QueryType, BodyType>(
#[async_trait]

Choose a reason for hiding this comment

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

I wonder if the language will ever support this directly - I wasn't able to find anything in the rust-lang issue tracker.

Copy link
Contributor Author

@adamchalmers adamchalmers Jan 9, 2020

Choose a reason for hiding this comment

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

The async book mentions it, and this article explains why it's hard. There's two features that probably have to land before async traits are properly supported: 1 and 2

impl ApiClient for Client {
async fn request<ResultType, QueryType, BodyType>(
&self,
endpoint: &dyn Endpoint<ResultType, QueryType, BodyType>,
endpoint: &(dyn Endpoint<ResultType, QueryType, BodyType> + Send + Sync),
) -> ApiResponse<ResultType>
where
ResultType: ApiResult,
Expand Down
38 changes: 27 additions & 11 deletions cloudflare/src/framework/mock.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::framework::apiclient::ApiClient;
use crate::framework::async_api;
use crate::framework::endpoint::{Endpoint, Method};
use crate::framework::response::{ApiError, ApiErrors, ApiFailure, ApiResponse, ApiResult};
use async_trait::async_trait;
use reqwest;
use std::collections::HashMap;

Expand All @@ -22,21 +24,35 @@ impl Endpoint<NoopResult> for NoopEndpoint {
pub struct NoopResult {}
impl ApiResult for NoopResult {}

fn mock_response() -> ApiFailure {
ApiFailure::Error(
reqwest::StatusCode::INTERNAL_SERVER_ERROR,
ApiErrors {
errors: vec![ApiError {
code: 9999,
message: "This is a mocked failure response".to_owned(),
other: HashMap::new(),
}],
other: HashMap::new(),
},
)
}

impl ApiClient for MockApiClient {
fn request<ResultType, QueryType, BodyType>(
&self,
_endpoint: &dyn Endpoint<ResultType, QueryType, BodyType>,
) -> ApiResponse<ResultType> {
Err(ApiFailure::Error(
reqwest::StatusCode::INTERNAL_SERVER_ERROR,
ApiErrors {
errors: vec![ApiError {
code: 9999,
message: "This is a mocked failure response".to_owned(),
other: HashMap::new(),
}],
other: HashMap::new(),
},
))
Err(mock_response())
}
}

#[async_trait]
impl async_api::ApiClient for MockApiClient {
async fn request<ResultType, QueryType, BodyType>(
&self,
_endpoint: &(dyn Endpoint<ResultType, QueryType, BodyType> + Send + Sync),
) -> ApiResponse<ResultType> {
Err(mock_response())
}
}