1use std::{
2 future::IntoFuture,
3 marker::PhantomData,
4 net::{Ipv4Addr, SocketAddr, SocketAddrV4},
5 path::Path,
6 time::Duration,
7};
8
9use super::TestConfig;
10use async_tungstenite::tungstenite::handshake::client::Request;
11use futures_util::{stream::BoxStream, StreamExt};
12use grafbase_sdk_mock::{MockGraphQlServer, MockSubgraph};
13use graphql_composition::{LoadedExtension, Subgraphs};
14use graphql_ws_client::graphql::GraphqlOperation;
15use http::{
16 header::{IntoHeaderName, SEC_WEBSOCKET_PROTOCOL},
17 HeaderValue,
18};
19use serde::de::DeserializeOwned;
20use tempfile::TempDir;
21use tungstenite::client::IntoClientRequest;
22use url::Url;
23
24pub struct TestRunner {
26 http_client: reqwest::Client,
27 config: TestConfig,
28 gateway_handle: Option<duct::Handle>,
29 gateway_listen_address: SocketAddr,
30 gateway_endpoint: Url,
31 test_specific_temp_dir: TempDir,
32 _mock_subgraphs: Vec<MockGraphQlServer>,
33 federated_graph: String,
34}
35
36#[derive(Debug, serde::Deserialize)]
37struct ExtensionToml {
38 extension: ExtensionDefinition,
39}
40
41#[derive(Debug, serde::Deserialize)]
42struct ExtensionDefinition {
43 name: String,
44}
45
46#[allow(clippy::panic)]
47impl TestRunner {
48 pub async fn new(mut config: TestConfig) -> anyhow::Result<Self> {
50 let test_specific_temp_dir = tempfile::Builder::new().prefix("sdk-tests").tempdir()?;
51 let gateway_listen_address = listen_address()?;
52 let gateway_endpoint = Url::parse(&format!("http://{}/graphql", gateway_listen_address))?;
53
54 let extension_toml_path = std::env::current_dir()?.join("extension.toml");
55 let extension_toml = std::fs::read_to_string(&extension_toml_path)?;
56 let extension_toml: ExtensionToml = toml::from_str(&extension_toml)?;
57 let extension_name = extension_toml.extension.name;
58
59 let mut mock_subgraphs = Vec::new();
60 let mut subgraphs = Subgraphs::default();
61
62 let extension_path = match config.extension_path {
63 Some(ref path) => path.to_path_buf(),
64 None => std::env::current_dir()?.join("build"),
65 };
66
67 subgraphs.ingest_loaded_extensions(std::iter::once(LoadedExtension::new(
68 format!("file://{}", extension_path.display()),
69 extension_name.clone(),
70 )));
71
72 for subgraph in config.mock_subgraphs.drain(..) {
73 match subgraph {
74 MockSubgraph::Dynamic(subgraph) => {
75 let mock_graph = subgraph.start().await;
76 subgraphs.ingest_str(mock_graph.sdl(), mock_graph.name(), Some(mock_graph.url().as_str()))?;
77 mock_subgraphs.push(mock_graph);
78 }
79 MockSubgraph::ExtensionOnly(subgraph) => {
80 subgraphs.ingest_str(subgraph.sdl(), subgraph.name(), None)?;
81 }
82 }
83 }
84
85 let federated_graph = graphql_composition::compose(&subgraphs).into_result().unwrap();
86 let federated_graph = graphql_federated_graph::render_federated_sdl(&federated_graph)?;
87
88 let mut this = Self {
89 http_client: reqwest::Client::new(),
90 config,
91 gateway_handle: None,
92 gateway_listen_address,
93 gateway_endpoint,
94 test_specific_temp_dir,
95 _mock_subgraphs: mock_subgraphs,
96 federated_graph,
97 };
98
99 if this.config.extension_path.is_none() {
100 this.build_extension(&extension_path)?;
101 }
102
103 this.start_servers(&extension_name, &extension_path).await?;
104
105 Ok(this)
106 }
107
108 async fn start_servers(&mut self, extension_name: &str, extension_path: &Path) -> anyhow::Result<()> {
109 let extension_path = extension_path.display();
110 let config_path = self.test_specific_temp_dir.path().join("grafbase.toml");
111 let schema_path = self.test_specific_temp_dir.path().join("federated-schema.graphql");
112 let config = &self.config.gateway_configuration;
113 let enable_stdout = self.config.enable_stdout;
114 let enable_stderr = self.config.enable_stdout;
115 let enable_networking = self.config.enable_networking;
116 let enable_environment_variables = self.config.enable_environment_variables;
117 let max_pool_size = self.config.max_pool_size.unwrap_or(100);
118
119 let config = indoc::formatdoc! {r#"
120 [extensions.{extension_name}]
121 path = "{extension_path}"
122 stdout = {enable_stdout}
123 stderr = {enable_stderr}
124 networking = {enable_networking}
125 environment_variables = {enable_environment_variables}
126 max_pool_size = {max_pool_size}
127
128 {config}
129 "#};
130
131 println!("{config}");
132
133 std::fs::write(&config_path, config.as_bytes())?;
134 std::fs::write(&schema_path, self.federated_graph.as_bytes())?;
135
136 let args = &[
137 "--listen-address",
138 &self.gateway_listen_address.to_string(),
139 "--config",
140 &config_path.to_string_lossy(),
141 "--schema",
142 &schema_path.to_string_lossy(),
143 "--log",
144 self.config.log_level.as_ref(),
145 ];
146
147 let mut expr = duct::cmd(&self.config.gateway_path, args);
148
149 if !self.config.enable_stderr {
150 expr = expr.stderr_capture();
151 }
152
153 if !self.config.enable_stdout {
154 expr = expr.stdout_capture();
155 }
156
157 let gateway_handle = expr.unchecked().start()?;
158
159 let mut i = 0;
160 while !self.check_gateway_health().await? {
161 if i % 10 == 0 {
163 match gateway_handle.try_wait() {
164 Ok(Some(output)) => panic!(
165 "Gateway process exited unexpectedly: {:?}\n{}\n{}",
166 output.status,
167 String::from_utf8_lossy(&output.stdout),
168 String::from_utf8_lossy(&output.stderr)
169 ),
170 Ok(None) => (),
171 Err(err) => panic!("Error waiting for gateway process: {}", err),
172 }
173 println!("Waiting for gateway to be ready...");
174 }
175 i += 1;
176 std::thread::sleep(Duration::from_millis(100));
177 }
178
179 self.gateway_handle = Some(gateway_handle);
180
181 Ok(())
182 }
183
184 async fn check_gateway_health(&self) -> anyhow::Result<bool> {
185 let url = self.gateway_endpoint.join("/health")?;
186
187 let Ok(result) = self.http_client.get(url).send().await else {
188 return Ok(false);
189 };
190
191 let result = result.error_for_status().is_ok();
192
193 Ok(result)
194 }
195
196 fn build_extension(&mut self, extension_path: &Path) -> anyhow::Result<()> {
197 let extension_path = extension_path.to_string_lossy();
198
199 let mut lock_file = fslock::LockFile::open(".build.lock")?;
202 lock_file.lock()?;
203
204 let args = &["extension", "build", "--debug", "--output-dir", &*extension_path];
205 let mut expr = duct::cmd(&self.config.cli_path, args);
206
207 if !self.config.enable_stdout {
208 expr = expr.stdout_capture();
209 }
210
211 if !self.config.enable_stderr {
212 expr = expr.stderr_capture();
213 }
214
215 let output = expr.unchecked().run()?;
216 if !output.status.success() {
217 panic!(
218 "Failed to build extension: {}\n{}\n{}",
219 output.status,
220 String::from_utf8_lossy(&output.stdout),
221 String::from_utf8_lossy(&output.stderr)
222 );
223 }
224
225 lock_file.unlock()?;
226
227 Ok(())
228 }
229
230 pub fn graphql_query<Response>(&self, query: impl Into<String>) -> QueryBuilder<Response> {
240 let reqwest_builder = self
241 .http_client
242 .post(self.gateway_endpoint.clone())
243 .header(http::header::ACCEPT, "application/json");
244
245 QueryBuilder {
246 query: query.into(),
247 variables: None,
248 phantom: PhantomData,
249 reqwest_builder,
250 }
251 }
252
253 pub fn graphql_subscription<Response>(
262 &self,
263 query: impl Into<String>,
264 ) -> anyhow::Result<SubscriptionBuilder<Response>> {
265 let mut url = self.gateway_endpoint.clone();
266
267 url.set_path("/ws");
268 url.set_scheme("ws").unwrap();
269
270 let mut request_builder = url.as_ref().into_client_request()?;
271
272 request_builder
273 .headers_mut()
274 .insert(SEC_WEBSOCKET_PROTOCOL, HeaderValue::from_static("graphql-transport-ws"));
275
276 let operation = Operation {
277 query: query.into(),
278 variables: None,
279 phantom: PhantomData,
280 };
281
282 Ok(SubscriptionBuilder {
283 operation,
284 request_builder,
285 })
286 }
287
288 pub fn federated_graph(&self) -> &str {
290 &self.federated_graph
291 }
292}
293
294pub(crate) fn free_port() -> anyhow::Result<u16> {
295 const INITIAL_PORT: u16 = 14712;
296
297 let test_dir = std::env::temp_dir().join("grafbase/sdk-tests");
298 std::fs::create_dir_all(&test_dir)?;
299
300 let lock_file_path = test_dir.join("port-number.lock");
301 let port_number_file_path = test_dir.join("port-number.txt");
302
303 let mut lock_file = fslock::LockFile::open(&lock_file_path)?;
304 lock_file.lock()?;
305
306 let port = if port_number_file_path.exists() {
307 std::fs::read_to_string(&port_number_file_path)?.trim().parse::<u16>()? + 1
308 } else {
309 INITIAL_PORT
310 };
311
312 std::fs::write(&port_number_file_path, port.to_string())?;
313 lock_file.unlock()?;
314
315 Ok(port)
316}
317
318pub(crate) fn listen_address() -> anyhow::Result<SocketAddr> {
319 let port = free_port()?;
320 Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port)))
321}
322
323impl Drop for TestRunner {
324 fn drop(&mut self) {
325 let Some(handle) = self.gateway_handle.take() else {
326 return;
327 };
328
329 if let Err(err) = handle.kill() {
330 eprintln!("Failed to kill grafbase-gateway: {}", err)
331 }
332 }
333}
334
335#[derive(serde::Serialize)]
336#[must_use]
337pub struct QueryBuilder<Response> {
339 query: String,
341 #[serde(skip_serializing_if = "Option::is_none")]
342 variables: Option<serde_json::Value>,
343
344 #[serde(skip)]
346 phantom: PhantomData<fn() -> Response>,
347 #[serde(skip)]
348 reqwest_builder: reqwest::RequestBuilder,
349}
350
351impl<Response> QueryBuilder<Response> {
352 pub fn with_variables(mut self, variables: impl serde::Serialize) -> Self {
358 self.variables = Some(serde_json::to_value(variables).unwrap());
359 self
360 }
361
362 pub fn with_header(self, name: &str, value: &str) -> Self {
364 let Self {
365 phantom,
366 query,
367 mut reqwest_builder,
368 variables,
369 } = self;
370
371 reqwest_builder = reqwest_builder.header(name, value);
372
373 Self {
374 query,
375 variables,
376 phantom,
377 reqwest_builder,
378 }
379 }
380
381 pub async fn send(self) -> anyhow::Result<Response>
394 where
395 Response: for<'de> serde::Deserialize<'de>,
396 {
397 let json = serde_json::to_value(&self)?;
398 Ok(self.reqwest_builder.json(&json).send().await?.json().await?)
399 }
400}
401
402#[must_use]
403pub struct SubscriptionBuilder<Response> {
405 operation: Operation<Response>,
406 request_builder: Request,
407}
408
409#[derive(serde::Serialize)]
410struct Operation<Response> {
411 query: String,
412 #[serde(skip_serializing_if = "Option::is_none")]
413 variables: Option<serde_json::Value>,
414 #[serde(skip)]
415 phantom: PhantomData<fn() -> Response>,
416}
417
418impl<Response> GraphqlOperation for Operation<Response>
419where
420 Response: DeserializeOwned,
421{
422 type Response = Response;
423 type Error = serde_json::Error;
424
425 fn decode(&self, data: serde_json::Value) -> Result<Self::Response, Self::Error> {
426 serde_json::from_value(data)
427 }
428}
429
430impl<Response> SubscriptionBuilder<Response>
431where
432 Response: DeserializeOwned + 'static,
433{
434 pub fn with_variables(mut self, variables: impl serde::Serialize) -> Self {
440 self.operation.variables = Some(serde_json::to_value(variables).unwrap());
441 self
442 }
443
444 pub fn with_header<K>(mut self, name: K, value: HeaderValue) -> Self
451 where
452 K: IntoHeaderName,
453 {
454 self.request_builder.headers_mut().insert(name, value);
455 self
456 }
457
458 pub async fn subscribe(self) -> anyhow::Result<BoxStream<'static, Response>> {
470 let (connection, _) = async_tungstenite::tokio::connect_async(self.request_builder).await?;
471 let (client, actor) = graphql_ws_client::Client::build(connection).await?;
472
473 tokio::spawn(actor.into_future());
474
475 let stream = client
476 .subscribe(self.operation)
477 .await?
478 .map(move |item| -> Response { item.unwrap() });
479
480 Ok(Box::pin(stream))
481 }
482}