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
use std::{
future::Future,
io::{self, ErrorKind},
pin::Pin,
};
use actix_http::{body::BoxBody, error::PayloadError};
use actix_web::{
dev::Payload,
error::JsonPayloadError,
http,
http::{Method, StatusCode},
Error, FromRequest, HttpRequest, HttpResponse, Responder, Result,
};
use async_graphql::{http::MultipartOptions, ParseRequestError};
use futures_util::{
future::{self, FutureExt},
StreamExt, TryStreamExt,
};
pub struct GraphQLRequest(pub async_graphql::Request);
impl GraphQLRequest {
#[must_use]
pub fn into_inner(self) -> async_graphql::Request {
self.0
}
}
type BatchToRequestMapper =
fn(<<GraphQLBatchRequest as FromRequest>::Future as Future>::Output) -> Result<GraphQLRequest>;
impl FromRequest for GraphQLRequest {
type Error = Error;
type Future = future::Map<<GraphQLBatchRequest as FromRequest>::Future, BatchToRequestMapper>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
GraphQLBatchRequest::from_request(req, payload).map(|res| {
Ok(Self(
res?.0
.into_single()
.map_err(actix_web::error::ErrorBadRequest)?,
))
})
}
}
pub struct GraphQLBatchRequest(pub async_graphql::BatchRequest);
impl GraphQLBatchRequest {
#[must_use]
pub fn into_inner(self) -> async_graphql::BatchRequest {
self.0
}
}
impl FromRequest for GraphQLBatchRequest {
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<GraphQLBatchRequest>>>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let config = req
.app_data::<MultipartOptions>()
.cloned()
.unwrap_or_default();
if req.method() == Method::GET {
let res = async_graphql::http::parse_query_string(req.query_string())
.map_err(|err| io::Error::new(ErrorKind::Other, err));
Box::pin(async move { Ok(Self(async_graphql::BatchRequest::Single(res?))) })
} else if req.method() == Method::POST {
let content_type = req
.headers()
.get(http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(|value| value.to_string());
let (tx, rx) = async_channel::bounded(16);
let mut payload = payload.take();
actix::spawn(async move {
while let Some(item) = payload.next().await {
if tx.send(item).await.is_err() {
return;
}
}
});
Box::pin(async move {
Ok(GraphQLBatchRequest(
async_graphql::http::receive_batch_body(
content_type,
rx.map_err(|e| match e {
PayloadError::Incomplete(Some(e)) | PayloadError::Io(e) => e,
PayloadError::Incomplete(None) => {
io::Error::from(ErrorKind::UnexpectedEof)
}
PayloadError::EncodingCorrupted => io::Error::new(
ErrorKind::InvalidData,
"cannot decode content-encoding",
),
PayloadError::Overflow => io::Error::new(
ErrorKind::InvalidData,
"a payload reached size limit",
),
PayloadError::UnknownLength => {
io::Error::new(ErrorKind::Other, "a payload length is unknown")
}
PayloadError::Http2Payload(e) if e.is_io() => e.into_io().unwrap(),
PayloadError::Http2Payload(e) => io::Error::new(ErrorKind::Other, e),
_ => io::Error::new(ErrorKind::Other, e),
})
.into_async_read(),
config,
)
.await
.map_err(|err| match err {
ParseRequestError::PayloadTooLarge => {
actix_web::error::ErrorPayloadTooLarge(err)
}
_ => actix_web::error::ErrorBadRequest(err),
})?,
))
})
} else {
Box::pin(async move {
Err(actix_web::error::ErrorMethodNotAllowed(
"GraphQL only supports GET and POST requests",
))
})
}
}
}
pub struct GraphQLResponse(pub async_graphql::BatchResponse);
impl From<async_graphql::Response> for GraphQLResponse {
fn from(resp: async_graphql::Response) -> Self {
Self(resp.into())
}
}
impl From<async_graphql::BatchResponse> for GraphQLResponse {
fn from(resp: async_graphql::BatchResponse) -> Self {
Self(resp)
}
}
#[cfg(feature = "cbor")]
mod cbor {
use core::fmt;
use actix_web::{http::StatusCode, ResponseError};
#[derive(Debug)]
pub struct Error(pub serde_cbor::Error);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl ResponseError for Error {
fn status_code(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
}
}
impl Responder for GraphQLResponse {
type Body = BoxBody;
fn respond_to(self, req: &HttpRequest) -> HttpResponse {
let mut builder = HttpResponse::build(StatusCode::OK);
if self.0.is_ok() {
if let Some(cache_control) = self.0.cache_control().value() {
builder.append_header((http::header::CACHE_CONTROL, cache_control));
}
}
let accept = req
.headers()
.get(http::header::ACCEPT)
.and_then(|val| val.to_str().ok());
let (ct, body) = match accept {
#[cfg(feature = "cbor")]
Some(ct @ "application/cbor") => (
ct,
match serde_cbor::to_vec(&self.0) {
Ok(body) => body,
Err(e) => return HttpResponse::from_error(cbor::Error(e)),
},
),
_ => (
"application/json",
match serde_json::to_vec(&self.0) {
Ok(body) => body,
Err(e) => return HttpResponse::from_error(JsonPayloadError::Serialize(e)),
},
),
};
let mut resp = builder.content_type(ct).body(body);
for (name, value) in self.0.http_headers_iter() {
resp.headers_mut().append(name, value);
}
resp
}
}