Repository navigation
Expand file tree
/
Copy pathserver.rs
More file actions
206 lines (185 loc) · 7.5 KB
/
Copy pathserver.rs
File metadata and controls
206 lines (185 loc) · 7.5 KB
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
use graph::{
data::query::QueryTarget,
prelude::{SubscriptionServer as SubscriptionServerTrait, *},
};
use http::header::{ACCESS_CONTROL_ALLOW_ORIGIN, CONTENT_TYPE};
use http::{HeaderValue, Response, StatusCode};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Mutex;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::handshake::server::Request;
use crate::connection::GraphQlConnection;
/// A GraphQL subscription server based on Hyper / Websockets.
pub struct SubscriptionServer<Q, S> {
logger: Logger,
graphql_runner: Arc<Q>,
store: Arc<S>,
}
impl<Q, S> SubscriptionServer<Q, S>
where
Q: GraphQlRunner,
S: QueryStoreManager,
{
pub fn new(logger: &Logger, graphql_runner: Arc<Q>, store: Arc<S>) -> Self {
SubscriptionServer {
logger: logger.new(o!("component" => "SubscriptionServer")),
graphql_runner,
store,
}
}
async fn subgraph_id_from_url_path(
store: Arc<S>,
path: &str,
) -> Result<Option<DeploymentState>, Error> {
fn target_from_name(name: String) -> Option<QueryTarget> {
SubgraphName::new(name).ok().map(QueryTarget::Name)
}
fn target_from_id(id: &str) -> Option<QueryTarget> {
DeploymentHash::new(id).ok().map(QueryTarget::Deployment)
}
async fn state<S: QueryStoreManager>(
store: Arc<S>,
target: Option<QueryTarget>,
) -> Option<DeploymentState> {
let target = match target {
Some(target) => target,
None => return None,
};
match store.query_store(target, false).await.ok() {
Some(query_store) => query_store.deployment_state().await.ok(),
None => None,
}
}
let path_segments = {
let mut segments = path.split('/');
// Remove leading '/'
let first_segment = segments.next();
if first_segment != Some("") {
return Ok(None);
}
segments.collect::<Vec<_>>()
};
match path_segments.as_slice() {
&["subgraphs", "id", subgraph_id] => {
Ok(state(store, target_from_id(subgraph_id)).await)
}
&["subgraphs", "name", _] | &["subgraphs", "name", _, _] => {
Ok(state(store, target_from_name(path_segments[2..].join("/"))).await)
}
&["subgraphs", "network", _, _] => {
Ok(state(store, target_from_name(path_segments[1..].join("/"))).await)
}
_ => Ok(None),
}
}
}
#[async_trait]
impl<Q, S> SubscriptionServerTrait for SubscriptionServer<Q, S>
where
Q: GraphQlRunner,
S: QueryStoreManager,
{
async fn serve(self, port: u16) {
info!(
self.logger,
"Starting GraphQL WebSocket server at: ws://localhost:{}", port
);
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port);
let socket = TcpListener::bind(&addr)
.await
.expect("Failed to bind WebSocket port");
loop {
let stream = match socket.accept().await {
Ok((stream, _)) => stream,
Err(e) => {
trace!(self.logger, "Connection error: {}", e);
continue;
}
};
let logger = self.logger.clone();
let logger2 = self.logger.clone();
let graphql_runner = self.graphql_runner.clone();
let store = self.store.clone();
// Subgraph that the request is resolved to (if any)
let subgraph_id = Arc::new(Mutex::new(None));
let accept_subgraph_id = subgraph_id.clone();
accept_hdr_async(stream, move |request: &Request, mut response: Response<()>| {
// Try to obtain the subgraph ID or name from the URL path.
// Return a 404 if the URL path contains no name/ID segment.
let path = request.uri().path();
// `block_in_place` is not recommended but in this case we have no alternative since
// we're in an async context but `tokio_tungstenite` doesn't allow this callback
// to be a future.
let state = tokio::task::block_in_place(|| {
graph::block_on(Self::subgraph_id_from_url_path(
store.clone(),
path.as_ref(),
))
})
.map_err(|e| {
error!(
logger,
"Error resolving subgraph ID from URL path";
"error" => e.to_string()
);
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(CONTENT_TYPE, "text/plain")
.body(None)
.unwrap()
})
.and_then(|state| {
state.ok_or_else(|| {
Response::builder()
.status(StatusCode::NOT_FOUND)
.header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(CONTENT_TYPE, "text/plain")
.body(None)
.unwrap()
})
})?;
// Check if the subgraph is deployed
if !state.is_deployed() {
error!(logger, "Failed to establish WS connection, no data found for subgraph";
"subgraph_id" => state.id.to_string(),
);
return Err(Response::builder()
.status(StatusCode::NOT_FOUND)
.header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(CONTENT_TYPE, "text/plain")
.body(None)
.unwrap());
}
*accept_subgraph_id.lock().unwrap() = Some(state.id);
response.headers_mut().insert(
"Sec-WebSocket-Protocol",
HeaderValue::from_static("graphql-ws"),
);
Ok(response)
})
.then(move |result| async move {
match result {
Ok(ws_stream) => {
// Obtain the subgraph ID or name that we resolved the request to
let subgraph_id = subgraph_id.lock().unwrap().clone().unwrap();
// Spawn a GraphQL over WebSocket connection
let service = GraphQlConnection::new(
&logger2,
subgraph_id,
ws_stream,
graphql_runner.clone(),
);
graph::spawn_allow_panic(service.into_future().compat());
}
Err(e) => {
// We gracefully skip over failed connection attempts rather
// than tearing down the entire stream
trace!(logger2, "Failed to establish WebSocket connection: {}", e);
}
}
}).await
}
}
}