use std::error::Error;
use std::fmt;
#[allow(warnings)]
use futures::future;
use futures::Future;
use rusoto_core::credential::ProvideAwsCredentials;
use rusoto_core::region;
use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest};
use rusoto_core::{Client, RusotoError, RusotoFuture};
use rusoto_core::signature::SignedRequest;
use serde_json;
use serde_json::from_slice;
use serde_json::Value as SerdeJsonValue;
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct AttributeValue {
#[serde(rename = "Value")]
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DescribeServicesRequest {
#[serde(rename = "FormatVersion")]
#[serde(skip_serializing_if = "Option::is_none")]
pub format_version: Option<String>,
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<i64>,
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
#[serde(rename = "ServiceCode")]
#[serde(skip_serializing_if = "Option::is_none")]
pub service_code: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct DescribeServicesResponse {
#[serde(rename = "FormatVersion")]
#[serde(skip_serializing_if = "Option::is_none")]
pub format_version: Option<String>,
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
#[serde(rename = "Services")]
#[serde(skip_serializing_if = "Option::is_none")]
pub services: Option<Vec<Service>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct Filter {
#[serde(rename = "Field")]
pub field: String,
#[serde(rename = "Type")]
pub type_: String,
#[serde(rename = "Value")]
pub value: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetAttributeValuesRequest {
#[serde(rename = "AttributeName")]
pub attribute_name: String,
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<i64>,
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
#[serde(rename = "ServiceCode")]
pub service_code: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetAttributeValuesResponse {
#[serde(rename = "AttributeValues")]
#[serde(skip_serializing_if = "Option::is_none")]
pub attribute_values: Option<Vec<AttributeValue>>,
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetProductsRequest {
#[serde(rename = "Filters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub filters: Option<Vec<Filter>>,
#[serde(rename = "FormatVersion")]
#[serde(skip_serializing_if = "Option::is_none")]
pub format_version: Option<String>,
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<i64>,
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
#[serde(rename = "ServiceCode")]
#[serde(skip_serializing_if = "Option::is_none")]
pub service_code: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetProductsResponse {
#[serde(rename = "FormatVersion")]
#[serde(skip_serializing_if = "Option::is_none")]
pub format_version: Option<String>,
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
#[serde(rename = "PriceList")]
#[serde(skip_serializing_if = "Option::is_none")]
pub price_list: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Service {
#[serde(rename = "AttributeNames")]
#[serde(skip_serializing_if = "Option::is_none")]
pub attribute_names: Option<Vec<String>>,
#[serde(rename = "ServiceCode")]
#[serde(skip_serializing_if = "Option::is_none")]
pub service_code: Option<String>,
}
#[derive(Debug, PartialEq)]
pub enum DescribeServicesError {
ExpiredNextToken(String),
InternalError(String),
InvalidNextToken(String),
InvalidParameter(String),
NotFound(String),
}
impl DescribeServicesError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DescribeServicesError> {
if let Ok(json) = from_slice::<SerdeJsonValue>(&res.body) {
let raw_error_type = json
.get("__type")
.and_then(|e| e.as_str())
.unwrap_or("Unknown");
let error_message = json.get("message").and_then(|m| m.as_str()).unwrap_or("");
let pieces: Vec<&str> = raw_error_type.split("#").collect();
let error_type = pieces.last().expect("Expected error type");
match *error_type {
"ExpiredNextTokenException" => {
return RusotoError::Service(DescribeServicesError::ExpiredNextToken(
String::from(error_message),
))
}
"InternalErrorException" => {
return RusotoError::Service(DescribeServicesError::InternalError(
String::from(error_message),
))
}
"InvalidNextTokenException" => {
return RusotoError::Service(DescribeServicesError::InvalidNextToken(
String::from(error_message),
))
}
"InvalidParameterException" => {
return RusotoError::Service(DescribeServicesError::InvalidParameter(
String::from(error_message),
))
}
"NotFoundException" => {
return RusotoError::Service(DescribeServicesError::NotFound(String::from(
error_message,
)))
}
"ValidationException" => return RusotoError::Validation(error_message.to_string()),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DescribeServicesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DescribeServicesError {
fn description(&self) -> &str {
match *self {
DescribeServicesError::ExpiredNextToken(ref cause) => cause,
DescribeServicesError::InternalError(ref cause) => cause,
DescribeServicesError::InvalidNextToken(ref cause) => cause,
DescribeServicesError::InvalidParameter(ref cause) => cause,
DescribeServicesError::NotFound(ref cause) => cause,
}
}
}
#[derive(Debug, PartialEq)]
pub enum GetAttributeValuesError {
ExpiredNextToken(String),
InternalError(String),
InvalidNextToken(String),
InvalidParameter(String),
NotFound(String),
}
impl GetAttributeValuesError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetAttributeValuesError> {
if let Ok(json) = from_slice::<SerdeJsonValue>(&res.body) {
let raw_error_type = json
.get("__type")
.and_then(|e| e.as_str())
.unwrap_or("Unknown");
let error_message = json.get("message").and_then(|m| m.as_str()).unwrap_or("");
let pieces: Vec<&str> = raw_error_type.split("#").collect();
let error_type = pieces.last().expect("Expected error type");
match *error_type {
"ExpiredNextTokenException" => {
return RusotoError::Service(GetAttributeValuesError::ExpiredNextToken(
String::from(error_message),
))
}
"InternalErrorException" => {
return RusotoError::Service(GetAttributeValuesError::InternalError(
String::from(error_message),
))
}
"InvalidNextTokenException" => {
return RusotoError::Service(GetAttributeValuesError::InvalidNextToken(
String::from(error_message),
))
}
"InvalidParameterException" => {
return RusotoError::Service(GetAttributeValuesError::InvalidParameter(
String::from(error_message),
))
}
"NotFoundException" => {
return RusotoError::Service(GetAttributeValuesError::NotFound(String::from(
error_message,
)))
}
"ValidationException" => return RusotoError::Validation(error_message.to_string()),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetAttributeValuesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetAttributeValuesError {
fn description(&self) -> &str {
match *self {
GetAttributeValuesError::ExpiredNextToken(ref cause) => cause,
GetAttributeValuesError::InternalError(ref cause) => cause,
GetAttributeValuesError::InvalidNextToken(ref cause) => cause,
GetAttributeValuesError::InvalidParameter(ref cause) => cause,
GetAttributeValuesError::NotFound(ref cause) => cause,
}
}
}
#[derive(Debug, PartialEq)]
pub enum GetProductsError {
ExpiredNextToken(String),
InternalError(String),
InvalidNextToken(String),
InvalidParameter(String),
NotFound(String),
}
impl GetProductsError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetProductsError> {
if let Ok(json) = from_slice::<SerdeJsonValue>(&res.body) {
let raw_error_type = json
.get("__type")
.and_then(|e| e.as_str())
.unwrap_or("Unknown");
let error_message = json.get("message").and_then(|m| m.as_str()).unwrap_or("");
let pieces: Vec<&str> = raw_error_type.split("#").collect();
let error_type = pieces.last().expect("Expected error type");
match *error_type {
"ExpiredNextTokenException" => {
return RusotoError::Service(GetProductsError::ExpiredNextToken(String::from(
error_message,
)))
}
"InternalErrorException" => {
return RusotoError::Service(GetProductsError::InternalError(String::from(
error_message,
)))
}
"InvalidNextTokenException" => {
return RusotoError::Service(GetProductsError::InvalidNextToken(String::from(
error_message,
)))
}
"InvalidParameterException" => {
return RusotoError::Service(GetProductsError::InvalidParameter(String::from(
error_message,
)))
}
"NotFoundException" => {
return RusotoError::Service(GetProductsError::NotFound(String::from(
error_message,
)))
}
"ValidationException" => return RusotoError::Validation(error_message.to_string()),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetProductsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetProductsError {
fn description(&self) -> &str {
match *self {
GetProductsError::ExpiredNextToken(ref cause) => cause,
GetProductsError::InternalError(ref cause) => cause,
GetProductsError::InvalidNextToken(ref cause) => cause,
GetProductsError::InvalidParameter(ref cause) => cause,
GetProductsError::NotFound(ref cause) => cause,
}
}
}
pub trait Pricing {
fn describe_services(
&self,
input: DescribeServicesRequest,
) -> RusotoFuture<DescribeServicesResponse, DescribeServicesError>;
fn get_attribute_values(
&self,
input: GetAttributeValuesRequest,
) -> RusotoFuture<GetAttributeValuesResponse, GetAttributeValuesError>;
fn get_products(
&self,
input: GetProductsRequest,
) -> RusotoFuture<GetProductsResponse, GetProductsError>;
}
#[derive(Clone)]
pub struct PricingClient {
client: Client,
region: region::Region,
}
impl PricingClient {
pub fn new(region: region::Region) -> PricingClient {
PricingClient {
client: Client::shared(),
region: region,
}
}
pub fn new_with<P, D>(
request_dispatcher: D,
credentials_provider: P,
region: region::Region,
) -> PricingClient
where
P: ProvideAwsCredentials + Send + Sync + 'static,
P::Future: Send,
D: DispatchSignedRequest + Send + Sync + 'static,
D::Future: Send,
{
PricingClient {
client: Client::new_with(credentials_provider, request_dispatcher),
region: region,
}
}
}
impl Pricing for PricingClient {
fn describe_services(
&self,
input: DescribeServicesRequest,
) -> RusotoFuture<DescribeServicesResponse, DescribeServicesError> {
let mut request = SignedRequest::new("POST", "pricing", &self.region, "/");
request.set_endpoint_prefix("api.pricing".to_string());
request.set_content_type("application/x-amz-json-1.1".to_owned());
request.add_header("x-amz-target", "AWSPriceListService.DescribeServices");
let encoded = serde_json::to_string(&input).unwrap();
request.set_payload(Some(encoded.into_bytes()));
self.client.sign_and_dispatch(request, |response| {
if response.status.is_success() {
Box::new(response.buffer().from_err().map(|response| {
let mut body = response.body;
if body.is_empty() || body == b"null" {
body = b"{}".to_vec();
}
serde_json::from_str::<DescribeServicesResponse>(
String::from_utf8_lossy(body.as_ref()).as_ref(),
)
.unwrap()
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DescribeServicesError::from_response(response))),
)
}
})
}
fn get_attribute_values(
&self,
input: GetAttributeValuesRequest,
) -> RusotoFuture<GetAttributeValuesResponse, GetAttributeValuesError> {
let mut request = SignedRequest::new("POST", "pricing", &self.region, "/");
request.set_endpoint_prefix("api.pricing".to_string());
request.set_content_type("application/x-amz-json-1.1".to_owned());
request.add_header("x-amz-target", "AWSPriceListService.GetAttributeValues");
let encoded = serde_json::to_string(&input).unwrap();
request.set_payload(Some(encoded.into_bytes()));
self.client.sign_and_dispatch(request, |response| {
if response.status.is_success() {
Box::new(response.buffer().from_err().map(|response| {
let mut body = response.body;
if body.is_empty() || body == b"null" {
body = b"{}".to_vec();
}
serde_json::from_str::<GetAttributeValuesResponse>(
String::from_utf8_lossy(body.as_ref()).as_ref(),
)
.unwrap()
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetAttributeValuesError::from_response(response))),
)
}
})
}
fn get_products(
&self,
input: GetProductsRequest,
) -> RusotoFuture<GetProductsResponse, GetProductsError> {
let mut request = SignedRequest::new("POST", "pricing", &self.region, "/");
request.set_endpoint_prefix("api.pricing".to_string());
request.set_content_type("application/x-amz-json-1.1".to_owned());
request.add_header("x-amz-target", "AWSPriceListService.GetProducts");
let encoded = serde_json::to_string(&input).unwrap();
request.set_payload(Some(encoded.into_bytes()));
self.client.sign_and_dispatch(request, |response| {
if response.status.is_success() {
Box::new(response.buffer().from_err().map(|response| {
let mut body = response.body;
if body.is_empty() || body == b"null" {
body = b"{}".to_vec();
}
serde_json::from_str::<GetProductsResponse>(
String::from_utf8_lossy(body.as_ref()).as_ref(),
)
.unwrap()
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetProductsError::from_response(response))),
)
}
})
}
}
#[cfg(test)]
mod protocol_tests {}