grafbase_sdk/test/
runner.rs

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::{StreamExt, stream::BoxStream};
12use grafbase_sdk_mock::{MockGraphQlServer, MockSubgraph};
13use graphql_composition::{LoadedExtension, Subgraphs};
14use graphql_ws_client::graphql::GraphqlOperation;
15use http::{
16    HeaderValue,
17    header::{IntoHeaderName, SEC_WEBSOCKET_PROTOCOL},
18};
19use serde::de::DeserializeOwned;
20use tempfile::TempDir;
21use tungstenite::client::IntoClientRequest;
22use url::Url;
23
24/// A test runner that can start a gateway and execute GraphQL queries against it.
25pub 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    /// Creates a new [`TestRunner`] with the given [`TestConfig`].
49    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)
104            .await
105            .map_err(|err| anyhow::anyhow!("Failed to start servers: {err}"))?;
106
107        Ok(this)
108    }
109
110    async fn start_servers(&mut self, extension_name: &str, extension_path: &Path) -> anyhow::Result<()> {
111        let extension_path = extension_path.display();
112        let config_path = self.test_specific_temp_dir.path().join("grafbase.toml");
113        let schema_path = self.test_specific_temp_dir.path().join("federated-schema.graphql");
114        let config = &self.config.gateway_configuration;
115        let enable_stdout = self.config.enable_stdout;
116        let enable_stderr = self.config.enable_stdout;
117        let enable_networking = self.config.enable_networking;
118        let enable_environment_variables = self.config.enable_environment_variables;
119        let max_pool_size = self.config.max_pool_size.unwrap_or(100);
120
121        let config = indoc::formatdoc! {r#"
122            [extensions.{extension_name}]
123            path = "{extension_path}"
124            stdout = {enable_stdout}
125            stderr = {enable_stderr}
126            networking = {enable_networking}
127            environment_variables = {enable_environment_variables}
128            max_pool_size = {max_pool_size}
129
130            {config}
131        "#};
132
133        println!("{config}");
134
135        std::fs::write(&config_path, config.as_bytes())
136            .map_err(|err| anyhow::anyhow!("Failed to write config at {:?}: {err}", config_path))?;
137        std::fs::write(&schema_path, self.federated_graph.as_bytes())
138            .map_err(|err| anyhow::anyhow!("Failed to write schema at {:?}: {err}", schema_path))?;
139
140        let args = &[
141            "--listen-address",
142            &self.gateway_listen_address.to_string(),
143            "--config",
144            &config_path.to_string_lossy(),
145            "--schema",
146            &schema_path.to_string_lossy(),
147            "--log",
148            self.config.log_level.as_ref(),
149        ];
150
151        let mut expr = duct::cmd(&self.config.gateway_path, args);
152
153        if !self.config.enable_stderr {
154            expr = expr.stderr_capture();
155        }
156
157        if !self.config.enable_stdout {
158            expr = expr.stdout_capture();
159        }
160
161        let gateway_handle = expr
162            .unchecked()
163            .start()
164            .map_err(|err| anyhow::anyhow!("Failed to start the gateway: {err}"))?;
165
166        let mut i = 0;
167        while !self.check_gateway_health().await? {
168            // printing every second only
169            if i % 10 == 0 {
170                match gateway_handle.try_wait() {
171                    Ok(Some(output)) => panic!(
172                        "Gateway process exited unexpectedly: {:?}\n{}\n{}",
173                        output.status,
174                        String::from_utf8_lossy(&output.stdout),
175                        String::from_utf8_lossy(&output.stderr)
176                    ),
177                    Ok(None) => (),
178                    Err(err) => panic!("Error waiting for gateway process: {}", err),
179                }
180                println!("Waiting for gateway to be ready...");
181            }
182            i += 1;
183            std::thread::sleep(Duration::from_millis(100));
184        }
185
186        self.gateway_handle = Some(gateway_handle);
187
188        Ok(())
189    }
190
191    async fn check_gateway_health(&self) -> anyhow::Result<bool> {
192        let url = self.gateway_endpoint.join("/health")?;
193
194        let Ok(result) = self.http_client.get(url).send().await else {
195            return Ok(false);
196        };
197
198        let result = result.error_for_status().is_ok();
199
200        Ok(result)
201    }
202
203    fn build_extension(&mut self, extension_path: &Path) -> anyhow::Result<()> {
204        let extension_path = extension_path.to_string_lossy();
205
206        // Only one test can build the extension at a time. The others must
207        // wait.
208        let mut lock_file = fslock::LockFile::open(".build.lock")?;
209        lock_file.lock()?;
210
211        let args = &["extension", "build", "--debug", "--output-dir", &*extension_path];
212        let mut expr = duct::cmd(&self.config.cli_path, args);
213
214        if !self.config.enable_stdout {
215            expr = expr.stdout_capture();
216        }
217
218        if !self.config.enable_stderr {
219            expr = expr.stderr_capture();
220        }
221
222        let output = expr.unchecked().run()?;
223        if !output.status.success() {
224            panic!(
225                "Failed to build extension: {}\n{}\n{}",
226                output.status,
227                String::from_utf8_lossy(&output.stdout),
228                String::from_utf8_lossy(&output.stderr)
229            );
230        }
231
232        lock_file.unlock()?;
233
234        Ok(())
235    }
236
237    /// Creates a new GraphQL query builder with the given query.
238    ///
239    /// # Arguments
240    ///
241    /// * `query` - The GraphQL query string to execute
242    ///
243    /// # Returns
244    ///
245    /// A [`QueryBuilder`] that can be used to customize and execute the query
246    pub fn graphql_query<Response>(&self, query: impl Into<String>) -> QueryBuilder<Response> {
247        let reqwest_builder = self
248            .http_client
249            .post(self.gateway_endpoint.clone())
250            .header(http::header::ACCEPT, "application/json");
251
252        QueryBuilder {
253            query: query.into(),
254            variables: None,
255            phantom: PhantomData,
256            reqwest_builder,
257        }
258    }
259
260    ///
261    /// # Arguments
262    ///
263    /// * `query` - The GraphQL subscription query string to execute
264    ///
265    /// # Returns
266    ///
267    /// A [`SubscriptionBuilder`] that can be used to customize and execute the subscription
268    pub fn graphql_subscription<Response>(
269        &self,
270        query: impl Into<String>,
271    ) -> anyhow::Result<SubscriptionBuilder<Response>> {
272        let mut url = self.gateway_endpoint.clone();
273
274        url.set_path("/ws");
275        url.set_scheme("ws").unwrap();
276
277        let mut request_builder = url.as_ref().into_client_request()?;
278
279        request_builder
280            .headers_mut()
281            .insert(SEC_WEBSOCKET_PROTOCOL, HeaderValue::from_static("graphql-transport-ws"));
282
283        let operation = Operation {
284            query: query.into(),
285            variables: None,
286            phantom: PhantomData,
287        };
288
289        Ok(SubscriptionBuilder {
290            operation,
291            request_builder,
292        })
293    }
294
295    /// Returns the federated schema as a string.
296    pub fn federated_graph(&self) -> &str {
297        &self.federated_graph
298    }
299}
300
301pub(crate) fn free_port() -> anyhow::Result<u16> {
302    const INITIAL_PORT: u16 = 14712;
303
304    let test_dir = std::env::temp_dir().join("grafbase/sdk-tests");
305    std::fs::create_dir_all(&test_dir)?;
306
307    let lock_file_path = test_dir.join("port-number.lock");
308    let port_number_file_path = test_dir.join("port-number.txt");
309
310    let mut lock_file = fslock::LockFile::open(&lock_file_path)?;
311    lock_file.lock()?;
312
313    let port = if port_number_file_path.exists() {
314        std::fs::read_to_string(&port_number_file_path)?.trim().parse::<u16>()? + 1
315    } else {
316        INITIAL_PORT
317    };
318
319    std::fs::write(&port_number_file_path, port.to_string())?;
320    lock_file.unlock()?;
321
322    Ok(port)
323}
324
325pub(crate) fn listen_address() -> anyhow::Result<SocketAddr> {
326    let port = free_port()?;
327    Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port)))
328}
329
330impl Drop for TestRunner {
331    fn drop(&mut self) {
332        let Some(handle) = self.gateway_handle.take() else {
333            return;
334        };
335
336        if let Err(err) = handle.kill() {
337            eprintln!("Failed to kill grafbase-gateway: {}", err)
338        }
339    }
340}
341
342#[derive(serde::Serialize)]
343#[must_use]
344/// A builder for constructing GraphQL queries with customizable parameters and headers.
345pub struct QueryBuilder<Response> {
346    // These two will be serialized into the request
347    query: String,
348    #[serde(skip_serializing_if = "Option::is_none")]
349    variables: Option<serde_json::Value>,
350
351    // These won't
352    #[serde(skip)]
353    phantom: PhantomData<fn() -> Response>,
354    #[serde(skip)]
355    reqwest_builder: reqwest::RequestBuilder,
356}
357
358impl<Response> QueryBuilder<Response> {
359    /// Adds variables to the GraphQL query.
360    ///
361    /// # Arguments
362    ///
363    /// * `variables` - The variables to include with the query, serializable to JSON
364    pub fn with_variables(mut self, variables: impl serde::Serialize) -> Self {
365        self.variables = Some(serde_json::to_value(variables).unwrap());
366        self
367    }
368
369    /// Adds a header to the GraphQL request.
370    pub fn with_header(self, name: &str, value: &str) -> Self {
371        let Self {
372            phantom,
373            query,
374            mut reqwest_builder,
375            variables,
376        } = self;
377
378        reqwest_builder = reqwest_builder.header(name, value);
379
380        Self {
381            query,
382            variables,
383            phantom,
384            reqwest_builder,
385        }
386    }
387
388    /// Sends the GraphQL query and returns the response.
389    ///
390    /// # Returns
391    ///
392    /// The deserialized response from the GraphQL server
393    ///
394    /// # Errors
395    ///
396    /// Will return an error if:
397    /// - Request serialization fails
398    /// - Network request fails
399    /// - Response deserialization fails
400    pub async fn send(self) -> anyhow::Result<Response>
401    where
402        Response: for<'de> serde::Deserialize<'de>,
403    {
404        let json = serde_json::to_value(&self)?;
405        Ok(self.reqwest_builder.json(&json).send().await?.json().await?)
406    }
407}
408
409#[must_use]
410/// A builder for constructing GraphQL queries with customizable parameters and headers.
411pub struct SubscriptionBuilder<Response> {
412    operation: Operation<Response>,
413    request_builder: Request,
414}
415
416#[derive(serde::Serialize)]
417struct Operation<Response> {
418    query: String,
419    #[serde(skip_serializing_if = "Option::is_none")]
420    variables: Option<serde_json::Value>,
421    #[serde(skip)]
422    phantom: PhantomData<fn() -> Response>,
423}
424
425impl<Response> GraphqlOperation for Operation<Response>
426where
427    Response: DeserializeOwned,
428{
429    type Response = Response;
430    type Error = serde_json::Error;
431
432    fn decode(&self, data: serde_json::Value) -> Result<Self::Response, Self::Error> {
433        serde_json::from_value(data)
434    }
435}
436
437impl<Response> SubscriptionBuilder<Response>
438where
439    Response: DeserializeOwned + 'static,
440{
441    /// Adds variables to the GraphQL subscription.
442    ///
443    /// # Arguments
444    ///
445    /// * `variables` - The variables to include with the subscription, serializable to JSON
446    pub fn with_variables(mut self, variables: impl serde::Serialize) -> Self {
447        self.operation.variables = Some(serde_json::to_value(variables).unwrap());
448        self
449    }
450
451    /// Adds a header to the GraphQL request.
452    ///
453    /// # Arguments
454    ///
455    /// * `name` - The header name
456    /// * `value` - The header value
457    pub fn with_header<K>(mut self, name: K, value: HeaderValue) -> Self
458    where
459        K: IntoHeaderName,
460    {
461        self.request_builder.headers_mut().insert(name, value);
462        self
463    }
464
465    /// Subscribes to the GraphQL subscription and returns a stream of responses.
466    ///
467    /// # Returns
468    ///
469    /// A pinned stream that yields the deserialized subscription responses
470    ///
471    /// # Errors
472    ///
473    /// Will return an error if:
474    /// - WebSocket connection fails
475    /// - GraphQL subscription initialization fails
476    pub async fn subscribe(self) -> anyhow::Result<BoxStream<'static, Response>> {
477        let (connection, _) = async_tungstenite::tokio::connect_async(self.request_builder).await?;
478        let (client, actor) = graphql_ws_client::Client::build(connection).await?;
479
480        tokio::spawn(actor.into_future());
481
482        let stream = client
483            .subscribe(self.operation)
484            .await?
485            .map(move |item| -> Response { item.unwrap() });
486
487        Ok(Box::pin(stream))
488    }
489}