axum_extra/protobuf.rs
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
//! Protocol Buffer extractor and response.
use axum::{
extract::{rejection::BytesRejection, FromRequest, Request},
response::{IntoResponse, Response},
};
use axum_core::__composite_rejection as composite_rejection;
use axum_core::__define_rejection as define_rejection;
use bytes::{Bytes, BytesMut};
use http::StatusCode;
use prost::Message;
/// A Protocol Buffer message extractor and response.
///
/// This can be used both as an extractor and as a response.
///
/// # As extractor
///
/// When used as an extractor, it can decode request bodies into some type that
/// implements [`prost::Message`]. The request will be rejected (and a [`ProtobufRejection`] will
/// be returned) if:
///
/// - The body couldn't be decoded into the target Protocol Buffer message type.
/// - Buffering the request body fails.
///
/// See [`ProtobufRejection`] for more details.
///
/// The extractor does not expect a `Content-Type` header to be present in the request.
///
/// # Extractor example
///
/// ```rust,no_run
/// use axum::{routing::post, Router};
/// use axum_extra::protobuf::Protobuf;
///
/// #[derive(prost::Message)]
/// struct CreateUser {
/// #[prost(string, tag="1")]
/// email: String,
/// #[prost(string, tag="2")]
/// password: String,
/// }
///
/// async fn create_user(Protobuf(payload): Protobuf<CreateUser>) {
/// // payload is `CreateUser`
/// }
///
/// let app = Router::new().route("/users", post(create_user));
/// # let _: Router = app;
/// ```
///
/// # As response
///
/// When used as a response, it can encode any type that implements [`prost::Message`] to
/// a newly allocated buffer.
///
/// If no `Content-Type` header is set, the `Content-Type: application/octet-stream` header
/// will be used automatically.
///
/// # Response example
///
/// ```
/// use axum::{
/// extract::Path,
/// routing::get,
/// Router,
/// };
/// use axum_extra::protobuf::Protobuf;
///
/// #[derive(prost::Message)]
/// struct User {
/// #[prost(string, tag="1")]
/// username: String,
/// }
///
/// async fn get_user(Path(user_id) : Path<String>) -> Protobuf<User> {
/// let user = find_user(user_id).await;
/// Protobuf(user)
/// }
///
/// async fn find_user(user_id: String) -> User {
/// // ...
/// # unimplemented!()
/// }
///
/// let app = Router::new().route("/users/{id}", get(get_user));
/// # let _: Router = app;
/// ```
#[derive(Debug, Clone, Copy, Default)]
#[cfg_attr(docsrs, doc(cfg(feature = "protobuf")))]
#[must_use]
pub struct Protobuf<T>(pub T);
impl<T, S> FromRequest<S> for Protobuf<T>
where
T: Message + Default,
S: Send + Sync,
{
type Rejection = ProtobufRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let mut bytes = Bytes::from_request(req, state).await?;
match T::decode(&mut bytes) {
Ok(value) => Ok(Protobuf(value)),
Err(err) => Err(ProtobufDecodeError::from_err(err).into()),
}
}
}
axum_core::__impl_deref!(Protobuf);
impl<T> From<T> for Protobuf<T> {
fn from(inner: T) -> Self {
Self(inner)
}
}
impl<T> IntoResponse for Protobuf<T>
where
T: Message + Default,
{
fn into_response(self) -> Response {
let mut buf = BytesMut::with_capacity(128);
match &self.0.encode(&mut buf) {
Ok(()) => buf.into_response(),
Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response(),
}
}
}
define_rejection! {
#[status = UNPROCESSABLE_ENTITY]
#[body = "Failed to decode the body"]
/// Rejection type for [`Protobuf`].
///
/// This rejection is used if the request body couldn't be decoded into the target type.
pub struct ProtobufDecodeError(Error);
}
composite_rejection! {
/// Rejection used for [`Protobuf`].
///
/// Contains one variant for each way the [`Protobuf`] extractor
/// can fail.
pub enum ProtobufRejection {
ProtobufDecodeError,
BytesRejection,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_helpers::*;
use axum::{routing::post, Router};
#[tokio::test]
async fn decode_body() {
#[derive(prost::Message)]
struct Input {
#[prost(string, tag = "1")]
foo: String,
}
let app = Router::new().route(
"/",
post(|input: Protobuf<Input>| async move { input.foo.to_owned() }),
);
let input = Input {
foo: "bar".to_owned(),
};
let client = TestClient::new(app);
let res = client.post("/").body(input.encode_to_vec()).await;
let body = res.text().await;
assert_eq!(body, "bar");
}
#[tokio::test]
async fn prost_decode_error() {
#[derive(prost::Message)]
struct Input {
#[prost(string, tag = "1")]
foo: String,
}
#[derive(prost::Message)]
struct Expected {
#[prost(int32, tag = "1")]
test: i32,
}
let app = Router::new().route("/", post(|_: Protobuf<Expected>| async {}));
let input = Input {
foo: "bar".to_owned(),
};
let client = TestClient::new(app);
let res = client.post("/").body(input.encode_to_vec()).await;
assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn encode_body() {
#[derive(prost::Message)]
struct Input {
#[prost(string, tag = "1")]
foo: String,
}
#[derive(prost::Message)]
struct Output {
#[prost(string, tag = "1")]
result: String,
}
#[axum::debug_handler]
async fn handler(input: Protobuf<Input>) -> Protobuf<Output> {
let output = Output {
result: input.foo.to_owned(),
};
Protobuf(output)
}
let app = Router::new().route("/", post(handler));
let input = Input {
foo: "bar".to_owned(),
};
let client = TestClient::new(app);
let res = client.post("/").body(input.encode_to_vec()).await;
assert_eq!(
res.headers()["content-type"],
mime::APPLICATION_OCTET_STREAM.as_ref()
);
let body = res.bytes().await;
let output = Output::decode(body).unwrap();
assert_eq!(output.result, "bar");
}
}