|
| 1 | +use std::{convert::Infallible, fmt::Display, sync::Arc, time::Duration}; |
| 2 | + |
| 3 | +use bytes::{Buf, Bytes}; |
| 4 | +use http::Response; |
| 5 | +use http_body::Body; |
| 6 | +use http_body_util::{BodyExt, Empty, Full, combinators::UnsyncBoxBody}; |
| 7 | +use sse_stream::{KeepAlive, Sse, SseBody}; |
| 8 | + |
| 9 | +use crate::model::{ClientJsonRpcMessage, ServerJsonRpcMessage}; |
| 10 | + |
| 11 | +use super::http_header::EVENT_STREAM_MIME_TYPE; |
| 12 | + |
| 13 | +pub type SessionId = Arc<str>; |
| 14 | + |
| 15 | +pub fn session_id() -> SessionId { |
| 16 | + uuid::Uuid::new_v4().to_string().into() |
| 17 | +} |
| 18 | + |
| 19 | +pub const DEFAULT_AUTO_PING_INTERVAL: Duration = Duration::from_secs(15); |
| 20 | + |
| 21 | +pub(crate) type BoxResponse = Response<UnsyncBoxBody<Bytes, Infallible>>; |
| 22 | + |
| 23 | +pub(crate) fn accecpted_response() -> Response<UnsyncBoxBody<Bytes, Infallible>> { |
| 24 | + Response::builder() |
| 25 | + .status(http::StatusCode::ACCEPTED) |
| 26 | + .body(Empty::new().boxed_unsync()) |
| 27 | + .expect("valid response") |
| 28 | +} |
| 29 | +pin_project_lite::pin_project! { |
| 30 | + struct TokioTimer { |
| 31 | + #[pin] |
| 32 | + sleep: tokio::time::Sleep, |
| 33 | + } |
| 34 | +} |
| 35 | +impl Future for TokioTimer { |
| 36 | + type Output = (); |
| 37 | + |
| 38 | + fn poll( |
| 39 | + self: std::pin::Pin<&mut Self>, |
| 40 | + cx: &mut std::task::Context<'_>, |
| 41 | + ) -> std::task::Poll<Self::Output> { |
| 42 | + let this = self.project(); |
| 43 | + this.sleep.poll(cx) |
| 44 | + } |
| 45 | +} |
| 46 | +impl sse_stream::Timer for TokioTimer { |
| 47 | + fn from_duration(duration: Duration) -> Self { |
| 48 | + Self { |
| 49 | + sleep: tokio::time::sleep(duration), |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + fn reset(self: std::pin::Pin<&mut Self>, when: std::time::Instant) { |
| 54 | + let this = self.project(); |
| 55 | + this.sleep.reset(tokio::time::Instant::from_std(when)); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +#[derive(Debug, Clone)] |
| 60 | +pub struct ServerSseMessage { |
| 61 | + pub event_id: Option<String>, |
| 62 | + pub message: Arc<ServerJsonRpcMessage>, |
| 63 | +} |
| 64 | + |
| 65 | +pub(crate) fn sse_stream_response( |
| 66 | + stream: impl futures::Stream<Item = ServerSseMessage> + Send + 'static, |
| 67 | + keep_alive: Option<Duration>, |
| 68 | +) -> Response<UnsyncBoxBody<Bytes, Infallible>> { |
| 69 | + use futures::StreamExt; |
| 70 | + let stream = SseBody::new(stream.map(|message| { |
| 71 | + let data = serde_json::to_string(&message.message).expect("valid message"); |
| 72 | + let mut sse = Sse::default().data(data); |
| 73 | + sse.id = message.event_id; |
| 74 | + Result::<Sse, Infallible>::Ok(sse) |
| 75 | + })); |
| 76 | + let stream = match keep_alive { |
| 77 | + Some(duration) => stream |
| 78 | + .with_keep_alive::<TokioTimer>(KeepAlive::new().interval(duration)) |
| 79 | + .boxed_unsync(), |
| 80 | + None => stream.boxed_unsync(), |
| 81 | + }; |
| 82 | + Response::builder() |
| 83 | + .status(http::StatusCode::OK) |
| 84 | + .header(http::header::CONTENT_TYPE, EVENT_STREAM_MIME_TYPE) |
| 85 | + .header(http::header::CACHE_CONTROL, "no-cache") |
| 86 | + .body(stream) |
| 87 | + .expect("valid response") |
| 88 | +} |
| 89 | + |
| 90 | +pub(crate) const fn internal_error_response<E: Display>( |
| 91 | + context: &str, |
| 92 | +) -> impl FnOnce(E) -> Response<UnsyncBoxBody<Bytes, Infallible>> { |
| 93 | + move |error| { |
| 94 | + tracing::error!("Internal server error when {context}: {error}"); |
| 95 | + Response::builder() |
| 96 | + .status(http::StatusCode::INTERNAL_SERVER_ERROR) |
| 97 | + .body( |
| 98 | + Full::new(Bytes::from(format!( |
| 99 | + "Encounter an error when {context}: {error}" |
| 100 | + ))) |
| 101 | + .boxed_unsync(), |
| 102 | + ) |
| 103 | + .expect("valid response") |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +pub(crate) async fn expect_json<B>( |
| 108 | + body: B, |
| 109 | +) -> Result<ClientJsonRpcMessage, Response<UnsyncBoxBody<Bytes, Infallible>>> |
| 110 | +where |
| 111 | + B: Body + Send + 'static, |
| 112 | + B::Error: Display, |
| 113 | +{ |
| 114 | + match body.collect().await { |
| 115 | + Ok(bytes) => { |
| 116 | + match serde_json::from_reader::<_, ClientJsonRpcMessage>(bytes.aggregate().reader()) { |
| 117 | + Ok(message) => Ok(message), |
| 118 | + Err(e) => { |
| 119 | + let response = Response::builder() |
| 120 | + .status(http::StatusCode::UNSUPPORTED_MEDIA_TYPE) |
| 121 | + .body( |
| 122 | + Full::new(Bytes::from(format!("fail to deserialize request body {e}"))) |
| 123 | + .boxed_unsync(), |
| 124 | + ) |
| 125 | + .expect("valid response"); |
| 126 | + Err(response) |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + Err(e) => { |
| 131 | + let response = Response::builder() |
| 132 | + .status(http::StatusCode::INTERNAL_SERVER_ERROR) |
| 133 | + .body( |
| 134 | + Full::new(Bytes::from(format!("Failed to read request body: {e}"))) |
| 135 | + .boxed_unsync(), |
| 136 | + ) |
| 137 | + .expect("valid response"); |
| 138 | + Err(response) |
| 139 | + } |
| 140 | + } |
| 141 | +} |
0 commit comments