jsonrpsee_server/transport/
http.rs1use crate::{server::handle_rpc_call, BatchRequestConfig, HttpRequest, HttpResponse, LOG_TARGET};
2use http::Method;
3use hyper::body::Bytes;
4use jsonrpsee_core::{
5 http_helpers::{read_body, HttpError},
6 middleware::RpcServiceT,
7 BoxError,
8};
9use std::time::Duration;
10
11fn is_json(content_type: Option<&hyper::header::HeaderValue>) -> bool {
18 content_type.and_then(|val| val.to_str().ok()).is_some_and(|content| {
19 ["application/json", "application/json-rpc"].into_iter().any(|media_type| {
20 content.split_at_checked(media_type.len()).is_some_and(|(prefix, params)| {
21 prefix.eq_ignore_ascii_case(media_type) &&
22 matches!(params.trim_ascii_start().as_bytes(), [] | [b';', ..])
23 })
24 })
25 })
26}
27
28pub async fn call_with_service<S, B>(
32 request: HttpRequest<B>,
33 batch_config: BatchRequestConfig,
34 max_request_size: u32,
35 request_body_read_timeout: Option<Duration>,
36 rpc_service: &S,
37) -> HttpResponse
38where
39 B: http_body::Body<Data = Bytes> + Send + 'static,
40 B::Data: Send,
41 B::Error: Into<BoxError>,
42 S: RpcServiceT + Send,
43{
44 match *request.method() {
46 Method::POST if is_json(request.headers().get(hyper::header::CONTENT_TYPE)) => {
47 let (parts, body) = request.into_parts();
48
49 let read = read_body(&parts.headers, body, max_request_size);
52 let read = async {
53 match request_body_read_timeout {
54 Some(timeout) => tokio::time::timeout(timeout, read).await,
55 None => Ok(read.await),
56 }
57 };
58 let (body, is_single) = match read.await {
59 Ok(Ok(r)) => r,
60 Ok(Err(HttpError::TooLarge)) => return response::too_large(max_request_size),
61 Ok(Err(HttpError::Malformed)) => return response::malformed(),
62 Ok(Err(HttpError::Stream(e))) => {
63 tracing::warn!(target: LOG_TARGET, "Internal error reading request body: {}", e);
64 return response::internal_error();
65 }
66 Err(_elapsed) => return response::request_timeout(parts.version),
67 };
68
69 let mut rp =
70 handle_rpc_call(&body, is_single, batch_config, max_request_size, rpc_service)
71 .await;
72 if parts.version < hyper::Version::HTTP_11 {
75 rp = rp.buffer().await;
76 }
77
78 response::from_method_response(rp)
81 }
82 Method::POST => response::unsupported_content_type(),
84 _ => response::method_not_allowed(),
85 }
86}
87
88pub mod response {
90 use futures_util::StreamExt;
91 use http::Version;
92 use http_body::Frame;
93 use http_body_util::StreamBody;
94 use jsonrpsee_core::server::{MethodResponse, ResponseBody};
95 use jsonrpsee_types::{
96 error::{reject_too_big_request, ErrorCode},
97 ErrorObjectOwned, Id, Response, ResponsePayload,
98 };
99
100 use crate::{HttpBody, HttpResponse};
101
102 const JSON: &str = "application/json; charset=utf-8";
103 const TEXT: &str = "text/plain";
104
105 pub fn internal_error() -> HttpResponse {
107 let err = ResponsePayload::<()>::error(ErrorObjectOwned::from(ErrorCode::InternalError));
108 let rp = Response::new(err, Id::Null);
109 let error = serde_json::to_string(&rp).expect("built from known-good data; qed");
110
111 from_template(hyper::StatusCode::INTERNAL_SERVER_ERROR, error, JSON)
112 }
113
114 pub fn method_not_allowed() -> HttpResponse {
116 from_template(
117 hyper::StatusCode::METHOD_NOT_ALLOWED,
118 "Used HTTP Method is not allowed. POST is required\n",
119 TEXT,
120 )
121 }
122
123 pub fn too_large(limit: u32) -> HttpResponse {
125 let err = ResponsePayload::<()>::error(reject_too_big_request(limit));
126 let rp = Response::new(err, Id::Null);
127 let error = serde_json::to_string(&rp).expect("JSON serialization infallible; qed");
128
129 from_template(hyper::StatusCode::PAYLOAD_TOO_LARGE, error, JSON)
130 }
131
132 pub fn request_timeout(version: Version) -> HttpResponse {
134 if version == Version::HTTP_2 {
135 let mut response = HttpResponse::new(HttpBody::empty());
137 *response.status_mut() = hyper::StatusCode::REQUEST_TIMEOUT;
138 return response;
139 }
140
141 from_template(
142 hyper::StatusCode::REQUEST_TIMEOUT,
143 "Request body was not received in time\n",
144 TEXT,
145 )
146 }
147
148 pub fn malformed() -> HttpResponse {
150 let rp = Response::new(ResponsePayload::<()>::error(ErrorCode::ParseError), Id::Null);
151 let error = serde_json::to_string(&rp).expect("JSON serialization infallible; qed");
152
153 from_template(hyper::StatusCode::BAD_REQUEST, error, JSON)
154 }
155
156 pub(crate) fn from_template(
158 status: hyper::StatusCode,
159 body: impl Into<HttpBody>,
160 content_type: &'static str,
161 ) -> HttpResponse {
162 HttpResponse::builder()
163 .status(status)
164 .header("content-type", hyper::header::HeaderValue::from_static(content_type))
165 .body(body.into())
166 .expect("Unable to parse response body for type conversion")
169 }
170
171 pub fn from_method_response(rp: MethodResponse) -> HttpResponse {
177 let body = match rp.into_body() {
178 ResponseBody::Json(json) => HttpBody::from(json),
179 ResponseBody::Stream(stream) => HttpBody::new(StreamBody::new(stream.map(|part| {
180 part.map(Frame::data).inspect_err(|err| {
181 tracing::warn!(target: "rpc", code = err.code(), "Aborting streamed response");
184 })
185 }))),
186 };
187 from_template(hyper::StatusCode::OK, body, JSON)
188 }
189
190 pub fn unsupported_content_type() -> HttpResponse {
192 from_template(
193 hyper::StatusCode::UNSUPPORTED_MEDIA_TYPE,
194 "Supplied content type is not allowed. Content-Type: application/json is required\n",
195 TEXT,
196 )
197 }
198
199 pub fn too_many_requests() -> HttpResponse {
201 from_template(
202 hyper::StatusCode::TOO_MANY_REQUESTS,
203 "Too many connections. Please try again later.",
204 TEXT,
205 )
206 }
207
208 pub fn denied() -> HttpResponse {
210 from_template(hyper::StatusCode::FORBIDDEN, HttpBody::default(), TEXT)
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217 use hyper::header::HeaderValue;
218
219 #[test]
220 fn json_content_types_are_accepted_whatever_their_parameters() {
221 for accepted in [
222 "application/json",
223 "application/json-rpc",
224 "APPLICATION/JSON",
225 "application/json; charset=utf-8",
226 "application/json;charset=utf-8",
227 "application/json; charset=UTF-8",
228 r#"application/json; charset="utf-8""#,
229 "application/json ; charset=utf-8",
230 "application/json-rpc; charset=utf-8",
231 "application/json;charset=utf-8;foo=bar",
232 ] {
233 assert!(is_json(Some(&HeaderValue::from_str(accepted).unwrap())), "{accepted}");
234 }
235
236 for rejected in [
237 "",
238 "text/plain",
239 "application/jsonx",
240 "application/json x",
241 "application/json-rpcx",
242 "application/octet-stream; charset=utf-8",
243 ] {
244 assert!(!is_json(Some(&HeaderValue::from_str(rejected).unwrap())), "{rejected}");
245 }
246
247 assert!(!is_json(None));
248 }
249}