relay/src/middleware/payload.rs

78 lines
2 KiB
Rust
Raw Normal View History

2020-07-10 20:07:47 +00:00
use actix_web::{
2021-06-24 17:02:27 +00:00
dev::{Payload, Service, ServiceRequest, Transform},
2021-09-18 17:55:39 +00:00
http::Method,
web::BytesMut,
2021-09-18 17:55:39 +00:00
HttpMessage,
2020-07-10 20:07:47 +00:00
};
2021-09-18 17:55:39 +00:00
use std::{
future::{ready, Ready},
task::{Context, Poll},
};
2023-09-09 20:46:22 +00:00
use streem::IntoStreamer;
2020-07-10 20:07:47 +00:00
#[derive(Clone, Debug)]
2021-02-10 04:17:20 +00:00
pub(crate) struct DebugPayload(pub bool);
2020-07-10 20:07:47 +00:00
#[doc(hidden)]
#[derive(Clone, Debug)]
2021-02-10 04:17:20 +00:00
pub(crate) struct DebugPayloadMiddleware<S>(bool, S);
2020-07-10 20:07:47 +00:00
2021-02-11 00:00:11 +00:00
impl<S> Transform<S, ServiceRequest> for DebugPayload
2020-07-10 20:07:47 +00:00
where
2021-02-11 00:00:11 +00:00
S: Service<ServiceRequest, Error = actix_web::Error>,
2020-07-10 20:07:47 +00:00
S::Future: 'static,
S::Error: 'static,
{
type Response = S::Response;
type Error = S::Error;
type InitError = ();
type Transform = DebugPayloadMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
2021-09-18 17:55:39 +00:00
ready(Ok(DebugPayloadMiddleware(self.0, service)))
2020-07-10 20:07:47 +00:00
}
}
2021-02-11 00:00:11 +00:00
impl<S> Service<ServiceRequest> for DebugPayloadMiddleware<S>
2020-07-10 20:07:47 +00:00
where
2021-02-11 00:00:11 +00:00
S: Service<ServiceRequest, Error = actix_web::Error>,
2020-07-10 20:07:47 +00:00
S::Future: 'static,
S::Error: 'static,
{
type Response = S::Response;
type Error = S::Error;
2022-11-23 16:44:11 +00:00
type Future = S::Future;
2020-07-10 20:07:47 +00:00
2021-02-11 00:00:11 +00:00
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
2020-07-10 20:07:47 +00:00
self.1.poll_ready(cx)
}
2021-02-11 00:00:11 +00:00
fn call(&self, mut req: ServiceRequest) -> Self::Future {
if self.0 && req.method() == Method::POST {
2023-09-09 20:46:22 +00:00
let mut pl = req.take_payload().into_streamer();
2021-12-28 16:23:48 +00:00
req.set_payload(Payload::Stream {
2023-09-09 20:46:22 +00:00
payload: Box::pin(streem::try_from_fn(|yielder| async move {
let mut buf = BytesMut::new();
while let Some(bytes) = pl.try_next().await? {
buf.extend(bytes);
}
let bytes = buf.freeze();
tracing::info!("{}", String::from_utf8_lossy(&bytes));
yielder.yield_ok(bytes).await;
Ok(())
})),
2021-12-28 16:23:48 +00:00
});
2020-07-10 20:07:47 +00:00
2022-11-23 16:44:11 +00:00
self.1.call(req)
2020-07-10 20:34:18 +00:00
} else {
2022-11-23 16:44:11 +00:00
self.1.call(req)
2020-07-10 20:34:18 +00:00
}
2020-07-10 20:07:47 +00:00
}
}