1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use futures_util::future::{self, BoxFuture, FutureExt};
use gotham::{
	handler::HandlerError,
	hyper::{
		header::{HeaderMap, HeaderName, HeaderValue},
		Body, StatusCode
	},
	mime::{Mime, APPLICATION_JSON, STAR_STAR}
};
#[cfg(feature = "openapi")]
use openapi_type::{OpenapiSchema, OpenapiType};
use serde::Serialize;
use std::{
	convert::Infallible,
	fmt::{Debug, Display},
	future::Future,
	pin::Pin
};

mod auth_result;
#[allow(unreachable_pub)]
pub use auth_result::{AuthError, AuthErrorOrOther, AuthResult, AuthSuccess};

mod no_content;
#[allow(unreachable_pub)]
pub use no_content::NoContent;

mod raw;
#[allow(unreachable_pub)]
pub use raw::Raw;

mod redirect;
#[allow(unreachable_pub)]
pub use redirect::Redirect;

mod result;
#[allow(unreachable_pub)]
pub use result::IntoResponseError;

mod success;
#[allow(unreachable_pub)]
pub use success::Success;

pub(crate) trait OrAllTypes {
	fn or_all_types(self) -> Vec<Mime>;
}

impl OrAllTypes for Option<Vec<Mime>> {
	fn or_all_types(self) -> Vec<Mime> {
		self.unwrap_or_else(|| vec![STAR_STAR])
	}
}

/// A response, used to create the final gotham response from.
///
/// This type is not meant to be used as the return type of endpoint handlers. While it can be
/// freely used without the `openapi` feature, it is more complicated to use when you enable it,
/// since this type does not store any schema information. You can attach schema information
/// like so:
///
/// ```rust
/// # #[cfg(feature = "openapi")] mod example {
/// # use gotham::hyper::StatusCode;
/// # use gotham_restful::*;
/// # use openapi_type::*;
/// fn schema(code: StatusCode) -> OpenapiSchema {
/// 	assert_eq!(code, StatusCode::ACCEPTED);
/// 	<()>::schema()
/// }
///
/// fn status_codes() -> Vec<StatusCode> {
/// 	vec![StatusCode::ACCEPTED]
/// }
///
/// #[create(schema = "schema", status_codes = "status_codes")]
/// fn create(body: Raw<Vec<u8>>) {}
/// # }
/// ```
#[derive(Debug)]
pub struct Response {
	pub(crate) status: StatusCode,
	pub(crate) body: Body,
	pub(crate) mime: Option<Mime>,
	pub(crate) headers: HeaderMap
}

impl Response {
	/// Create a new [Response] from raw data.
	#[must_use = "Creating a response is pointless if you don't use it"]
	pub fn new<B: Into<Body>>(status: StatusCode, body: B, mime: Option<Mime>) -> Self {
		Self {
			status,
			body: body.into(),
			mime,
			headers: Default::default()
		}
	}

	/// Create a [Response] with mime type json from already serialized data.
	#[must_use = "Creating a response is pointless if you don't use it"]
	pub fn json<B: Into<Body>>(status: StatusCode, body: B) -> Self {
		Self {
			status,
			body: body.into(),
			mime: Some(APPLICATION_JSON),
			headers: Default::default()
		}
	}

	/// Create a _204 No Content_ [Response].
	#[must_use = "Creating a response is pointless if you don't use it"]
	pub fn no_content() -> Self {
		Self {
			status: StatusCode::NO_CONTENT,
			body: Body::empty(),
			mime: None,
			headers: Default::default()
		}
	}

	/// Create an empty _403 Forbidden_ [Response].
	#[must_use = "Creating a response is pointless if you don't use it"]
	pub fn forbidden() -> Self {
		Self {
			status: StatusCode::FORBIDDEN,
			body: Body::empty(),
			mime: None,
			headers: Default::default()
		}
	}

	/// Return the status code of this [Response].
	pub fn status(&self) -> StatusCode {
		self.status
	}

	/// Return the mime type of this [Response].
	pub fn mime(&self) -> Option<&Mime> {
		self.mime.as_ref()
	}

	/// Add an HTTP header to the [Response].
	pub fn header(&mut self, name: HeaderName, value: HeaderValue) {
		self.headers.insert(name, value);
	}

	pub(crate) fn with_headers(mut self, headers: HeaderMap) -> Self {
		self.headers = headers;
		self
	}

	#[cfg(test)]
	pub(crate) fn full_body(
		mut self
	) -> Result<Vec<u8>, <Body as gotham::hyper::body::HttpBody>::Error> {
		use futures_executor::block_on;
		use gotham::hyper::body::to_bytes;

		let bytes: &[u8] = &block_on(to_bytes(&mut self.body))?;
		Ok(bytes.to_vec())
	}
}

impl IntoResponse for Response {
	type Err = Infallible;

	fn into_response(self) -> BoxFuture<'static, Result<Response, Self::Err>> {
		future::ok(self).boxed()
	}
}

/// This trait needs to be implemented by every type returned from an endpoint to
/// to provide the response.
pub trait IntoResponse {
	type Err: Into<HandlerError> + Send + Sync + 'static;

	/// Turn this into a response that can be returned to the browser. This api will likely
	/// change in the future.
	fn into_response(self) -> BoxFuture<'static, Result<Response, Self::Err>>;

	/// Return a list of supported mime types.
	fn accepted_types() -> Option<Vec<Mime>> {
		None
	}
}

/// Additional details for [IntoResponse] to be used with an OpenAPI-aware router.
#[cfg(feature = "openapi")]
pub trait ResponseSchema {
	/// All status codes returned by this response. Returns `[StatusCode::OK]` by default.
	fn status_codes() -> Vec<StatusCode> {
		vec![StatusCode::OK]
	}

	/// Return the schema of the response for the given status code. The code may
	/// only be one that was previously returned by [Self::status_codes]. The
	/// implementation should panic if that is not the case.
	fn schema(code: StatusCode) -> OpenapiSchema;
}

#[cfg(feature = "openapi")]
mod private {
	pub trait Sealed {}
}

/// A trait provided to convert a resource's result to json, and provide an OpenAPI schema to the
/// router. This trait is implemented for all types that implement [IntoResponse] and
/// [ResponseSchema].
#[cfg(feature = "openapi")]
pub trait IntoResponseWithSchema: IntoResponse + ResponseSchema + private::Sealed {}

#[cfg(feature = "openapi")]
impl<R: IntoResponse + ResponseSchema> private::Sealed for R {}

#[cfg(feature = "openapi")]
impl<R: IntoResponse + ResponseSchema> IntoResponseWithSchema for R {}

/// The default json returned on an 500 Internal Server Error.
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "openapi", derive(OpenapiType))]
pub(crate) struct ResourceError {
	/// This is always `true` and can be used to detect an error response without looking at the
	/// HTTP status code.
	error: bool,
	/// The error message.
	message: String
}

impl<T: ToString> From<T> for ResourceError {
	fn from(message: T) -> Self {
		Self {
			error: true,
			message: message.to_string()
		}
	}
}

#[cfg(feature = "errorlog")]
fn errorlog<E: Display>(e: E) {
	error!("The handler encountered an error: {e}");
}

#[cfg(not(feature = "errorlog"))]
fn errorlog<E>(_e: E) {}

fn handle_error<E>(e: E) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>>
where
	E: Display + IntoResponseError
{
	let msg = e.to_string();
	let res = e.into_response_error();
	match &res {
		Ok(res) if res.status.is_server_error() => errorlog(msg),
		Err(err) => {
			errorlog(msg);
			errorlog(&err);
		},
		_ => {}
	};
	future::ready(res).boxed()
}

impl<Res> IntoResponse for Pin<Box<dyn Future<Output = Res> + Send>>
where
	Res: IntoResponse + 'static
{
	type Err = Res::Err;

	fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>> {
		self.then(IntoResponse::into_response).boxed()
	}

	fn accepted_types() -> Option<Vec<Mime>> {
		Res::accepted_types()
	}
}

#[cfg(feature = "openapi")]
impl<Res> ResponseSchema for Pin<Box<dyn Future<Output = Res> + Send>>
where
	Res: ResponseSchema
{
	fn status_codes() -> Vec<StatusCode> {
		Res::status_codes()
	}

	fn schema(code: StatusCode) -> OpenapiSchema {
		Res::schema(code)
	}
}

#[cfg(test)]
mod test {
	use super::*;
	use futures_executor::block_on;
	use thiserror::Error;

	#[derive(Debug, Default, Deserialize, Serialize)]
	#[cfg_attr(feature = "openapi", derive(openapi_type::OpenapiType))]
	struct Msg {
		msg: String
	}

	#[derive(Debug, Default, Error)]
	#[error("An Error")]
	struct MsgError;

	#[test]
	fn result_from_future() {
		let nc = NoContent::default();
		let res = block_on(nc.into_response()).unwrap();

		let fut_nc = async move { NoContent::default() }.boxed();
		let fut_res = block_on(fut_nc.into_response()).unwrap();

		assert_eq!(res.status, fut_res.status);
		assert_eq!(res.mime, fut_res.mime);
		assert_eq!(res.full_body().unwrap(), fut_res.full_body().unwrap());
	}
}