From 415edb89ee256a9d7257420388af03ec7404da36 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Thu, 3 May 2018 12:01:44 +0100 Subject: [PATCH] [rust-server] Enhance middleware support (+ perf fix) (#8114) * Revert change to use a new hyper client on every request * Fix some formatting * Update sample after fixing formatting * Add constant with API version * Use semver::Version for ApiVersion * Go back to API version as a string * Rust composite services * added context type parameter to API trait * use Has trait * added context type parameter to Service and Client structs * made AuthData in Context an option in client * updated client example using generic contexts * added generic context parameters in server/auth * use ExtendsWith with associated types * added (fake) X-Span-ID in auth::Service * updated server example with generic contexts * use real X-Span-ID in auth wrapper service and remove from main server code * only require Has> if API has auth methods * tidy up swagger imports * Actually use the version from the swagger file * remove old comments * add AuthData/Authorization requirements only when AuthMethods are present * updated auth to use new version of the Has trait * update example code to use new Has trait * updated examples to use version of AllowAllAuthenticator that consumes AuthData * update examples to use macros for constructing contexts * use new versions of context traits * autogen sample * rename EmpContext to EmptyContext * fix indentation * remove unecessary uses of Context, and rename existing ones to ContextBuilder * replace Has::::get(&context) with (&context as &Has).get() * remove github dependency for swagger-rs * tidy up swagger entry in Cargo.toml * Update to swagger-rs 0.12.0, and remove warning-inducing extra parentheses * Update petstore examples * Bump to swagger-rs 0.12.1 --- .../main/resources/rust-server/Cargo.mustache | 2 +- .../resources/rust-server/client-mod.mustache | 41 +- .../rust-server/example-client.mustache | 10 +- .../rust-server/example-server.mustache | 5 +- .../rust-server/example-server_lib.mustache | 22 +- .../example-server_server.mustache | 20 +- .../main/resources/rust-server/lib.mustache | 18 +- .../rust-server/server-auth.mustache | 80 +++- .../resources/rust-server/server-mod.mustache | 61 ++- run-in-docker.sh | 2 +- .../server/petstore/rust-server/Cargo.toml | 2 +- samples/server/petstore/rust-server/README.md | 4 +- .../petstore/rust-server/api/swagger.yaml | 2 + .../petstore/rust-server/examples/client.rs | 84 ++-- .../petstore/rust-server/examples/server.rs | 5 +- .../rust-server/examples/server_lib/mod.rs | 22 +- .../rust-server/examples/server_lib/server.rs | 146 +++--- .../petstore/rust-server/src/client/mod.rs | 358 +++++++------- .../server/petstore/rust-server/src/lib.rs | 108 ++--- .../petstore/rust-server/src/mimetypes.rs | 8 +- .../petstore/rust-server/src/server/auth.rs | 80 +++- .../petstore/rust-server/src/server/mod.rs | 436 +++++++----------- 22 files changed, 772 insertions(+), 744 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/rust-server/Cargo.mustache b/modules/swagger-codegen/src/main/resources/rust-server/Cargo.mustache index 787d5c72ce8..c52c1e88977 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/Cargo.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/Cargo.mustache @@ -19,7 +19,7 @@ chrono = { version = "0.4", features = ["serde"] } futures = "0.1" hyper = {version = "0.11", optional = true} hyper-tls = {version = "0.1.2", optional = true} -swagger = "0.10.0" +swagger = "0.12.1" # Not required by example server. # diff --git a/modules/swagger-codegen/src/main/resources/rust-server/client-mod.mustache b/modules/swagger-codegen/src/main/resources/rust-server/client-mod.mustache index 9ed53c0b807..12768e25f30 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/client-mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/client-mod.mustache @@ -38,7 +38,7 @@ use std::collections::{HashMap, BTreeMap}; #[allow(unused_imports)] use swagger; -use swagger::{Context, ApiError, XSpanId}; +use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData}; use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} @@ -67,8 +67,7 @@ fn into_base_path(input: &str, correct_scheme: Option<&'static str>) -> Result Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, - handle: Arc, + hyper_client: Arc, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>>>, base_path: String, } @@ -173,25 +172,13 @@ impl Client { where C: hyper::client::Connect + hyper::client::Service, { - let hyper_client = { - move |handle: &Handle| -> Box< - hyper::client::Service< - Request = hyper::Request, - Response = hyper::Response, - Error = hyper::Error, - Future = hyper::client::FutureResponse, - >, - > { - let connector = connector_fn(handle); - Box::new(hyper::Client::configure().connector(connector).build( - handle, - )) - } - }; + let connector = connector_fn(&handle); + let hyper_client = Box::new(hyper::Client::configure().connector(connector).build( + &handle, + )); Ok(Client { hyper_client: Arc::new(hyper_client), - handle: Arc::new(handle), base_path: into_base_path(base_path, protocol)?, }) } @@ -205,22 +192,21 @@ impl Client { /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. /// This is not a recommended way to write new tests. If other reasons are found for using this function, they /// should be mentioned here. - pub fn try_new_with_hyper_client(hyper_client: Arc Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, + pub fn try_new_with_hyper_client(hyper_client: Arc, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>>>, handle: Handle, base_path: &str) -> Result { Ok(Client { hyper_client: hyper_client, - handle: Arc::new(handle), base_path: into_base_path(base_path, None)?, }) } } -impl Api for Client { +impl Api for Client where C: Has {{#hasAuthMethods}}+ Has>{{/hasAuthMethods}}{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box> { + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &C) -> Box> { {{#queryParams}}{{#-first}} // Query parameters {{/-first}}{{#required}} let query_{{paramName}} = format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=param_{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}}); @@ -306,9 +292,9 @@ impl Api for Client { request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone())); {{/bodyParam}} - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); -{{#authMethods}}{{#isBasic}} context.auth_data.as_ref().map(|auth_data| { - if let &swagger::AuthData::Basic(ref basic_header) = auth_data { + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); +{{#authMethods}}{{#isBasic}} (context as &Has>).get().as_ref().map(|auth_data| { + if let &AuthData::Basic(ref basic_header) = auth_data { request.headers_mut().set(hyper::header::Authorization( basic_header.clone(), )) @@ -326,8 +312,7 @@ impl Api for Client { request.set_body(body_string.into_bytes()); {{/hasFile}}{{/vendorExtensions}} - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-client.mustache b/modules/swagger-codegen/src/main/resources/rust-server/example-client.mustache index 2245ae47562..0620589c60e 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/example-client.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-client.mustache @@ -4,12 +4,15 @@ extern crate {{externCrateName}}; #[allow(unused_extern_crates)] extern crate futures; #[allow(unused_extern_crates)] +#[macro_use] extern crate swagger; #[allow(unused_extern_crates)] extern crate uuid; extern crate clap; extern crate tokio_core; +use swagger::{ContextBuilder, EmptyContext, XSpanIdString, Has, Push, AuthData}; + #[allow(unused_imports)] use futures::{Future, future, Stream, stream}; use tokio_core::reactor; @@ -60,15 +63,16 @@ fn main() { .expect("Failed to create HTTP client") }; - // Using a non-default `Context` is not required; this is just an example! - let client = client.with_context({{externCrateName}}::Context::new_with_span_id(self::uuid::Uuid::new_v4().to_string())); + let context: make_context_ty!(ContextBuilder, EmptyContext, Option, XSpanIdString) = + make_context!(ContextBuilder, EmptyContext, None, XSpanIdString(self::uuid::Uuid::new_v4().to_string())); + let client = client.with_context(context); match matches.value_of("operation") { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#vendorExtensions}}{{#noClientExample}}// Disabled because there's no example. // {{/noClientExample}}Some("{{operationId}}") => { {{#noClientExample}}// {{/noClientExample}} let result = core.run(client.{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^-first}}, {{/-first}}{{#vendorExtensions}}{{{example}}}{{/vendorExtensions}}{{/allParams}})); - {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); {{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} }, {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} _ => { diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-server.mustache b/modules/swagger-codegen/src/main/resources/rust-server/example-server.mustache index ee99d434bb3..0dbc3cacca0 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/example-server.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-server.mustache @@ -29,6 +29,7 @@ use hyper::server::Http; use tokio_proto::TcpServer; use clap::{App, Arg}; use swagger::auth::AllowAllAuthenticator; +use swagger::EmptyContext; mod server_lib; @@ -54,9 +55,9 @@ fn main() { .get_matches(); let service_fn = - {{externCrateName}}::server::auth::NewService::new( + {{externCrateName}}::server::auth::NewService::<_, EmptyContext>::new( AllowAllAuthenticator::new( - server_lib::NewService, + server_lib::NewService::new(), "cosmo" ) ); diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-server_lib.mustache b/modules/swagger-codegen/src/main/resources/rust-server/example-server_lib.mustache index d02d0525b47..761d3e6b07f 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/example-server_lib.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-server_lib.mustache @@ -8,19 +8,31 @@ mod errors { pub use self::errors::*; use std::io; +use std::clone::Clone; +use std::marker::PhantomData; use hyper; use {{externCrateName}}; +use swagger::{Has, XSpanIdString}; +use swagger::auth::Authorization; -pub struct NewService; +pub struct NewService{ + marker: PhantomData +} + +impl NewService{ + pub fn new() -> Self { + NewService{marker:PhantomData} + } +} -impl hyper::server::NewService for NewService { - type Request = (hyper::Request, {{externCrateName}}::Context); +impl hyper::server::NewService for NewService where C: Has {{#hasAuthMethods}}+ Has>{{/hasAuthMethods}} + Clone + 'static { + type Request = (hyper::Request, C); type Response = hyper::Response; type Error = hyper::Error; - type Instance = {{externCrateName}}::server::Service; + type Instance = {{externCrateName}}::server::Service, C>; /// Instantiate a new server. fn new_service(&self) -> io::Result { - Ok({{externCrateName}}::server::Service::new(server::Server)) + Ok({{externCrateName}}::server::Service::new(server::Server::new())) } } diff --git a/modules/swagger-codegen/src/main/resources/rust-server/example-server_server.mustache b/modules/swagger-codegen/src/main/resources/rust-server/example-server_server.mustache index fdb7ceaf541..c5122fcefac 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/example-server_server.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/example-server_server.mustache @@ -7,23 +7,33 @@ use chrono; {{#apiHasFile}}use futures::Stream;{{/apiHasFile}} use std::collections::HashMap; {{#apiHasFile}}use std::io::Error;{{/apiHasFile}} +use std::marker::PhantomData; {{#apiUsesUuid}}use uuid;{{/apiUsesUuid}} use swagger; +use swagger::{Has, XSpanIdString}; -use {{externCrateName}}::{Api, ApiError, Context{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, +use {{externCrateName}}::{Api, ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, {{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} }; use {{externCrateName}}::models; #[derive(Copy, Clone)] -pub struct Server; +pub struct Server { + marker: PhantomData, +} + +impl Server { + pub fn new() -> Self { + Server{marker: PhantomData} + } +} -impl Api for Server { +impl Api for Server where C: Has{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#summary}} /// {{{summary}}}{{/summary}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box> { + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &C) -> Box> { let context = context.clone(); - println!("{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^isFile}}{{#vendorExtensions}}{{{formatString}}}{{/vendorExtensions}}{{#hasMore}}, {{/hasMore}}{{/isFile}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}{{^isFile}}, {{paramName}}{{/isFile}}{{/allParams}}, context.x_span_id.unwrap_or(String::from("")).clone());{{#allParams}}{{#isFile}} + println!("{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^isFile}}{{#vendorExtensions}}{{{formatString}}}{{/vendorExtensions}}{{#hasMore}}, {{/hasMore}}{{/isFile}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}{{^isFile}}, {{paramName}}{{/isFile}}{{/allParams}}, context.get().0.clone());{{#allParams}}{{#isFile}} let _ = {{paramName}}; //Suppresses unused param warning{{/isFile}}{{/allParams}} Box::new(futures::failed("Generic failure".into())) } diff --git a/modules/swagger-codegen/src/main/resources/rust-server/lib.mustache b/modules/swagger-codegen/src/main/resources/rust-server/lib.mustache index 6c54cdda649..10cd24f4b3e 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/lib.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/lib.mustache @@ -30,7 +30,7 @@ pub use futures::Future; #[cfg(any(feature = "client", feature = "server"))] mod mimetypes; -pub use swagger::{ApiError, Context, ContextWrapper}; +pub use swagger::{ApiError, ContextWrapper}; pub const BASE_PATH: &'static str = "{{basePathWithoutHost}}"; pub const API_VERSION: &'static str = "{{appVersion}}"; @@ -48,10 +48,10 @@ pub enum {{operationId}}Response { {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} /// API -pub trait Api { +pub trait Api { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#summary}} /// {{{summary}}}{{/summary}} - fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box>; + fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &C) -> Box>; {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} } @@ -64,18 +64,18 @@ pub trait ApiNoContext { } /// Trait to extend an API to make it easy to bind it to a context. -pub trait ContextWrapperExt<'a> where Self: Sized { +pub trait ContextWrapperExt<'a, C> where Self: Sized { /// Binds this API to a context. - fn with_context(self: &'a Self, context: Context) -> ContextWrapper<'a, Self>; + fn with_context(self: &'a Self, context: C) -> ContextWrapper<'a, Self, C>; } -impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T { - fn with_context(self: &'a T, context: Context) -> ContextWrapper<'a, T> { - ContextWrapper::::new(self, context) +impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { + fn with_context(self: &'a T, context: C) -> ContextWrapper<'a, T, C> { + ContextWrapper::::new(self, context) } } -impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { +impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} {{#summary}} /// {{{summary}}}{{/summary}} fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box> { diff --git a/modules/swagger-codegen/src/main/resources/rust-server/server-auth.mustache b/modules/swagger-codegen/src/main/resources/rust-server/server-auth.mustache index 5f2884cf8aa..24e08ff44d9 100644 --- a/modules/swagger-codegen/src/main/resources/rust-server/server-auth.mustache +++ b/modules/swagger-codegen/src/main/resources/rust-server/server-auth.mustache @@ -1,25 +1,47 @@ use std::io; +use std::marker::PhantomData; +use std::default::Default; use hyper; use hyper::{Request, Response, Error, StatusCode}; use server::url::form_urlencoded; use swagger::auth::{Authorization, AuthData, Scopes}; +use swagger::{Has, Pop, Push, XSpanIdString}; use Api; -pub struct NewService where T: hyper::server::NewService), Response=Response, Error=Error> { +pub struct NewService + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::NewService>>::Result), Response = Response, Error = Error>, +{ inner: T, + marker: PhantomData, } -impl NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { - pub fn new(inner: T) -> NewService { - NewService{inner} +impl NewService + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::NewService>>::Result), Response = Response, Error = Error> + 'static, +{ + pub fn new(inner: T) -> NewService { + NewService { + inner, + marker: PhantomData, + } } } -impl hyper::server::NewService for NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { +impl hyper::server::NewService for NewService + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::NewService>>::Result), Response = Response, Error = Error> + 'static, +{ type Request = Request; type Response = Response; type Error = Error; - type Instance = Service; + type Instance = Service; fn new_service(&self) -> Result { self.inner.new_service().map(|s| Service::new(s)) @@ -27,23 +49,44 @@ impl hyper::server::NewService for NewService where T: hyper::server::NewS } /// Middleware to extract authentication data from request -pub struct Service where T: hyper::server::Service), Response=Response, Error=Error> { +pub struct Service + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::Service>>::Result), Response = Response, Error = Error>, +{ inner: T, + marker: PhantomData, } -impl Service where T: hyper::server::Service), Response=Response, Error=Error> { - pub fn new(inner: T) -> Service { - Service{inner} +impl Service + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::Service>>::Result), Response = Response, Error = Error>, +{ + pub fn new(inner: T) -> Service { + Service { + inner, + marker: PhantomData, + } } } -impl hyper::server::Service for Service where T: hyper::server::Service), Response=Response, Error=Error> { +impl hyper::server::Service for Service + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::Service>>::Result), Response = Response, Error = Error>, +{ type Request = Request; type Response = Response; type Error = Error; type Future = T::Future; fn call(&self, req: Self::Request) -> Self::Future { + let context = C::default().push(XSpanIdString::get_or_generate(&req)); + {{#authMethods}} {{#isBasic}} { @@ -51,7 +94,8 @@ impl hyper::server::Service for Service where T: hyper::server::Service>().cloned() { let auth_data = AuthData::Basic(basic.deref().clone()); - return self.inner.call((req, Some(auth_data))); + let context = context.push(Some(auth_data)); + return self.inner.call((req, context)); } } {{/isBasic}} @@ -61,7 +105,8 @@ impl hyper::server::Service for Service where T: hyper::server::Service>().cloned() { let auth_data = AuthData::Bearer(bearer.deref().clone()); - return self.inner.call((req, Some(auth_data))); + let context = context.push(Some(auth_data)); + return self.inner.call((req, context)); } } {{/isOAuth}} @@ -71,7 +116,8 @@ impl hyper::server::Service for Service where T: hyper::server::Service [String] } if let Some(header) = req.headers().get::().cloned() { let auth_data = AuthData::ApiKey(header.0); - return self.inner.call((req, Some(auth_data))); + let context = context.push(Some(auth_data)); + return self.inner.call((req, context)); } } {{/isKeyInHeader}} @@ -83,13 +129,15 @@ impl hyper::server::Service for Service where T: hyper::server::Service { +pub struct NewService { api_impl: Arc, + marker: PhantomData, } -impl NewService where T: Api + Clone + 'static { - pub fn new>>(api_impl: U) -> NewService { - NewService{api_impl: api_impl.into()} +impl NewService +where + T: Api + Clone + 'static, + C: Has {{#hasAuthMethods}}+ Has>{{/hasAuthMethods}} + 'static +{ + pub fn new>>(api_impl: U) -> NewService { + NewService{api_impl: api_impl.into(), marker: PhantomData} } } -impl hyper::server::NewService for NewService where T: Api + Clone + 'static { - type Request = (Request, Context); +impl hyper::server::NewService for NewService +where + T: Api + Clone + 'static, + C: Has {{#hasAuthMethods}}+ Has>{{/hasAuthMethods}} + 'static +{ + type Request = (Request, C); type Response = Response; type Error = Error; - type Instance = Service; + type Instance = Service; fn new_service(&self) -> Result { Ok(Service::new(self.api_impl.clone())) } } -pub struct Service { +pub struct Service { api_impl: Arc, + marker: PhantomData, } -impl Service where T: Api + Clone + 'static { - pub fn new>>(api_impl: U) -> Service { - Service{api_impl: api_impl.into()} +impl Service +where + T: Api + Clone + 'static, + C: Has {{#hasAuthMethods}}+ Has>{{/hasAuthMethods}} + 'static { + pub fn new>>(api_impl: U) -> Service { + Service{api_impl: api_impl.into(), marker: PhantomData} } } -impl hyper::server::Service for Service where T: Api + Clone + 'static { - type Request = (Request, Context); +impl hyper::server::Service for Service +where + T: Api + Clone + 'static, + C: Has {{#hasAuthMethods}}+ Has>{{/hasAuthMethods}} + 'static +{ + type Request = (Request, C); type Response = Response; type Error = Error; type Future = Box>; @@ -113,14 +131,11 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} // {{operationId}} - {{httpMethod}} {{path}} &hyper::Method::{{vendorExtensions.HttpMethod}} if path.matched(paths::ID_{{vendorExtensions.PATH_ID}}) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } {{#hasAuthMethods}} { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -304,7 +319,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { {{^required}}{{#isFile}} let param_{{paramName}} = Box::new(future::ok(param_{{paramName}}));{{/isFile}}{{/required}} {{/formParams}} {{/hasFile}}{{^hasFile}} - Box::new(({ + Box::new({ {{ {{#formParams}}{{#-first}} // Form parameters @@ -315,7 +330,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}param_{{paramName}}{{#isListContainer}}.as_ref(){{/isListContainer}}, {{/allParams}}&context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); {{#bodyParams}}{{#vendorExtensions}}{{^consumesPlainText}} if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -410,7 +425,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) {{^bodyParams}}{{#vendorExtensions}}{{^hasFile}} }} - })) as Box> + }) as Box> {{/hasFile}}{{#hasFile}} as Box> }, diff --git a/run-in-docker.sh b/run-in-docker.sh index b762ecde368..6777d9a31b5 100755 --- a/run-in-docker.sh +++ b/run-in-docker.sh @@ -11,7 +11,7 @@ docker run --rm -it \ -w /gen \ -e GEN_DIR=/gen \ -e MAVEN_CONFIG=/var/maven/.m2 \ - -u "$(id -u):$(id -g)" \ + -u "$(id -u):$(id -g)" \ -v "${PWD}:/gen" \ -v "${maven_cache_repo}:/var/maven/.m2/repository" \ --entrypoint /gen/docker-entrypoint.sh \ diff --git a/samples/server/petstore/rust-server/Cargo.toml b/samples/server/petstore/rust-server/Cargo.toml index 6b264cc4709..45eb703c531 100644 --- a/samples/server/petstore/rust-server/Cargo.toml +++ b/samples/server/petstore/rust-server/Cargo.toml @@ -17,7 +17,7 @@ chrono = { version = "0.4", features = ["serde"] } futures = "0.1" hyper = {version = "0.11", optional = true} hyper-tls = {version = "0.1.2", optional = true} -swagger = "0.10.0" +swagger = "0.12.1" # Not required by example server. # diff --git a/samples/server/petstore/rust-server/README.md b/samples/server/petstore/rust-server/README.md index 7080b7d2e49..aaab3324407 100644 --- a/samples/server/petstore/rust-server/README.md +++ b/samples/server/petstore/rust-server/README.md @@ -13,7 +13,7 @@ To see how to make this your own, look here: [README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) - API version: 1.0.0 -- Build date: 2018-04-03T12:24:00.479+01:00 +- Build date: 2018-05-01T11:10:37.702+01:00 This autogenerated project defines an API crate `petstore_api` which contains: * An `Api` trait defining the API in Rust. @@ -57,11 +57,11 @@ To run a client, follow one of the following simple steps: ``` cargo run --example client TestSpecialTags -cargo run --example client TestBodyWithQueryParams cargo run --example client FakeOuterBooleanSerialize cargo run --example client FakeOuterCompositeSerialize cargo run --example client FakeOuterNumberSerialize cargo run --example client FakeOuterStringSerialize +cargo run --example client TestBodyWithQueryParams cargo run --example client TestClientModel cargo run --example client TestEndpointParameters cargo run --example client TestEnumParameters diff --git a/samples/server/petstore/rust-server/api/swagger.yaml b/samples/server/petstore/rust-server/api/swagger.yaml index 3849ef4c25a..4f9447bc93f 100644 --- a/samples/server/petstore/rust-server/api/swagger.yaml +++ b/samples/server/petstore/rust-server/api/swagger.yaml @@ -1482,6 +1482,8 @@ paths: noClientExample: true /fake/body-with-query-params: put: + tags: + - "fake" operationId: "testBodyWithQueryParams" consumes: - "application/json" diff --git a/samples/server/petstore/rust-server/examples/client.rs b/samples/server/petstore/rust-server/examples/client.rs index 2b2f69d1179..c36fd704dbb 100644 --- a/samples/server/petstore/rust-server/examples/client.rs +++ b/samples/server/petstore/rust-server/examples/client.rs @@ -4,12 +4,15 @@ extern crate petstore_api; #[allow(unused_extern_crates)] extern crate futures; #[allow(unused_extern_crates)] +#[macro_use] extern crate swagger; #[allow(unused_extern_crates)] extern crate uuid; extern crate clap; extern crate tokio_core; +use swagger::{ContextBuilder, EmptyContext, XSpanIdString, Has, Push, AuthData}; + #[allow(unused_imports)] use futures::{Future, future, Stream, stream}; use tokio_core::reactor; @@ -17,11 +20,11 @@ use tokio_core::reactor; use petstore_api::{ApiNoContext, ContextWrapperExt, ApiError, TestSpecialTagsResponse, - TestBodyWithQueryParamsResponse, FakeOuterBooleanSerializeResponse, FakeOuterCompositeSerializeResponse, FakeOuterNumberSerializeResponse, FakeOuterStringSerializeResponse, + TestBodyWithQueryParamsResponse, TestClientModelResponse, TestEndpointParametersResponse, TestEnumParametersResponse, @@ -112,179 +115,180 @@ fn main() { .expect("Failed to create HTTP client") }; - // Using a non-default `Context` is not required; this is just an example! - let client = client.with_context(petstore_api::Context::new_with_span_id(self::uuid::Uuid::new_v4().to_string())); + let context: make_context_ty!(ContextBuilder, EmptyContext, Option, XSpanIdString) = + make_context!(ContextBuilder, EmptyContext, None, XSpanIdString(self::uuid::Uuid::new_v4().to_string())); + let client = client.with_context(context); match matches.value_of("operation") { // Disabled because there's no example. // Some("TestSpecialTags") => { // let result = core.run(client.test_special_tags(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); - // }, - - // Disabled because there's no example. - // Some("TestBodyWithQueryParams") => { - // let result = core.run(client.test_body_with_query_params(???, "query_example".to_string())); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, Some("FakeOuterBooleanSerialize") => { let result = core.run(client.fake_outer_boolean_serialize(None)); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterCompositeSerialize") => { let result = core.run(client.fake_outer_composite_serialize(None)); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterNumberSerialize") => { let result = core.run(client.fake_outer_number_serialize(None)); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterStringSerialize") => { let result = core.run(client.fake_outer_string_serialize(None)); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, + // Disabled because there's no example. + // Some("TestBodyWithQueryParams") => { + // let result = core.run(client.test_body_with_query_params(???, "query_example".to_string())); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, + // Disabled because there's no example. // Some("TestClientModel") => { // let result = core.run(client.test_client_model(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, Some("TestEndpointParameters") => { let result = core.run(client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("B")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("B"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string()))); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("TestEnumParameters") => { let result = core.run(client.test_enum_parameters(Some(&Vec::new()), Some("enum_form_string_example".to_string()), Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2))); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, // Disabled because there's no example. // Some("TestInlineAdditionalProperties") => { // let result = core.run(client.test_inline_additional_properties(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, Some("TestJsonFormData") => { let result = core.run(client.test_json_form_data("param_example".to_string(), "param2_example".to_string())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, // Disabled because there's no example. // Some("TestClassname") => { // let result = core.run(client.test_classname(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, // Disabled because there's no example. // Some("AddPet") => { // let result = core.run(client.add_pet(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, Some("DeletePet") => { let result = core.run(client.delete_pet(789, Some("api_key_example".to_string()))); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FindPetsByStatus") => { let result = core.run(client.find_pets_by_status(&Vec::new())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FindPetsByTags") => { let result = core.run(client.find_pets_by_tags(&Vec::new())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("GetPetById") => { let result = core.run(client.get_pet_by_id(789)); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, // Disabled because there's no example. // Some("UpdatePet") => { // let result = core.run(client.update_pet(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, Some("UpdatePetWithForm") => { let result = core.run(client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string()))); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("UploadFile") => { let result = core.run(client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box + Send>))) as Box + Send>)); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("DeleteOrder") => { let result = core.run(client.delete_order("order_id_example".to_string())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("GetInventory") => { let result = core.run(client.get_inventory()); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("GetOrderById") => { let result = core.run(client.get_order_by_id(789)); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, // Disabled because there's no example. // Some("PlaceOrder") => { // let result = core.run(client.place_order(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, // Disabled because there's no example. // Some("CreateUser") => { // let result = core.run(client.create_user(???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, Some("CreateUsersWithArrayInput") => { let result = core.run(client.create_users_with_array_input(&Vec::new())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("CreateUsersWithListInput") => { let result = core.run(client.create_users_with_list_input(&Vec::new())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("DeleteUser") => { let result = core.run(client.delete_user("username_example".to_string())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("GetUserByName") => { let result = core.run(client.get_user_by_name("username_example".to_string())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("LoginUser") => { let result = core.run(client.login_user("username_example".to_string(), "password_example".to_string())); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("LogoutUser") => { let result = core.run(client.logout_user()); - println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, // Disabled because there's no example. // Some("UpdateUser") => { // let result = core.run(client.update_user("username_example".to_string(), ???)); - // println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from(""))); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); // }, _ => { diff --git a/samples/server/petstore/rust-server/examples/server.rs b/samples/server/petstore/rust-server/examples/server.rs index 65b48aced82..f3846ade0ea 100644 --- a/samples/server/petstore/rust-server/examples/server.rs +++ b/samples/server/petstore/rust-server/examples/server.rs @@ -29,6 +29,7 @@ use hyper::server::Http; use tokio_proto::TcpServer; use clap::{App, Arg}; use swagger::auth::AllowAllAuthenticator; +use swagger::EmptyContext; mod server_lib; @@ -54,9 +55,9 @@ fn main() { .get_matches(); let service_fn = - petstore_api::server::auth::NewService::new( + petstore_api::server::auth::NewService::<_, EmptyContext>::new( AllowAllAuthenticator::new( - server_lib::NewService, + server_lib::NewService::new(), "cosmo" ) ); diff --git a/samples/server/petstore/rust-server/examples/server_lib/mod.rs b/samples/server/petstore/rust-server/examples/server_lib/mod.rs index ac79dc722b5..c4f682d6539 100644 --- a/samples/server/petstore/rust-server/examples/server_lib/mod.rs +++ b/samples/server/petstore/rust-server/examples/server_lib/mod.rs @@ -8,19 +8,31 @@ mod errors { pub use self::errors::*; use std::io; +use std::clone::Clone; +use std::marker::PhantomData; use hyper; use petstore_api; +use swagger::{Has, XSpanIdString}; +use swagger::auth::Authorization; -pub struct NewService; +pub struct NewService{ + marker: PhantomData +} + +impl NewService{ + pub fn new() -> Self { + NewService{marker:PhantomData} + } +} -impl hyper::server::NewService for NewService { - type Request = (hyper::Request, petstore_api::Context); +impl hyper::server::NewService for NewService where C: Has + Has> + Clone + 'static { + type Request = (hyper::Request, C); type Response = hyper::Response; type Error = hyper::Error; - type Instance = petstore_api::server::Service; + type Instance = petstore_api::server::Service, C>; /// Instantiate a new server. fn new_service(&self) -> io::Result { - Ok(petstore_api::server::Service::new(server::Server)) + Ok(petstore_api::server::Service::new(server::Server::new())) } } diff --git a/samples/server/petstore/rust-server/examples/server_lib/server.rs b/samples/server/petstore/rust-server/examples/server_lib/server.rs index bb3a045dcbc..5314d8b5269 100644 --- a/samples/server/petstore/rust-server/examples/server_lib/server.rs +++ b/samples/server/petstore/rust-server/examples/server_lib/server.rs @@ -7,16 +7,18 @@ use chrono; use futures::Stream; use std::collections::HashMap; use std::io::Error; +use std::marker::PhantomData; use swagger; +use swagger::{Has, XSpanIdString}; -use petstore_api::{Api, ApiError, Context, +use petstore_api::{Api, ApiError, TestSpecialTagsResponse, - TestBodyWithQueryParamsResponse, FakeOuterBooleanSerializeResponse, FakeOuterCompositeSerializeResponse, FakeOuterNumberSerializeResponse, FakeOuterStringSerializeResponse, + TestBodyWithQueryParamsResponse, TestClientModelResponse, TestEndpointParametersResponse, TestEnumParametersResponse, @@ -47,232 +49,240 @@ use petstore_api::{Api, ApiError, Context, use petstore_api::models; #[derive(Copy, Clone)] -pub struct Server; +pub struct Server { + marker: PhantomData, +} + +impl Server { + pub fn new() -> Self { + Server{marker: PhantomData} + } +} -impl Api for Server { +impl Api for Server where C: Has{ /// To test special tags - fn test_special_tags(&self, body: models::Client, context: &Context) -> Box> { + fn test_special_tags(&self, body: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box> { + fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); - println!("test_body_with_query_params({:?}, \"{}\") - X-Span-ID: {:?}", body, query, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box> { + fn fake_outer_composite_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); - println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box> { + fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); - println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box> { + fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); - println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box> { + fn test_body_with_query_params(&self, body: models::User, query: String, context: &C) -> Box> { let context = context.clone(); - println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_body_with_query_params({:?}, \"{}\") - X-Span-ID: {:?}", body, query, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// To test \"client\" model - fn test_client_model(&self, body: models::Client, context: &Context) -> Box> { + fn test_client_model(&self, body: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box> { + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &C) -> Box> { let context = context.clone(); - println!("test_endpoint_parameters({}, {}, \"{}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_endpoint_parameters({}, {}, \"{}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// To test enum parameters - fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box> { + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &C) -> Box> { let context = context.clone(); - println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// test inline additionalProperties - fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box> { + fn test_inline_additional_properties(&self, param: object, context: &C) -> Box> { let context = context.clone(); - println!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", param, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", param, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// test json serialization of form data - fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box> { + fn test_json_form_data(&self, param: String, param2: String, context: &C) -> Box> { let context = context.clone(); - println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// To test class name in snake case - fn test_classname(&self, body: models::Client, context: &Context) -> Box> { + fn test_classname(&self, body: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Add a new pet to the store - fn add_pet(&self, body: models::Pet, context: &Context) -> Box> { + fn add_pet(&self, body: models::Pet, context: &C) -> Box> { let context = context.clone(); - println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Deletes a pet - fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box> { + fn delete_pet(&self, pet_id: i64, api_key: Option, context: &C) -> Box> { let context = context.clone(); - println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Finds Pets by status - fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box> { + fn find_pets_by_status(&self, status: &Vec, context: &C) -> Box> { let context = context.clone(); - println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Finds Pets by tags - fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box> { + fn find_pets_by_tags(&self, tags: &Vec, context: &C) -> Box> { let context = context.clone(); - println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Find pet by ID - fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box> { + fn get_pet_by_id(&self, pet_id: i64, context: &C) -> Box> { let context = context.clone(); - println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Update an existing pet - fn update_pet(&self, body: models::Pet, context: &Context) -> Box> { + fn update_pet(&self, body: models::Pet, context: &C) -> Box> { let context = context.clone(); - println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Updates a pet in the store with form data - fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box> { + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &C) -> Box> { let context = context.clone(); - println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// uploads an image - fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box> { + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &C) -> Box> { let context = context.clone(); - println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.get().0.clone()); let _ = file; //Suppresses unused param warning Box::new(futures::failed("Generic failure".into())) } /// Delete purchase order by ID - fn delete_order(&self, order_id: String, context: &Context) -> Box> { + fn delete_order(&self, order_id: String, context: &C) -> Box> { let context = context.clone(); - println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Returns pet inventories by status - fn get_inventory(&self, context: &Context) -> Box> { + fn get_inventory(&self, context: &C) -> Box> { let context = context.clone(); - println!("get_inventory() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); + println!("get_inventory() - X-Span-ID: {:?}", context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Find purchase order by ID - fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box> { + fn get_order_by_id(&self, order_id: i64, context: &C) -> Box> { let context = context.clone(); - println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Place an order for a pet - fn place_order(&self, body: models::Order, context: &Context) -> Box> { + fn place_order(&self, body: models::Order, context: &C) -> Box> { let context = context.clone(); - println!("place_order({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("place_order({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Create user - fn create_user(&self, body: models::User, context: &Context) -> Box> { + fn create_user(&self, body: models::User, context: &C) -> Box> { let context = context.clone(); - println!("create_user({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("create_user({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Creates list of users with given input array - fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box> { + fn create_users_with_array_input(&self, body: &Vec, context: &C) -> Box> { let context = context.clone(); - println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Creates list of users with given input array - fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box> { + fn create_users_with_list_input(&self, body: &Vec, context: &C) -> Box> { let context = context.clone(); - println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Delete user - fn delete_user(&self, username: String, context: &Context) -> Box> { + fn delete_user(&self, username: String, context: &C) -> Box> { let context = context.clone(); - println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Get user by user name - fn get_user_by_name(&self, username: String, context: &Context) -> Box> { + fn get_user_by_name(&self, username: String, context: &C) -> Box> { let context = context.clone(); - println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Logs user into the system - fn login_user(&self, username: String, password: String, context: &Context) -> Box> { + fn login_user(&self, username: String, password: String, context: &C) -> Box> { let context = context.clone(); - println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Logs out current logged in user session - fn logout_user(&self, context: &Context) -> Box> { + fn logout_user(&self, context: &C) -> Box> { let context = context.clone(); - println!("logout_user() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("")).clone()); + println!("logout_user() - X-Span-ID: {:?}", context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Updated user - fn update_user(&self, username: String, body: models::User, context: &Context) -> Box> { + fn update_user(&self, username: String, body: models::User, context: &C) -> Box> { let context = context.clone(); - println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.x_span_id.unwrap_or(String::from("")).clone()); + println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/src/client/mod.rs b/samples/server/petstore/rust-server/src/client/mod.rs index 645907ba2d1..4347c2897df 100644 --- a/samples/server/petstore/rust-server/src/client/mod.rs +++ b/samples/server/petstore/rust-server/src/client/mod.rs @@ -38,15 +38,15 @@ use std::collections::{HashMap, BTreeMap}; #[allow(unused_imports)] use swagger; -use swagger::{Context, ApiError, XSpanId}; +use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData}; use {Api, TestSpecialTagsResponse, - TestBodyWithQueryParamsResponse, FakeOuterBooleanSerializeResponse, FakeOuterCompositeSerializeResponse, FakeOuterNumberSerializeResponse, FakeOuterStringSerializeResponse, + TestBodyWithQueryParamsResponse, TestClientModelResponse, TestEndpointParametersResponse, TestEnumParametersResponse, @@ -98,8 +98,7 @@ fn into_base_path(input: &str, correct_scheme: Option<&'static str>) -> Result Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, - handle: Arc, + hyper_client: Arc, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>>>, base_path: String, } @@ -204,25 +203,13 @@ impl Client { where C: hyper::client::Connect + hyper::client::Service, { - let hyper_client = { - move |handle: &Handle| -> Box< - hyper::client::Service< - Request = hyper::Request, - Response = hyper::Response, - Error = hyper::Error, - Future = hyper::client::FutureResponse, - >, - > { - let connector = connector_fn(handle); - Box::new(hyper::Client::configure().connector(connector).build( - handle, - )) - } - }; + let connector = connector_fn(&handle); + let hyper_client = Box::new(hyper::Client::configure().connector(connector).build( + &handle, + )); Ok(Client { hyper_client: Arc::new(hyper_client), - handle: Arc::new(handle), base_path: into_base_path(base_path, protocol)?, }) } @@ -236,22 +223,21 @@ impl Client { /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. /// This is not a recommended way to write new tests. If other reasons are found for using this function, they /// should be mentioned here. - pub fn try_new_with_hyper_client(hyper_client: Arc Box, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>, + pub fn try_new_with_hyper_client(hyper_client: Arc, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>>>, handle: Handle, base_path: &str) -> Result { Ok(Client { hyper_client: hyper_client, - handle: Arc::new(handle), base_path: into_base_path(base_path, None)?, }) } } -impl Api for Client { +impl Api for Client where C: Has + Has>{ - fn test_special_tags(&self, param_body: models::Client, context: &Context) -> Box> { + fn test_special_tags(&self, param_body: models::Client, context: &C) -> Box> { let uri = format!( @@ -274,13 +260,12 @@ impl Api for Client { request.headers_mut().set(ContentType(mimetypes::requests::TEST_SPECIAL_TAGS.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -328,16 +313,12 @@ impl Api for Client { } - fn test_body_with_query_params(&self, param_body: models::User, param_query: String, context: &Context) -> Box> { - - // Query parameters - let query_query = format!("query={query}&", query=param_query.to_string()); + fn fake_outer_boolean_serialize(&self, param_body: Option, context: &C) -> Box> { let uri = format!( - "{}/v2/fake/body-with-query-params?{query}", - self.base_path, - query=utf8_percent_encode(&query_query, QUERY_ENCODE_SET) + "{}/v2/fake/outer/boolean", + self.base_path ); let uri = match Uri::from_str(&uri) { @@ -345,23 +326,24 @@ impl Api for Client { Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), }; - let mut request = hyper::Request::new(hyper::Method::Put, uri); - - - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + let mut request = hyper::Request::new(hyper::Method::Post, uri); + let body = param_body.map(|ref body| { - request.set_body(body.into_bytes()); + serde_json::to_string(body).expect("impossible to fail to serialize") + }); +if let Some(body) = body { + request.set_body(body.into_bytes()); + } - request.headers_mut().set(ContentType(mimetypes::requests::TEST_BODY_WITH_QUERY_PARAMS.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_BOOLEAN_SERIALIZE.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -369,8 +351,19 @@ impl Api for Client { let body = response.body(); Box::new( - future::ok( - TestBodyWithQueryParamsResponse::Success + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + serde_json::from_str::(body) + .map_err(|e| e.into()) + + )) + .map(move |body| + FakeOuterBooleanSerializeResponse::OutputBoolean(body) ) ) as Box> }, @@ -398,11 +391,11 @@ impl Api for Client { } - fn fake_outer_boolean_serialize(&self, param_body: Option, context: &Context) -> Box> { + fn fake_outer_composite_serialize(&self, param_body: Option, context: &C) -> Box> { let uri = format!( - "{}/v2/fake/outer/boolean", + "{}/v2/fake/outer/composite", self.base_path ); @@ -422,14 +415,13 @@ if let Some(body) = body { request.set_body(body.into_bytes()); } - request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_BOOLEAN_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_COMPOSITE_SERIALIZE.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -444,12 +436,12 @@ if let Some(body) = body { .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) .and_then(|body| - serde_json::from_str::(body) + serde_json::from_str::(body) .map_err(|e| e.into()) )) .map(move |body| - FakeOuterBooleanSerializeResponse::OutputBoolean(body) + FakeOuterCompositeSerializeResponse::OutputComposite(body) ) ) as Box> }, @@ -477,11 +469,11 @@ if let Some(body) = body { } - fn fake_outer_composite_serialize(&self, param_body: Option, context: &Context) -> Box> { + fn fake_outer_number_serialize(&self, param_body: Option, context: &C) -> Box> { let uri = format!( - "{}/v2/fake/outer/composite", + "{}/v2/fake/outer/number", self.base_path ); @@ -501,14 +493,13 @@ if let Some(body) = body { request.set_body(body.into_bytes()); } - request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_COMPOSITE_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_NUMBER_SERIALIZE.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -523,12 +514,12 @@ if let Some(body) = body { .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) .and_then(|body| - serde_json::from_str::(body) + serde_json::from_str::(body) .map_err(|e| e.into()) )) .map(move |body| - FakeOuterCompositeSerializeResponse::OutputComposite(body) + FakeOuterNumberSerializeResponse::OutputNumber(body) ) ) as Box> }, @@ -556,11 +547,11 @@ if let Some(body) = body { } - fn fake_outer_number_serialize(&self, param_body: Option, context: &Context) -> Box> { + fn fake_outer_string_serialize(&self, param_body: Option, context: &C) -> Box> { let uri = format!( - "{}/v2/fake/outer/number", + "{}/v2/fake/outer/string", self.base_path ); @@ -580,14 +571,13 @@ if let Some(body) = body { request.set_body(body.into_bytes()); } - request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_NUMBER_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_STRING_SERIALIZE.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -602,12 +592,12 @@ if let Some(body) = body { .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) .and_then(|body| - serde_json::from_str::(body) + serde_json::from_str::(body) .map_err(|e| e.into()) )) .map(move |body| - FakeOuterNumberSerializeResponse::OutputNumber(body) + FakeOuterStringSerializeResponse::OutputString(body) ) ) as Box> }, @@ -635,12 +625,16 @@ if let Some(body) = body { } - fn fake_outer_string_serialize(&self, param_body: Option, context: &Context) -> Box> { + fn test_body_with_query_params(&self, param_body: models::User, param_query: String, context: &C) -> Box> { + + // Query parameters + let query_query = format!("query={query}&", query=param_query.to_string()); let uri = format!( - "{}/v2/fake/outer/string", - self.base_path + "{}/v2/fake/body-with-query-params?{query}", + self.base_path, + query=utf8_percent_encode(&query_query, QUERY_ENCODE_SET) ); let uri = match Uri::from_str(&uri) { @@ -648,25 +642,22 @@ if let Some(body) = body { Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), }; - let mut request = hyper::Request::new(hyper::Method::Post, uri); + let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = param_body.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") - }); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); -if let Some(body) = body { - request.set_body(body.into_bytes()); - } - request.headers_mut().set(ContentType(mimetypes::requests::FAKE_OUTER_STRING_SERIALIZE.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.set_body(body.into_bytes()); + + + request.headers_mut().set(ContentType(mimetypes::requests::TEST_BODY_WITH_QUERY_PARAMS.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -674,19 +665,8 @@ if let Some(body) = body { let body = response.body(); Box::new( - body - .concat2() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .and_then(|body| str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) - .and_then(|body| - - serde_json::from_str::(body) - .map_err(|e| e.into()) - - )) - .map(move |body| - FakeOuterStringSerializeResponse::OutputString(body) + future::ok( + TestBodyWithQueryParamsResponse::Success ) ) as Box> }, @@ -714,7 +694,7 @@ if let Some(body) = body { } - fn test_client_model(&self, param_body: models::Client, context: &Context) -> Box> { + fn test_client_model(&self, param_body: models::Client, context: &C) -> Box> { let uri = format!( @@ -737,13 +717,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_CLIENT_MODEL.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -791,7 +770,7 @@ if let Some(body) = body { } - fn test_endpoint_parameters(&self, param_number: f64, param_double: f64, param_pattern_without_delimiter: String, param_byte: swagger::ByteArray, param_integer: Option, param_int32: Option, param_int64: Option, param_float: Option, param_string: Option, param_binary: Option, param_date: Option>, param_date_time: Option>, param_password: Option, param_callback: Option, context: &Context) -> Box> { + fn test_endpoint_parameters(&self, param_number: f64, param_double: f64, param_pattern_without_delimiter: String, param_byte: swagger::ByteArray, param_integer: Option, param_int32: Option, param_int64: Option, param_float: Option, param_string: Option, param_binary: Option, param_date: Option>, param_date_time: Option>, param_password: Option, param_callback: Option, context: &C) -> Box> { let uri = format!( @@ -827,9 +806,9 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_ENDPOINT_PARAMETERS.clone())); request.set_body(body.into_bytes()); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); - context.auth_data.as_ref().map(|auth_data| { - if let &swagger::AuthData::Basic(ref basic_header) = auth_data { + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); + (context as &Has>).get().as_ref().map(|auth_data| { + if let &AuthData::Basic(ref basic_header) = auth_data { request.headers_mut().set(hyper::header::Authorization( basic_header.clone(), )) @@ -838,8 +817,7 @@ if let Some(body) = body { - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -885,7 +863,7 @@ if let Some(body) = body { } - fn test_enum_parameters(&self, param_enum_form_string_array: Option<&Vec>, param_enum_form_string: Option, param_enum_header_string_array: Option<&Vec>, param_enum_header_string: Option, param_enum_query_string_array: Option<&Vec>, param_enum_query_string: Option, param_enum_query_integer: Option, param_enum_query_double: Option, context: &Context) -> Box> { + fn test_enum_parameters(&self, param_enum_form_string_array: Option<&Vec>, param_enum_form_string: Option, param_enum_header_string_array: Option<&Vec>, param_enum_header_string: Option, param_enum_query_string_array: Option<&Vec>, param_enum_query_string: Option, param_enum_query_integer: Option, param_enum_query_double: Option, context: &C) -> Box> { // Query parameters let query_enum_query_string_array = param_enum_query_string_array.map_or_else(String::new, |query| format!("enum_query_string_array={enum_query_string_array}&", enum_query_string_array=query.join(","))); @@ -918,7 +896,7 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_ENUM_PARAMETERS.clone())); request.set_body(body.into_bytes()); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); // Header parameters header! { (RequestEnumHeaderStringArray, "enum_header_string_array") => (String)* } @@ -929,8 +907,7 @@ if let Some(body) = body { - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -976,7 +953,7 @@ if let Some(body) = body { } - fn test_inline_additional_properties(&self, param_param: object, context: &Context) -> Box> { + fn test_inline_additional_properties(&self, param_param: object, context: &C) -> Box> { let uri = format!( @@ -999,13 +976,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_INLINE_ADDITIONAL_PROPERTIES.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1042,7 +1018,7 @@ if let Some(body) = body { } - fn test_json_form_data(&self, param_param: String, param_param2: String, context: &Context) -> Box> { + fn test_json_form_data(&self, param_param: String, param_param2: String, context: &C) -> Box> { let uri = format!( @@ -1066,13 +1042,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_JSON_FORM_DATA.clone())); request.set_body(body.into_bytes()); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1109,7 +1084,7 @@ if let Some(body) = body { } - fn test_classname(&self, param_body: models::Client, context: &Context) -> Box> { + fn test_classname(&self, param_body: models::Client, context: &C) -> Box> { let uri = format!( @@ -1132,13 +1107,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_CLASSNAME.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1186,7 +1160,7 @@ if let Some(body) = body { } - fn add_pet(&self, param_body: models::Pet, context: &Context) -> Box> { + fn add_pet(&self, param_body: models::Pet, context: &C) -> Box> { let uri = format!( @@ -1209,13 +1183,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::ADD_PET.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1252,7 +1225,7 @@ if let Some(body) = body { } - fn delete_pet(&self, param_pet_id: i64, param_api_key: Option, context: &Context) -> Box> { + fn delete_pet(&self, param_pet_id: i64, param_api_key: Option, context: &C) -> Box> { let uri = format!( @@ -1269,7 +1242,7 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); // Header parameters header! { (RequestApiKey, "api_key") => [String] } @@ -1278,8 +1251,7 @@ if let Some(body) = body { - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1316,7 +1288,7 @@ if let Some(body) = body { } - fn find_pets_by_status(&self, param_status: &Vec, context: &Context) -> Box> { + fn find_pets_by_status(&self, param_status: &Vec, context: &C) -> Box> { // Query parameters let query_status = format!("status={status}&", status=param_status.join(",")); @@ -1337,13 +1309,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1402,7 +1373,7 @@ if let Some(body) = body { } - fn find_pets_by_tags(&self, param_tags: &Vec, context: &Context) -> Box> { + fn find_pets_by_tags(&self, param_tags: &Vec, context: &C) -> Box> { // Query parameters let query_tags = format!("tags={tags}&", tags=param_tags.join(",")); @@ -1423,13 +1394,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1488,7 +1458,7 @@ if let Some(body) = body { } - fn get_pet_by_id(&self, param_pet_id: i64, context: &Context) -> Box> { + fn get_pet_by_id(&self, param_pet_id: i64, context: &C) -> Box> { let uri = format!( @@ -1505,13 +1475,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1579,7 +1548,7 @@ if let Some(body) = body { } - fn update_pet(&self, param_body: models::Pet, context: &Context) -> Box> { + fn update_pet(&self, param_body: models::Pet, context: &C) -> Box> { let uri = format!( @@ -1602,13 +1571,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::UPDATE_PET.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1663,7 +1631,7 @@ if let Some(body) = body { } - fn update_pet_with_form(&self, param_pet_id: i64, param_name: Option, param_status: Option, context: &Context) -> Box> { + fn update_pet_with_form(&self, param_pet_id: i64, param_name: Option, param_status: Option, context: &C) -> Box> { let uri = format!( @@ -1687,13 +1655,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::UPDATE_PET_WITH_FORM.clone())); request.set_body(body.into_bytes()); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1730,7 +1697,7 @@ if let Some(body) = body { } - fn upload_file(&self, param_pet_id: i64, param_additional_metadata: Option, param_file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box> { + fn upload_file(&self, param_pet_id: i64, param_additional_metadata: Option, param_file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &C) -> Box> { let uri = format!( @@ -1781,7 +1748,7 @@ if let Some(body) = body { Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build multipart header: {:?}", err))))), }; - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1789,8 +1756,7 @@ if let Some(body) = body { request.set_body(body_string.into_bytes()); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1838,7 +1804,7 @@ if let Some(body) = body { } - fn delete_order(&self, param_order_id: String, context: &Context) -> Box> { + fn delete_order(&self, param_order_id: String, context: &C) -> Box> { let uri = format!( @@ -1855,13 +1821,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1907,7 +1872,7 @@ if let Some(body) = body { } - fn get_inventory(&self, context: &Context) -> Box> { + fn get_inventory(&self, context: &C) -> Box> { let uri = format!( @@ -1924,13 +1889,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -1978,7 +1942,7 @@ if let Some(body) = body { } - fn get_order_by_id(&self, param_order_id: i64, context: &Context) -> Box> { + fn get_order_by_id(&self, param_order_id: i64, context: &C) -> Box> { let uri = format!( @@ -1995,13 +1959,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2069,7 +2032,7 @@ if let Some(body) = body { } - fn place_order(&self, param_body: models::Order, context: &Context) -> Box> { + fn place_order(&self, param_body: models::Order, context: &C) -> Box> { let uri = format!( @@ -2092,13 +2055,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::PLACE_ORDER.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2157,7 +2119,7 @@ if let Some(body) = body { } - fn create_user(&self, param_body: models::User, context: &Context) -> Box> { + fn create_user(&self, param_body: models::User, context: &C) -> Box> { let uri = format!( @@ -2180,13 +2142,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::CREATE_USER.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2223,7 +2184,7 @@ if let Some(body) = body { } - fn create_users_with_array_input(&self, param_body: &Vec, context: &Context) -> Box> { + fn create_users_with_array_input(&self, param_body: &Vec, context: &C) -> Box> { let uri = format!( @@ -2246,13 +2207,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::CREATE_USERS_WITH_ARRAY_INPUT.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2289,7 +2249,7 @@ if let Some(body) = body { } - fn create_users_with_list_input(&self, param_body: &Vec, context: &Context) -> Box> { + fn create_users_with_list_input(&self, param_body: &Vec, context: &C) -> Box> { let uri = format!( @@ -2312,13 +2272,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::CREATE_USERS_WITH_LIST_INPUT.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2355,7 +2314,7 @@ if let Some(body) = body { } - fn delete_user(&self, param_username: String, context: &Context) -> Box> { + fn delete_user(&self, param_username: String, context: &C) -> Box> { let uri = format!( @@ -2372,13 +2331,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2424,7 +2382,7 @@ if let Some(body) = body { } - fn get_user_by_name(&self, param_username: String, context: &Context) -> Box> { + fn get_user_by_name(&self, param_username: String, context: &C) -> Box> { let uri = format!( @@ -2441,13 +2399,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2515,7 +2472,7 @@ if let Some(body) = body { } - fn login_user(&self, param_username: String, param_password: String, context: &Context) -> Box> { + fn login_user(&self, param_username: String, param_password: String, context: &C) -> Box> { // Query parameters let query_username = format!("username={username}&", username=param_username.to_string()); @@ -2538,13 +2495,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2613,7 +2569,7 @@ if let Some(body) = body { } - fn logout_user(&self, context: &Context) -> Box> { + fn logout_user(&self, context: &C) -> Box> { let uri = format!( @@ -2630,13 +2586,12 @@ if let Some(body) = body { - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { @@ -2673,7 +2628,7 @@ if let Some(body) = body { } - fn update_user(&self, param_username: String, param_body: models::User, context: &Context) -> Box> { + fn update_user(&self, param_username: String, param_body: models::User, context: &C) -> Box> { let uri = format!( @@ -2696,13 +2651,12 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::UPDATE_USER.clone())); - context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone()))); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); - let hyper_client = (self.hyper_client)(&*self.handle); - Box::new(hyper_client.call(request) + Box::new(self.hyper_client.call(request) .map_err(|e| ApiError(format!("No response received: {}", e))) .and_then(|mut response| { match response.status().as_u16() { diff --git a/samples/server/petstore/rust-server/src/lib.rs b/samples/server/petstore/rust-server/src/lib.rs index cdfe30c6d01..ec451c60125 100644 --- a/samples/server/petstore/rust-server/src/lib.rs +++ b/samples/server/petstore/rust-server/src/lib.rs @@ -30,7 +30,7 @@ pub use futures::Future; #[cfg(any(feature = "client", feature = "server"))] mod mimetypes; -pub use swagger::{ApiError, Context, ContextWrapper}; +pub use swagger::{ApiError, ContextWrapper}; pub const BASE_PATH: &'static str = "/v2"; pub const API_VERSION: &'static str = "1.0.0"; @@ -42,12 +42,6 @@ pub enum TestSpecialTagsResponse { SuccessfulOperation ( models::Client ) , } -#[derive(Debug, PartialEq)] -pub enum TestBodyWithQueryParamsResponse { - /// Success - Success , -} - #[derive(Debug, PartialEq)] pub enum FakeOuterBooleanSerializeResponse { /// Output boolean @@ -72,6 +66,12 @@ pub enum FakeOuterStringSerializeResponse { OutputString ( models::OuterString ) , } +#[derive(Debug, PartialEq)] +pub enum TestBodyWithQueryParamsResponse { + /// Success + Success , +} + #[derive(Debug, PartialEq)] pub enum TestClientModelResponse { /// successful operation @@ -264,103 +264,103 @@ pub enum UpdateUserResponse { /// API -pub trait Api { +pub trait Api { /// To test special tags - fn test_special_tags(&self, body: models::Client, context: &Context) -> Box>; + fn test_special_tags(&self, body: models::Client, context: &C) -> Box>; - fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box>; + fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box>; - fn fake_outer_boolean_serialize(&self, body: Option, context: &Context) -> Box>; + fn fake_outer_composite_serialize(&self, body: Option, context: &C) -> Box>; - fn fake_outer_composite_serialize(&self, body: Option, context: &Context) -> Box>; + fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box>; - fn fake_outer_number_serialize(&self, body: Option, context: &Context) -> Box>; + fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box>; - fn fake_outer_string_serialize(&self, body: Option, context: &Context) -> Box>; + fn test_body_with_query_params(&self, body: models::User, query: String, context: &C) -> Box>; /// To test \"client\" model - fn test_client_model(&self, body: models::Client, context: &Context) -> Box>; + fn test_client_model(&self, body: models::Client, context: &C) -> Box>; /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &Context) -> Box>; + fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &C) -> Box>; /// To test enum parameters - fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &Context) -> Box>; + fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec>, enum_form_string: Option, enum_header_string_array: Option<&Vec>, enum_header_string: Option, enum_query_string_array: Option<&Vec>, enum_query_string: Option, enum_query_integer: Option, enum_query_double: Option, context: &C) -> Box>; /// test inline additionalProperties - fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box>; + fn test_inline_additional_properties(&self, param: object, context: &C) -> Box>; /// test json serialization of form data - fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box>; + fn test_json_form_data(&self, param: String, param2: String, context: &C) -> Box>; /// To test class name in snake case - fn test_classname(&self, body: models::Client, context: &Context) -> Box>; + fn test_classname(&self, body: models::Client, context: &C) -> Box>; /// Add a new pet to the store - fn add_pet(&self, body: models::Pet, context: &Context) -> Box>; + fn add_pet(&self, body: models::Pet, context: &C) -> Box>; /// Deletes a pet - fn delete_pet(&self, pet_id: i64, api_key: Option, context: &Context) -> Box>; + fn delete_pet(&self, pet_id: i64, api_key: Option, context: &C) -> Box>; /// Finds Pets by status - fn find_pets_by_status(&self, status: &Vec, context: &Context) -> Box>; + fn find_pets_by_status(&self, status: &Vec, context: &C) -> Box>; /// Finds Pets by tags - fn find_pets_by_tags(&self, tags: &Vec, context: &Context) -> Box>; + fn find_pets_by_tags(&self, tags: &Vec, context: &C) -> Box>; /// Find pet by ID - fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box>; + fn get_pet_by_id(&self, pet_id: i64, context: &C) -> Box>; /// Update an existing pet - fn update_pet(&self, body: models::Pet, context: &Context) -> Box>; + fn update_pet(&self, body: models::Pet, context: &C) -> Box>; /// Updates a pet in the store with form data - fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &Context) -> Box>; + fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &C) -> Box>; /// uploads an image - fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box>; + fn upload_file(&self, pet_id: i64, additional_metadata: Option, file: Box, Error=Error> + Send>>, Error=Error> + Send>, context: &C) -> Box>; /// Delete purchase order by ID - fn delete_order(&self, order_id: String, context: &Context) -> Box>; + fn delete_order(&self, order_id: String, context: &C) -> Box>; /// Returns pet inventories by status - fn get_inventory(&self, context: &Context) -> Box>; + fn get_inventory(&self, context: &C) -> Box>; /// Find purchase order by ID - fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box>; + fn get_order_by_id(&self, order_id: i64, context: &C) -> Box>; /// Place an order for a pet - fn place_order(&self, body: models::Order, context: &Context) -> Box>; + fn place_order(&self, body: models::Order, context: &C) -> Box>; /// Create user - fn create_user(&self, body: models::User, context: &Context) -> Box>; + fn create_user(&self, body: models::User, context: &C) -> Box>; /// Creates list of users with given input array - fn create_users_with_array_input(&self, body: &Vec, context: &Context) -> Box>; + fn create_users_with_array_input(&self, body: &Vec, context: &C) -> Box>; /// Creates list of users with given input array - fn create_users_with_list_input(&self, body: &Vec, context: &Context) -> Box>; + fn create_users_with_list_input(&self, body: &Vec, context: &C) -> Box>; /// Delete user - fn delete_user(&self, username: String, context: &Context) -> Box>; + fn delete_user(&self, username: String, context: &C) -> Box>; /// Get user by user name - fn get_user_by_name(&self, username: String, context: &Context) -> Box>; + fn get_user_by_name(&self, username: String, context: &C) -> Box>; /// Logs user into the system - fn login_user(&self, username: String, password: String, context: &Context) -> Box>; + fn login_user(&self, username: String, password: String, context: &C) -> Box>; /// Logs out current logged in user session - fn logout_user(&self, context: &Context) -> Box>; + fn logout_user(&self, context: &C) -> Box>; /// Updated user - fn update_user(&self, username: String, body: models::User, context: &Context) -> Box>; + fn update_user(&self, username: String, body: models::User, context: &C) -> Box>; } @@ -371,9 +371,6 @@ pub trait ApiNoContext { fn test_special_tags(&self, body: models::Client) -> Box>; - fn test_body_with_query_params(&self, body: models::User, query: String) -> Box>; - - fn fake_outer_boolean_serialize(&self, body: Option) -> Box>; @@ -385,6 +382,9 @@ pub trait ApiNoContext { fn fake_outer_string_serialize(&self, body: Option) -> Box>; + + fn test_body_with_query_params(&self, body: models::User, query: String) -> Box>; + /// To test \"client\" model fn test_client_model(&self, body: models::Client) -> Box>; @@ -466,18 +466,18 @@ pub trait ApiNoContext { } /// Trait to extend an API to make it easy to bind it to a context. -pub trait ContextWrapperExt<'a> where Self: Sized { +pub trait ContextWrapperExt<'a, C> where Self: Sized { /// Binds this API to a context. - fn with_context(self: &'a Self, context: Context) -> ContextWrapper<'a, Self>; + fn with_context(self: &'a Self, context: C) -> ContextWrapper<'a, Self, C>; } -impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T { - fn with_context(self: &'a T, context: Context) -> ContextWrapper<'a, T> { - ContextWrapper::::new(self, context) +impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { + fn with_context(self: &'a T, context: C) -> ContextWrapper<'a, T, C> { + ContextWrapper::::new(self, context) } } -impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { +impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { /// To test special tags fn test_special_tags(&self, body: models::Client) -> Box> { @@ -485,11 +485,6 @@ impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { } - fn test_body_with_query_params(&self, body: models::User, query: String) -> Box> { - self.api().test_body_with_query_params(body, query, &self.context()) - } - - fn fake_outer_boolean_serialize(&self, body: Option) -> Box> { self.api().fake_outer_boolean_serialize(body, &self.context()) } @@ -509,6 +504,11 @@ impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { self.api().fake_outer_string_serialize(body, &self.context()) } + + fn test_body_with_query_params(&self, body: models::User, query: String) -> Box> { + self.api().test_body_with_query_params(body, query, &self.context()) + } + /// To test \"client\" model fn test_client_model(&self, body: models::Client) -> Box> { self.api().test_client_model(body, &self.context()) diff --git a/samples/server/petstore/rust-server/src/mimetypes.rs b/samples/server/petstore/rust-server/src/mimetypes.rs index 1ad0e1d9b0c..6a832052499 100644 --- a/samples/server/petstore/rust-server/src/mimetypes.rs +++ b/samples/server/petstore/rust-server/src/mimetypes.rs @@ -61,10 +61,6 @@ pub mod requests { lazy_static! { pub static ref TEST_SPECIAL_TAGS: Mime = "application/json".parse().unwrap(); } - /// Create Mime objects for the request content types for TestBodyWithQueryParams - lazy_static! { - pub static ref TEST_BODY_WITH_QUERY_PARAMS: Mime = "application/json".parse().unwrap(); - } /// Create Mime objects for the request content types for FakeOuterBooleanSerialize lazy_static! { pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = "application/json".parse().unwrap(); @@ -81,6 +77,10 @@ pub mod requests { lazy_static! { pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = "application/json".parse().unwrap(); } + /// Create Mime objects for the request content types for TestBodyWithQueryParams + lazy_static! { + pub static ref TEST_BODY_WITH_QUERY_PARAMS: Mime = "application/json".parse().unwrap(); + } /// Create Mime objects for the request content types for TestClientModel lazy_static! { pub static ref TEST_CLIENT_MODEL: Mime = "application/json".parse().unwrap(); diff --git a/samples/server/petstore/rust-server/src/server/auth.rs b/samples/server/petstore/rust-server/src/server/auth.rs index 5c120b74c7c..1c770bcf6a7 100644 --- a/samples/server/petstore/rust-server/src/server/auth.rs +++ b/samples/server/petstore/rust-server/src/server/auth.rs @@ -1,25 +1,47 @@ use std::io; +use std::marker::PhantomData; +use std::default::Default; use hyper; use hyper::{Request, Response, Error, StatusCode}; use server::url::form_urlencoded; use swagger::auth::{Authorization, AuthData, Scopes}; +use swagger::{Has, Pop, Push, XSpanIdString}; use Api; -pub struct NewService where T: hyper::server::NewService), Response=Response, Error=Error> { +pub struct NewService + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::NewService>>::Result), Response = Response, Error = Error>, +{ inner: T, + marker: PhantomData, } -impl NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { - pub fn new(inner: T) -> NewService { - NewService{inner} +impl NewService + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::NewService>>::Result), Response = Response, Error = Error> + 'static, +{ + pub fn new(inner: T) -> NewService { + NewService { + inner, + marker: PhantomData, + } } } -impl hyper::server::NewService for NewService where T: hyper::server::NewService), Response=Response, Error=Error> + 'static { +impl hyper::server::NewService for NewService + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::NewService>>::Result), Response = Response, Error = Error> + 'static, +{ type Request = Request; type Response = Response; type Error = Error; - type Instance = Service; + type Instance = Service; fn new_service(&self) -> Result { self.inner.new_service().map(|s| Service::new(s)) @@ -27,28 +49,50 @@ impl hyper::server::NewService for NewService where T: hyper::server::NewS } /// Middleware to extract authentication data from request -pub struct Service where T: hyper::server::Service), Response=Response, Error=Error> { +pub struct Service + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::Service>>::Result), Response = Response, Error = Error>, +{ inner: T, + marker: PhantomData, } -impl Service where T: hyper::server::Service), Response=Response, Error=Error> { - pub fn new(inner: T) -> Service { - Service{inner} +impl Service + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::Service>>::Result), Response = Response, Error = Error>, +{ + pub fn new(inner: T) -> Service { + Service { + inner, + marker: PhantomData, + } } } -impl hyper::server::Service for Service where T: hyper::server::Service), Response=Response, Error=Error> { +impl hyper::server::Service for Service + where + C: Default + Push, + C::Result: Push>, + T: hyper::server::Service>>::Result), Response = Response, Error = Error>, +{ type Request = Request; type Response = Response; type Error = Error; type Future = T::Future; fn call(&self, req: Self::Request) -> Self::Future { + let context = C::default().push(XSpanIdString::get_or_generate(&req)); + { header! { (ApiKey1, "api_key") => [String] } if let Some(header) = req.headers().get::().cloned() { let auth_data = AuthData::ApiKey(header.0); - return self.inner.call((req, Some(auth_data))); + let context = context.push(Some(auth_data)); + return self.inner.call((req, context)); } } { @@ -58,7 +102,8 @@ impl hyper::server::Service for Service where T: hyper::server::Service hyper::server::Service for Service where T: hyper::server::Service>().cloned() { let auth_data = AuthData::Basic(basic.deref().clone()); - return self.inner.call((req, Some(auth_data))); + let context = context.push(Some(auth_data)); + return self.inner.call((req, context)); } } { @@ -74,10 +120,12 @@ impl hyper::server::Service for Service where T: hyper::server::Service>().cloned() { let auth_data = AuthData::Bearer(bearer.deref().clone()); - return self.inner.call((req, Some(auth_data))); + let context = context.push(Some(auth_data)); + return self.inner.call((req, context)); } } - return self.inner.call((req, None)); + let context = context.push(None); + return self.inner.call((req, context)); } } diff --git a/samples/server/petstore/rust-server/src/server/mod.rs b/samples/server/petstore/rust-server/src/server/mod.rs index 7f88b6b3ad8..53f9227e621 100644 --- a/samples/server/petstore/rust-server/src/server/mod.rs +++ b/samples/server/petstore/rust-server/src/server/mod.rs @@ -13,6 +13,7 @@ extern crate url; use std::sync::Arc; +use std::marker::PhantomData; use futures::{Future, future, Stream, stream}; use hyper; use hyper::{Request, Response, Error, StatusCode}; @@ -35,16 +36,16 @@ use std::io; use std::collections::BTreeSet; pub use swagger::auth::Authorization; -use swagger::{ApiError, Context, XSpanId}; +use swagger::{ApiError, XSpanId, XSpanIdString, Has}; use swagger::auth::Scopes; use {Api, TestSpecialTagsResponse, - TestBodyWithQueryParamsResponse, FakeOuterBooleanSerializeResponse, FakeOuterCompositeSerializeResponse, FakeOuterNumberSerializeResponse, FakeOuterStringSerializeResponse, + TestBodyWithQueryParamsResponse, TestClientModelResponse, TestEndpointParametersResponse, TestEnumParametersResponse, @@ -148,39 +149,56 @@ mod paths { } } -pub struct NewService { +pub struct NewService { api_impl: Arc, + marker: PhantomData, } -impl NewService where T: Api + Clone + 'static { - pub fn new>>(api_impl: U) -> NewService { - NewService{api_impl: api_impl.into()} +impl NewService +where + T: Api + Clone + 'static, + C: Has + Has> + 'static +{ + pub fn new>>(api_impl: U) -> NewService { + NewService{api_impl: api_impl.into(), marker: PhantomData} } } -impl hyper::server::NewService for NewService where T: Api + Clone + 'static { - type Request = (Request, Context); +impl hyper::server::NewService for NewService +where + T: Api + Clone + 'static, + C: Has + Has> + 'static +{ + type Request = (Request, C); type Response = Response; type Error = Error; - type Instance = Service; + type Instance = Service; fn new_service(&self) -> Result { Ok(Service::new(self.api_impl.clone())) } } -pub struct Service { +pub struct Service { api_impl: Arc, + marker: PhantomData, } -impl Service where T: Api + Clone + 'static { - pub fn new>>(api_impl: U) -> Service { - Service{api_impl: api_impl.into()} +impl Service +where + T: Api + Clone + 'static, + C: Has + Has> + 'static { + pub fn new>>(api_impl: U) -> Service { + Service{api_impl: api_impl.into(), marker: PhantomData} } } -impl hyper::server::Service for Service where T: Api + Clone + 'static { - type Request = (Request, Context); +impl hyper::server::Service for Service +where + T: Api + Clone + 'static, + C: Has + Has> + 'static +{ + type Request = (Request, C); type Response = Response; type Error = Error; type Future = Box>; @@ -193,9 +211,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // TestSpecialTags - PATCH /another-fake/dummy &hyper::Method::Patch if path.matched(paths::ID_ANOTHER_FAKE_DUMMY) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -235,7 +250,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.test_special_tags(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -281,28 +296,12 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }, - // TestBodyWithQueryParams - PUT /fake/body-with-query-params - &hyper::Method::Put if path.matched(paths::ID_FAKE_BODY_WITH_QUERY_PARAMS) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } - - + // FakeOuterBooleanSerialize - POST /fake/outer/boolean + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_BOOLEAN) => { - // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) - let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); - let param_query = query_params.iter().filter(|e| e.0 == "query").map(|e| e.1.to_owned()) - .nth(0); - let param_query = match param_query { - Some(param_query) => match param_query.parse::() { - Ok(param_query) => param_query, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter query - doesn't match schema: {}", e)))), - }, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter query"))), - }; // Body parameters (note that non-required body parameters will ignore garbage @@ -314,7 +313,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -323,22 +322,19 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { unused_elements.push(path.to_string()); }) { Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + + Err(_) => None, } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), - }; - Box::new(api_impl.test_body_with_query_params(param_body, param_query, &context) + Box::new(api_impl.fake_outer_boolean_serialize(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -346,12 +342,18 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { match result { Ok(rsp) => match rsp { - TestBodyWithQueryParamsResponse::Success + FakeOuterBooleanSerializeResponse::OutputBoolean + + (body) => { response.set_status(StatusCode::try_from(200).unwrap()); + + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + + response.set_body(body); }, }, Err(_) => { @@ -376,11 +378,8 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }, - // FakeOuterBooleanSerialize - POST /fake/outer/boolean - &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_BOOLEAN) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } + // FakeOuterCompositeSerialize - POST /fake/outer/composite + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_COMPOSITE) => { @@ -396,7 +395,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -414,10 +413,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }; - Box::new(api_impl.fake_outer_boolean_serialize(param_body, &context) + Box::new(api_impl.fake_outer_composite_serialize(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -425,7 +424,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { match result { Ok(rsp) => match rsp { - FakeOuterBooleanSerializeResponse::OutputBoolean + FakeOuterCompositeSerializeResponse::OutputComposite (body) @@ -461,11 +460,8 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }, - // FakeOuterCompositeSerialize - POST /fake/outer/composite - &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_COMPOSITE) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } + // FakeOuterNumberSerialize - POST /fake/outer/number + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_NUMBER) => { @@ -481,7 +477,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -499,10 +495,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }; - Box::new(api_impl.fake_outer_composite_serialize(param_body, &context) + Box::new(api_impl.fake_outer_number_serialize(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -510,7 +506,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { match result { Ok(rsp) => match rsp { - FakeOuterCompositeSerializeResponse::OutputComposite + FakeOuterNumberSerializeResponse::OutputNumber (body) @@ -546,11 +542,8 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }, - // FakeOuterNumberSerialize - POST /fake/outer/number - &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_NUMBER) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } + // FakeOuterStringSerialize - POST /fake/outer/string + &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_STRING) => { @@ -566,7 +559,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -584,10 +577,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }; - Box::new(api_impl.fake_outer_number_serialize(param_body, &context) + Box::new(api_impl.fake_outer_string_serialize(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -595,7 +588,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { match result { Ok(rsp) => match rsp { - FakeOuterNumberSerializeResponse::OutputNumber + FakeOuterStringSerializeResponse::OutputString (body) @@ -631,15 +624,25 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { }, - // FakeOuterStringSerialize - POST /fake/outer/string - &hyper::Method::Post if path.matched(paths::ID_FAKE_OUTER_STRING) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } + // TestBodyWithQueryParams - PUT /fake/body-with-query-params + &hyper::Method::Put if path.matched(paths::ID_FAKE_BODY_WITH_QUERY_PARAMS) => { + + // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) + let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); + let param_query = query_params.iter().filter(|e| e.0 == "query").map(|e| e.1.to_owned()) + + .nth(0); + let param_query = match param_query { + Some(param_query) => match param_query.parse::() { + Ok(param_query) => param_query, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter query - doesn't match schema: {}", e)))), + }, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter query"))), + }; // Body parameters (note that non-required body parameters will ignore garbage @@ -651,7 +654,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -660,19 +663,22 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { unused_elements.push(path.to_string()); }) { Ok(param_body) => param_body, - - Err(_) => None, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + }; - Box::new(api_impl.fake_outer_string_serialize(param_body, &context) + Box::new(api_impl.test_body_with_query_params(param_body, param_query, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -680,18 +686,12 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { match result { Ok(rsp) => match rsp { - FakeOuterStringSerializeResponse::OutputString - - (body) + TestBodyWithQueryParamsResponse::Success => { response.set_status(StatusCode::try_from(200).unwrap()); - - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - - response.set_body(body); }, }, Err(_) => { @@ -718,9 +718,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // TestClientModel - PATCH /fake &hyper::Method::Patch if path.matched(paths::ID_FAKE) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -760,7 +757,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.test_client_model(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -808,13 +805,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // TestEndpointParameters - POST /fake &hyper::Method::Post if path.matched(paths::ID_FAKE) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -827,7 +821,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ // Form parameters @@ -849,7 +843,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.test_endpoint_parameters(param_number, param_double, param_pattern_without_delimiter, param_byte, param_integer, param_int32, param_int64, param_float, param_string, param_binary, param_date, param_date_time, param_password, param_callback, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -881,7 +875,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -889,9 +883,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // TestEnumParameters - GET /fake &hyper::Method::Get if path.matched(paths::ID_FAKE) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -926,7 +917,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ // Form parameters @@ -937,7 +928,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.test_enum_parameters(param_enum_form_string_array.as_ref(), param_enum_form_string, param_enum_header_string_array.as_ref(), param_enum_header_string, param_enum_query_string_array.as_ref(), param_enum_query_string, param_enum_query_integer, param_enum_query_double, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -969,7 +960,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -977,9 +968,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // TestInlineAdditionalProperties - POST /fake/inline-additionalProperties &hyper::Method::Post if path.matched(paths::ID_FAKE_INLINE_ADDITIONALPROPERTIES) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -1019,7 +1007,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.test_inline_additional_properties(param_param, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -1059,9 +1047,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // TestJsonFormData - GET /fake/jsonFormData &hyper::Method::Get if path.matched(paths::ID_FAKE_JSONFORMDATA) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -1069,7 +1054,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ // Form parameters @@ -1079,7 +1064,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.test_json_form_data(param_param, param_param2, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -1104,7 +1089,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -1112,13 +1097,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // TestClassname - PATCH /fake_classname_test &hyper::Method::Patch if path.matched(paths::ID_FAKE_CLASSNAME_TEST) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1163,7 +1145,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.test_classname(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -1211,13 +1193,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // AddPet - POST /pet &hyper::Method::Post if path.matched(paths::ID_PET) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1279,7 +1258,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.add_pet(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -1319,13 +1298,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // DeletePet - DELETE /pet/{petId} &hyper::Method::Delete if path.matched(paths::ID_PET_PETID) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1376,13 +1352,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.delete_pet(param_pet_id, param_api_key, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -1407,7 +1383,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -1415,13 +1391,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // FindPetsByStatus - GET /pet/findByStatus &hyper::Method::Get if path.matched(paths::ID_PET_FINDBYSTATUS) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1458,13 +1431,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.find_pets_by_status(param_status.as_ref(), &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -1504,7 +1477,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -1512,13 +1485,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // FindPetsByTags - GET /pet/findByTags &hyper::Method::Get if path.matched(paths::ID_PET_FINDBYTAGS) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1555,13 +1525,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.find_pets_by_tags(param_tags.as_ref(), &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -1601,7 +1571,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -1609,13 +1579,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // GetPetById - GET /pet/{petId} &hyper::Method::Get if path.matched(paths::ID_PET_PETID) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1644,13 +1611,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.get_pet_by_id(param_pet_id, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -1697,7 +1664,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -1705,13 +1672,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // UpdatePet - PUT /pet &hyper::Method::Put if path.matched(paths::ID_PET) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1773,7 +1737,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.update_pet(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -1827,13 +1791,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // UpdatePetWithForm - POST /pet/{petId} &hyper::Method::Post if path.matched(paths::ID_PET_PETID) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -1880,7 +1841,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ // Form parameters @@ -1890,7 +1851,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.update_pet_with_form(param_pet_id, param_name, param_status, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -1915,7 +1876,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -1923,13 +1884,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // UploadFile - POST /pet/{petId}/uploadImage &hyper::Method::Post if path.matched(paths::ID_PET_PETID_UPLOADIMAGE) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -2020,7 +1978,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.upload_file(param_pet_id, param_additional_metadata, param_file, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2065,9 +2023,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // DeleteOrder - DELETE /store/order/{order_id} &hyper::Method::Delete if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } // Path parameters @@ -2091,13 +2046,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.delete_order(param_order_id, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2129,7 +2084,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -2137,13 +2092,10 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // GetInventory - GET /store/inventory &hyper::Method::Get if path.matched(paths::ID_STORE_INVENTORY) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } { - let authorization = match context.authorization.as_ref() { - Some(authorization) => authorization, - None => return Box::new(future::ok(Response::new() + let authorization = match (&context as &Has>).get() { + &Some(ref authorization) => authorization, + &None => return Box::new(future::ok(Response::new() .with_status(StatusCode::Forbidden) .with_body("Unauthenticated"))), }; @@ -2156,13 +2108,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.get_inventory(&context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2195,7 +2147,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -2203,9 +2155,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // GetOrderById - GET /store/order/{order_id} &hyper::Method::Get if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } // Path parameters @@ -2229,13 +2178,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.get_order_by_id(param_order_id, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2282,7 +2231,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -2290,9 +2239,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // PlaceOrder - POST /store/order &hyper::Method::Post if path.matched(paths::ID_STORE_ORDER) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -2332,7 +2278,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.place_order(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -2387,9 +2333,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // CreateUser - POST /user &hyper::Method::Post if path.matched(paths::ID_USER) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -2429,7 +2372,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.create_user(param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -2469,9 +2412,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // CreateUsersWithArrayInput - POST /user/createWithArray &hyper::Method::Post if path.matched(paths::ID_USER_CREATEWITHARRAY) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -2511,7 +2451,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.create_users_with_array_input(param_body.as_ref(), &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -2551,9 +2491,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // CreateUsersWithListInput - POST /user/createWithList &hyper::Method::Post if path.matched(paths::ID_USER_CREATEWITHLIST) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -2593,7 +2530,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.create_users_with_list_input(param_body.as_ref(), &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); @@ -2633,9 +2570,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // DeleteUser - DELETE /user/{username} &hyper::Method::Delete if path.matched(paths::ID_USER_USERNAME) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } // Path parameters @@ -2659,13 +2593,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.delete_user(param_username, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2697,7 +2631,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -2705,9 +2639,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // GetUserByName - GET /user/{username} &hyper::Method::Get if path.matched(paths::ID_USER_USERNAME) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } // Path parameters @@ -2731,13 +2662,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.get_user_by_name(param_username, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2784,7 +2715,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -2792,9 +2723,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // LoginUser - GET /user/login &hyper::Method::Get if path.matched(paths::ID_USER_LOGIN) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -2825,13 +2753,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.login_user(param_username, param_password, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2880,7 +2808,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -2888,9 +2816,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // LogoutUser - GET /user/logout &hyper::Method::Get if path.matched(paths::ID_USER_LOGOUT) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } @@ -2898,13 +2823,13 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { - Box::new(({ + Box::new({ {{ Box::new(api_impl.logout_user(&context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); match result { Ok(rsp) => match rsp { @@ -2929,7 +2854,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { )) }} - })) as Box> + }) as Box> }, @@ -2937,9 +2862,6 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { // UpdateUser - PUT /user/{username} &hyper::Method::Put if path.matched(paths::ID_USER_USERNAME) => { - if context.x_span_id.is_none() { - context.x_span_id = Some(headers.get::().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string())); - } // Path parameters @@ -2995,7 +2917,7 @@ impl hyper::server::Service for Service where T: Api + Clone + 'static { Box::new(api_impl.update_user(param_username, param_body, &context) .then(move |result| { let mut response = Response::new(); - context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone()))); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); if !unused_elements.is_empty() { response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements)));