Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor defer studio subgraph resolution until execution #2311

Merged
merged 5 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -247,5 +247,6 @@ reqwest = { workspace = true, features = ["native-tls-vendored"] }
rstest = { workspace = true }
serial_test = { workspace = true }
speculoos = { workspace = true }
tower-test = { workspace = true }
tracing-test = { workspace = true }
temp-env = { version = "0.3.6", features = ["async_closure"] }
2 changes: 2 additions & 0 deletions crates/rover-client/src/operations/subgraph/fetch/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod runner;
mod service;
mod types;

pub use runner::run;
pub use service::{SubgraphFetch, SubgraphFetchRequest};
pub use types::SubgraphFetchInput;
171 changes: 13 additions & 158 deletions crates/rover-client/src/operations/subgraph/fetch/runner.rs
Original file line number Diff line number Diff line change
@@ -1,168 +1,23 @@
use super::types::*;
use tower::{Service, ServiceExt};

use crate::blocking::StudioClient;
use crate::shared::{FetchResponse, Sdl, SdlType};
use crate::shared::FetchResponse;
use crate::RoverClientError;

use graphql_client::*;

#[derive(GraphQLQuery)]
// The paths are relative to the directory where your `Cargo.toml` is located.
// Both json and the GraphQL schema language are supported as sources for the schema
#[graphql(
query_path = "src/operations/subgraph/fetch/fetch_query.graphql",
schema_path = ".schema/schema.graphql",
response_derives = "Eq, PartialEq, Debug, Serialize, Deserialize",
deprecated = "warn"
)]
/// This struct is used to generate the module containing `Variables` and
/// `ResponseData` structs.
/// Snake case of this name is the mod name. i.e. subgraph_fetch_query
pub(crate) struct SubgraphFetchQuery;
use super::service::{SubgraphFetch, SubgraphFetchRequest};
use super::types::*;

/// Fetches a schema from apollo studio and returns its SDL (String)
pub async fn run(
input: SubgraphFetchInput,
client: &StudioClient,
) -> Result<FetchResponse, RoverClientError> {
let variables = input.clone().into();
let response_data = client.post::<SubgraphFetchQuery>(variables).await?;
get_sdl_from_response_data(input, response_data)
}

fn get_sdl_from_response_data(
input: SubgraphFetchInput,
response_data: SubgraphFetchResponseData,
) -> Result<FetchResponse, RoverClientError> {
let subgraph = get_subgraph_from_response_data(input, response_data)?;
Ok(FetchResponse {
sdl: Sdl {
contents: subgraph.sdl,
r#type: SdlType::Subgraph {
routing_url: subgraph.url,
},
},
})
}

#[derive(Debug, PartialEq)]
struct Subgraph {
url: Option<String>,
sdl: String,
}

fn get_subgraph_from_response_data(
input: SubgraphFetchInput,
response_data: SubgraphFetchResponseData,
) -> Result<Subgraph, RoverClientError> {
if let Some(maybe_variant) = response_data.variant {
match maybe_variant {
SubgraphFetchGraphVariant::GraphVariant(variant) => {
if let Some(subgraph) = variant.subgraph {
Ok(Subgraph {
url: subgraph.url.clone(),
sdl: subgraph.active_partial_schema.sdl,
})
} else if let Some(subgraphs) = variant.subgraphs {
let valid_subgraphs = subgraphs
.iter()
.map(|subgraph| subgraph.name.clone())
.collect();
Err(RoverClientError::NoSubgraphInGraph {
invalid_subgraph: input.subgraph_name,
valid_subgraphs,
})
} else {
Err(RoverClientError::ExpectedFederatedGraph {
graph_ref: input.graph_ref,
can_operation_convert: true,
})
}
}
_ => Err(RoverClientError::InvalidGraphRef),
}
} else {
Err(RoverClientError::GraphNotFound {
graph_ref: input.graph_ref,
})
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::shared::GraphRef;
use serde_json::json;

#[test]
fn get_services_from_response_data_works() {
let sdl = "extend type User @key(fields: \"id\") {\n id: ID! @external\n age: Int\n}\n"
.to_string();
let url = "http://my.subgraph.com".to_string();
let input = mock_input();
let json_response = json!({
"variant": {
"__typename": "GraphVariant",
"subgraphs": [
{ "name": "accounts" },
{ "name": &input.subgraph_name }
],
"subgraph": {
"url": &url,
"activePartialSchema": {
"sdl": &sdl
}
}
}
});
let data: SubgraphFetchResponseData = serde_json::from_value(json_response).unwrap();
let expected_subgraph = Subgraph {
url: Some(url),
sdl,
};
let output = get_subgraph_from_response_data(input, data);

assert!(output.is_ok());
assert_eq!(output.unwrap(), expected_subgraph);
}

#[test]
fn get_services_from_response_data_errs_with_no_variant() {
let json_response = json!({ "variant": null });
let data: SubgraphFetchResponseData = serde_json::from_value(json_response).unwrap();
let output = get_subgraph_from_response_data(mock_input(), data);
assert!(output.is_err());
}

#[test]
fn get_sdl_for_service_errs_on_invalid_name() {
let input = mock_input();
let json_response = json!({
"variant": {
"__typename": "GraphVariant",
"subgraphs": [
{ "name": "accounts" },
{ "name": &input.subgraph_name }
],
"subgraph": null
}
});
let data: SubgraphFetchResponseData = serde_json::from_value(json_response).unwrap();
let output = get_subgraph_from_response_data(input, data);

assert!(output.is_err());
}

fn mock_input() -> SubgraphFetchInput {
let graph_ref = GraphRef {
name: "mygraph".to_string(),
variant: "current".to_string(),
};

let subgraph_name = "products".to_string();

SubgraphFetchInput {
graph_ref,
subgraph_name,
}
}
let mut service = SubgraphFetch::new(
client
.service()
.map_err(|err| RoverClientError::ServiceError(Box::new(err)))?,
);
let service = service.ready().await?;
let fetch_response = service.call(SubgraphFetchRequest::from(input)).await?;
Ok(fetch_response)
}
Loading
Loading