|
| 1 | +// #![cfg(feature = "http")] |
| 2 | + |
| 3 | +use std::future::Future; |
| 4 | +use std::pin::Pin; |
| 5 | +use std::task::{Context, Poll}; |
| 6 | + |
| 7 | +use bytes::Bytes; |
| 8 | +use futures::future::Ready; |
| 9 | +use futures::ready; |
| 10 | +use http_body::Body; |
| 11 | +use http_body_util::{combinators::Collect, Collected}; |
| 12 | + |
| 13 | +use crate::error::{Error, Result}; |
| 14 | +use crate::events::{Event, EventKind}; |
| 15 | +use crate::parser::RequestParser; |
| 16 | + |
| 17 | +pin_project_lite::pin_project! { |
| 18 | + #[must_use] |
| 19 | + #[project = CollectBodyProject] |
| 20 | + struct CollectBody<B> |
| 21 | + where |
| 22 | + B: Body, |
| 23 | + B: ?Sized, |
| 24 | + { |
| 25 | + #[pin] |
| 26 | + collect: Collect<B>, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +impl<B> Future for CollectBody<B> |
| 31 | +where |
| 32 | + B: Body + ?Sized, |
| 33 | + B::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, |
| 34 | +{ |
| 35 | + type Output = Result<Bytes>; |
| 36 | + |
| 37 | + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 38 | + let s = self.project(); |
| 39 | + let collected = ready!(s.collect.poll(cx)); |
| 40 | + let res = collected |
| 41 | + .map(Collected::to_bytes) |
| 42 | + .map_err(Error::read_body_failed); |
| 43 | + Poll::Ready(res) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +pin_project_lite::pin_project! { |
| 48 | + #[must_use] |
| 49 | + #[project = ParseRequestInnerProject] |
| 50 | + struct ParseRequestInner<K, B> { |
| 51 | + #[pin] |
| 52 | + kind: K, |
| 53 | + #[pin] |
| 54 | + body: B, |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl<K, B> Future for ParseRequestInner<K, B> |
| 59 | +where |
| 60 | + K: Future<Output = Result<EventKind>>, |
| 61 | + B: Future<Output = Result<Bytes>>, |
| 62 | +{ |
| 63 | + type Output = Result<Event>; |
| 64 | + |
| 65 | + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 66 | + let s = self.project(); |
| 67 | + let kind = match ready!(s.kind.poll(cx)) { |
| 68 | + Ok(k) => k, |
| 69 | + Err(e) => return Poll::Ready(Err(e)), |
| 70 | + }; |
| 71 | + let body = ready!(s.body.poll(cx)); |
| 72 | + let res: Result<Event> = { |
| 73 | + let body = body?; |
| 74 | + let body = std::str::from_utf8(&body).map_err(Error::read_body_failed)?; |
| 75 | + super::parse_body(kind, body) |
| 76 | + }; |
| 77 | + Poll::Ready(res) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +pin_project_lite::pin_project! { |
| 82 | + /// <code>impl [Future]<Output = Result<[Event], [Error]>></code> |
| 83 | + /// |
| 84 | + /// [Future]: std::future::Future |
| 85 | + /// [Event]: crate::Event |
| 86 | + /// [Error]: crate::Error |
| 87 | + #[must_use] |
| 88 | + #[project = ParseRequestProject] |
| 89 | + pub struct ParseRequest<B> |
| 90 | + where |
| 91 | + B: Body, |
| 92 | + { |
| 93 | + #[pin] |
| 94 | + inner: ParseRequestInner<Ready<Result<EventKind>>, CollectBody<B>> |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +impl<B> ParseRequest<B> |
| 99 | +where |
| 100 | + B: Body, |
| 101 | +{ |
| 102 | + fn new(kind: Result<EventKind>, body: B) -> Self { |
| 103 | + use http_body_util::BodyExt; |
| 104 | + |
| 105 | + let kind = futures::future::ready(kind); |
| 106 | + let inner = ParseRequestInner { |
| 107 | + kind, |
| 108 | + body: CollectBody { |
| 109 | + collect: body.collect(), |
| 110 | + }, |
| 111 | + }; |
| 112 | + Self { inner } |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +impl<B> Future for ParseRequest<B> |
| 117 | +where |
| 118 | + B: Body, |
| 119 | + B::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, |
| 120 | +{ |
| 121 | + type Output = Result<Event>; |
| 122 | + |
| 123 | + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 124 | + let s = self.project(); |
| 125 | + s.inner.poll(cx) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +impl RequestParser { |
| 130 | + /// [`http::Request`]をパースします。 |
| 131 | + /// |
| 132 | + /// **Note**: この関数は`http`featureが有効になっている時のみ有効です。 |
| 133 | + /// |
| 134 | + /// # Arguments |
| 135 | + /// |
| 136 | + /// * `request`: リクエスト全体 |
| 137 | + /// |
| 138 | + /// # Example |
| 139 | + /// |
| 140 | + /// ``` |
| 141 | + /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 142 | + /// # let res: Result<(), Box<dyn std::error::Error>> = futures::executor::block_on(async { |
| 143 | + /// use traq_bot_http::{EventKind, RequestParser}; |
| 144 | + /// |
| 145 | + /// let verification_token = "verification_token"; |
| 146 | + /// let body = r#"{"eventTime": "2019-05-07T04:50:48.582586882Z"}"#.to_string(); |
| 147 | + /// let request = http::Request::builder() |
| 148 | + /// .method(http::Method::POST) |
| 149 | + /// .header(http::header::CONTENT_TYPE, "application/json") |
| 150 | + /// .header("X-TRAQ-BOT-TOKEN", verification_token) |
| 151 | + /// .header("X-TRAQ-BOT-EVENT", "PING") |
| 152 | + /// .body(body)?; |
| 153 | + /// let parser = RequestParser::new(verification_token); |
| 154 | + /// let event = parser.parse_request(request).await?; |
| 155 | + /// assert_eq!(event.kind(), EventKind::Ping); |
| 156 | + /// # Ok(()) |
| 157 | + /// # }); |
| 158 | + /// # res |
| 159 | + /// # } |
| 160 | + /// ``` |
| 161 | + /// |
| 162 | + /// # Errors |
| 163 | + /// |
| 164 | + /// [`Error`]のうち、[`Error::kind`]が以下のものを返す可能性があります。 |
| 165 | + /// |
| 166 | + /// - [`parse`]で返されるもの |
| 167 | + /// - [`ErrorKind::ReadBodyFailed`] : |
| 168 | + /// リクエストボディの読み込みに失敗した |
| 169 | + /// |
| 170 | + /// [`Error::kind`]: crate::Error::kind |
| 171 | + /// [`parse`]: crate::RequestParser::parse |
| 172 | + /// [`ErrorKind::ReadBodyFailed`]: crate::ErrorKind::ReadBodyFailed |
| 173 | + pub fn parse_request<B>(&self, request: http::Request<B>) -> ParseRequest<B> |
| 174 | + where |
| 175 | + B: Body, |
| 176 | + B::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, |
| 177 | + { |
| 178 | + let (parts, body) = request.into_parts(); |
| 179 | + let kind = self.parse_headers(&parts.headers); |
| 180 | + ParseRequest::new(kind, body) |
| 181 | + } |
| 182 | +} |
| 183 | + |
| 184 | +#[cfg(test)] |
| 185 | +mod tests { |
| 186 | + use futures::executor::block_on; |
| 187 | + use http_body_util::BodyExt; |
| 188 | + |
| 189 | + use super::{CollectBody, ParseRequest}; |
| 190 | + use crate::{Event, EventKind}; |
| 191 | + |
| 192 | + #[test] |
| 193 | + fn collect_body() { |
| 194 | + let body_content = "some content"; |
| 195 | + let fut = CollectBody { |
| 196 | + collect: body_content.to_string().collect(), |
| 197 | + }; |
| 198 | + let collected = block_on(fut).unwrap(); |
| 199 | + assert_eq!(collected, body_content.as_bytes()); |
| 200 | + } |
| 201 | + |
| 202 | + #[test] |
| 203 | + fn parse_request_future() { |
| 204 | + let kind = EventKind::Ping; |
| 205 | + let payload = r#"{"eventTime": "2019-05-07T04:50:48.582586882Z"}"#; |
| 206 | + let body = payload.to_string(); |
| 207 | + let fut = ParseRequest::new(Ok(kind), body); |
| 208 | + let event = block_on(fut).unwrap(); |
| 209 | + assert!(matches!(event, Event::Ping(_))); |
| 210 | + } |
| 211 | +} |
0 commit comments