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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use std::{borrow::Cow, convert::Infallible, future::Future, str::FromStr};
use async_graphql::{
futures_util::task::{Context, Poll},
http::{WebSocketProtocols, WsMessage, ALL_WEBSOCKET_PROTOCOLS},
Data, ObjectType, Result, Schema, SubscriptionType,
};
use axum::{
body::{boxed, BoxBody, HttpBody},
extract::{
ws::{CloseFrame, Message},
FromRequest, RequestParts, WebSocketUpgrade,
},
http::{self, Request, Response, StatusCode},
response::IntoResponse,
Error,
};
use futures_util::{
future,
future::{BoxFuture, Ready},
stream::{SplitSink, SplitStream},
Sink, SinkExt, Stream, StreamExt,
};
use tower_service::Service;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct GraphQLProtocol(WebSocketProtocols);
#[async_trait::async_trait]
impl<B: Send> FromRequest<B> for GraphQLProtocol {
type Rejection = StatusCode;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
req.headers()
.get(http::header::SEC_WEBSOCKET_PROTOCOL)
.and_then(|value| value.to_str().ok())
.and_then(|protocols| {
protocols
.split(',')
.find_map(|p| WebSocketProtocols::from_str(p.trim()).ok())
})
.map(Self)
.ok_or(StatusCode::BAD_REQUEST)
}
}
pub struct GraphQLSubscription<Query, Mutation, Subscription> {
schema: Schema<Query, Mutation, Subscription>,
}
impl<Query, Mutation, Subscription> Clone for GraphQLSubscription<Query, Mutation, Subscription>
where
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
fn clone(&self) -> Self {
Self {
schema: self.schema.clone(),
}
}
}
impl<Query, Mutation, Subscription> GraphQLSubscription<Query, Mutation, Subscription>
where
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
pub fn new(schema: Schema<Query, Mutation, Subscription>) -> Self {
Self { schema }
}
}
impl<B, Query, Mutation, Subscription> Service<Request<B>>
for GraphQLSubscription<Query, Mutation, Subscription>
where
B: HttpBody + Send + 'static,
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
type Response = Response<BoxBody>;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<B>) -> Self::Future {
let schema = self.schema.clone();
Box::pin(async move {
let mut parts = RequestParts::new(req);
let protocol = match GraphQLProtocol::from_request(&mut parts).await {
Ok(protocol) => protocol,
Err(err) => return Ok(err.into_response().map(boxed)),
};
let upgrade = match WebSocketUpgrade::from_request(&mut parts).await {
Ok(protocol) => protocol,
Err(err) => return Ok(err.into_response().map(boxed)),
};
let schema = schema.clone();
let resp = upgrade
.protocols(ALL_WEBSOCKET_PROTOCOLS)
.on_upgrade(move |stream| GraphQLWebSocket::new(stream, schema, protocol).serve());
Ok(resp.into_response().map(boxed))
})
}
}
type DefaultOnConnInitType = fn(serde_json::Value) -> Ready<async_graphql::Result<Data>>;
fn default_on_connection_init(_: serde_json::Value) -> Ready<async_graphql::Result<Data>> {
futures_util::future::ready(Ok(Data::default()))
}
pub struct GraphQLWebSocket<Sink, Stream, Query, Mutation, Subscription, OnConnInit> {
sink: Sink,
stream: Stream,
schema: Schema<Query, Mutation, Subscription>,
data: Data,
on_connection_init: OnConnInit,
protocol: GraphQLProtocol,
}
impl<S, Query, Mutation, Subscription>
GraphQLWebSocket<
SplitSink<S, Message>,
SplitStream<S>,
Query,
Mutation,
Subscription,
DefaultOnConnInitType,
>
where
S: Stream<Item = Result<Message, Error>> + Sink<Message>,
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
pub fn new(
stream: S,
schema: Schema<Query, Mutation, Subscription>,
protocol: GraphQLProtocol,
) -> Self {
let (sink, stream) = stream.split();
GraphQLWebSocket::new_with_pair(sink, stream, schema, protocol)
}
}
impl<Sink, Stream, Query, Mutation, Subscription>
GraphQLWebSocket<Sink, Stream, Query, Mutation, Subscription, DefaultOnConnInitType>
where
Sink: futures_util::sink::Sink<Message>,
Stream: futures_util::stream::Stream<Item = Result<Message, Error>>,
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
pub fn new_with_pair(
sink: Sink,
stream: Stream,
schema: Schema<Query, Mutation, Subscription>,
protocol: GraphQLProtocol,
) -> Self {
GraphQLWebSocket {
sink,
stream,
schema,
data: Data::default(),
on_connection_init: default_on_connection_init,
protocol,
}
}
}
impl<Sink, Stream, Query, Mutation, Subscription, OnConnInit, OnConnInitFut>
GraphQLWebSocket<Sink, Stream, Query, Mutation, Subscription, OnConnInit>
where
Sink: futures_util::sink::Sink<Message>,
Stream: futures_util::stream::Stream<Item = Result<Message, Error>>,
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
OnConnInit: FnOnce(serde_json::Value) -> OnConnInitFut + Send + 'static,
OnConnInitFut: Future<Output = async_graphql::Result<Data>> + Send + 'static,
{
#[must_use]
pub fn with_data(self, data: Data) -> Self {
Self { data, ..self }
}
pub fn on_connection_init<OnConnInit2, Fut>(
self,
callback: OnConnInit2,
) -> GraphQLWebSocket<Sink, Stream, Query, Mutation, Subscription, OnConnInit2>
where
OnConnInit2: FnOnce(serde_json::Value) -> Fut + Send + 'static,
Fut: Future<Output = async_graphql::Result<Data>> + Send + 'static,
{
GraphQLWebSocket {
sink: self.sink,
stream: self.stream,
schema: self.schema,
data: self.data,
on_connection_init: callback,
protocol: self.protocol,
}
}
pub async fn serve(self) {
let input = self
.stream
.take_while(|res| future::ready(res.is_ok()))
.map(Result::unwrap)
.filter_map(|msg| {
if let Message::Text(_) | Message::Binary(_) = msg {
future::ready(Some(msg))
} else {
future::ready(None)
}
})
.map(Message::into_data);
let stream =
async_graphql::http::WebSocket::new(self.schema.clone(), input, self.protocol.0)
.connection_data(self.data)
.on_connection_init(self.on_connection_init)
.map(|msg| match msg {
WsMessage::Text(text) => Message::Text(text),
WsMessage::Close(code, status) => Message::Close(Some(CloseFrame {
code,
reason: Cow::from(status),
})),
});
let sink = self.sink;
futures_util::pin_mut!(stream, sink);
while let Some(item) = stream.next().await {
let _ = sink.send(item).await;
}
}
}