diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index ffe9f8cfc6..ee1f62be1c 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -96,14 +96,16 @@ At the crate root: In the `apollo_router::plugin::Plugin` trait: +* `router_service` → `supergraph_service` * `query_planning_service` → `query_planner_service` A new `apollo_router::stages` module replaces `apollo_router::services` in the public API, reexporting its items and adding `BoxService` and `BoxCloneService` type aliases. -In pseudo-syntax: +Additionally, the "router stage" is now known as "supergraph stage". +In pseudo-syntax, `use`’ing the old names: ```rust -mod router { +mod supergraph { use apollo_router::services::RouterRequest as Request; use apollo_router::services::RouterResponse as Response; type BoxService = tower::util::BoxService; diff --git a/apollo-router-benchmarks/src/shared.rs b/apollo-router-benchmarks/src/shared.rs index 17bb1d9247..16e8ecc51c 100644 --- a/apollo-router-benchmarks/src/shared.rs +++ b/apollo-router-benchmarks/src/shared.rs @@ -4,7 +4,7 @@ use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::plugin::test::MockSubgraph; -use apollo_router::stages::router; +use apollo_router::stages::supergraph; use apollo_router::stages::subgraph; use apollo_router::TestHarness; use apollo_router::graphql::Response; @@ -21,14 +21,14 @@ static EXPECTED_RESPONSE: Lazy = Lazy::new(|| { static QUERY: &str = r#"query TopProducts($first: Int) { topProducts(first: $first) { upc name reviews { id product { name } author { id name } } } }"#; pub async fn basic_composition_benchmark( - mut router_service: router::BoxCloneService, + mut supergraph_service: supergraph::BoxCloneService, ) { - let request = router::Request::fake_builder() + let request = supergraph::Request::fake_builder() .query(QUERY.to_string()) .variable("first", 2usize) .build().expect("expecting valid request"); - let response = router_service + let response = supergraph_service .ready() .await .unwrap() diff --git a/apollo-router-scaffold/templates/plugin/src/plugins/{{snake_name}}.rs b/apollo-router-scaffold/templates/plugin/src/plugins/{{snake_name}}.rs index d8713ba8ee..cd22d81fe2 100644 --- a/apollo-router-scaffold/templates/plugin/src/plugins/{{snake_name}}.rs +++ b/apollo-router-scaffold/templates/plugin/src/plugins/{{snake_name}}.rs @@ -1,7 +1,7 @@ use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; -use apollo_router::stages::router; +use apollo_router::stages::supergraph; {{#if type_basic}} use apollo_router::stages::execution; use apollo_router::stages::query_planner; @@ -47,10 +47,10 @@ impl Plugin for {{pascal_name}} { } // Delete this function if you are not customizing it. - fn router_service( + fn supergraph_service( &self, - service: router::BoxService, - ) -> router::BoxService { + service: supergraph::BoxService, + ) -> supergraph::BoxService { // Always use service builder to compose your plugins. // It provides off the shelf building blocks for your plugin. // @@ -99,13 +99,13 @@ impl Plugin for {{pascal_name}} { Ok({{pascal_name}} { configuration: init.config }) } - fn router_service( + fn supergraph_service( &self, - service: router::BoxService, - ) -> router::BoxService { + service: supergraph::BoxService, + ) -> supergraph::BoxService { ServiceBuilder::new() - .checkpoint_async(|request : router::Request| async { + .checkpoint_async(|request : supergraph::Request| async { // Do some async call here to auth, and decide if to continue or not. Ok(ControlFlow::Continue(request)) }) @@ -126,10 +126,10 @@ impl Plugin for {{pascal_name}} { Ok({{pascal_name}} { configuration: init.config }) } - fn router_service( + fn supergraph_service( &self, - service: router::BoxService, - ) -> router::BoxService { + service: supergraph::BoxService, + ) -> supergraph::BoxService { ServiceBuilder::new() .instrument(|_request| { @@ -155,7 +155,7 @@ register_plugin!("{{project_name}}", "{{snake_name}}", {{pascal_name}}); #[cfg(test)] mod tests { use apollo_router::TestHarness; - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use tower::BoxError; use tower::ServiceExt; @@ -173,7 +173,7 @@ mod tests { .build() .await .unwrap(); - let request = router::Request::canned_builder().build().unwrap(); + let request = supergraph::Request::canned_builder().build().unwrap(); let mut streamed_response = test_harness.oneshot(request).await?; let first_response = streamed_response diff --git a/apollo-router/src/axum_http_server_factory.rs b/apollo-router/src/axum_http_server_factory.rs index 42f916aa58..0466bff0ae 100644 --- a/apollo-router/src/axum_http_server_factory.rs +++ b/apollo-router/src/axum_http_server_factory.rs @@ -776,23 +776,23 @@ mod tests { mock! { #[derive(Debug)] - RouterService { + SupergraphService { fn service_call(&mut self, req: Request) -> Result>, BoxError>; } } - type MockRouterServiceType = tower_test::mock::Mock< + type MockSupergraphServiceType = tower_test::mock::Mock< http_ext::Request, http_ext::Response + Send>>>, >; #[derive(Clone)] struct TestRouterServiceFactory { - inner: MockRouterServiceType, + inner: MockSupergraphServiceType, } impl NewService> for TestRouterServiceFactory { - type Service = MockRouterServiceType; + type Service = MockSupergraphServiceType; fn new_service(&self) -> Self::Service { self.inner.clone() @@ -800,7 +800,7 @@ mod tests { } impl RouterServiceFactory for TestRouterServiceFactory { - type RouterService = MockRouterServiceType; + type RouterService = MockSupergraphServiceType; type Future = <, @@ -811,7 +811,7 @@ mod tests { } } - async fn init(mut mock: MockRouterService) -> (HttpServerHandle, Client) { + async fn init(mut mock: MockSupergraphService) -> (HttpServerHandle, Client) { let server_factory = AxumHttpServerFactory::new(); let (service, mut handle) = tower_test::mock::spawn(); @@ -856,7 +856,7 @@ mod tests { } async fn init_with_config( - mut mock: MockRouterService, + mut mock: MockSupergraphService, conf: Configuration, plugin_handlers: HashMap, ) -> (HttpServerHandle, Client) { @@ -897,7 +897,7 @@ mod tests { #[cfg(unix)] async fn init_unix( - mut mock: MockRouterService, + mut mock: MockSupergraphService, temp_dir: &tempfile::TempDir, ) -> HttpServerHandle { let server_factory = AxumHttpServerFactory::new(); @@ -943,7 +943,7 @@ mod tests { // let root_span = info_span!("root"); // { // let _guard = root_span.enter(); - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let (server, client) = init(expectations).await; // Regular studio redirect @@ -974,7 +974,7 @@ mod tests { .data(json!({"response": "yayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"})) // Body must be bigger than 32 to be compressed .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(2) @@ -1061,7 +1061,7 @@ mod tests { .data(json!({"response": "yayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"})) // Body must be bigger than 32 to be compressed .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(1) @@ -1103,7 +1103,7 @@ mod tests { #[tokio::test] async fn malformed_request() -> Result<(), ApolloRouterError> { - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let (server, client) = init(expectations).await; let response = client @@ -1127,7 +1127,7 @@ mod tests { .data(json!({"response": "yay"})) .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(2) @@ -1189,7 +1189,7 @@ mod tests { #[tokio::test] async fn bad_response() -> Result<(), ApolloRouterError> { - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let (server, client) = init(expectations).await; let url = format!("{}/test", server.listen_address()); @@ -1229,7 +1229,7 @@ mod tests { .data(json!({"response": "yay"})) .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(2) @@ -1298,7 +1298,7 @@ mod tests { .data(json!({"response": "yay"})) .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(2) @@ -1367,7 +1367,7 @@ mod tests { .data(json!({"response": "yay"})) .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(4) @@ -1451,7 +1451,7 @@ mod tests { .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(1) @@ -1511,7 +1511,7 @@ mod tests { .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(1) @@ -1554,7 +1554,7 @@ mod tests { #[tokio::test] async fn response_failure() -> Result<(), ApolloRouterError> { - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(1) @@ -1602,7 +1602,7 @@ mod tests { #[tokio::test] async fn cors_preflight() -> Result<(), ApolloRouterError> { - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let conf = Configuration::builder() .server( crate::configuration::Server::builder() @@ -1661,7 +1661,7 @@ mod tests { .build(); let example_response = expected_response.clone(); - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(2) @@ -1771,7 +1771,7 @@ Content-Type: application/json\r // let root_span = info_span!("root"); // { // let _guard = root_span.enter(); - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let (server, client) = init(expectations).await; let url = format!( "{}/.well-known/apollo/server-health", @@ -1797,7 +1797,7 @@ Content-Type: application/json\r .build(), ) .build(); - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let (server, client) = init_with_config(expectations, conf, HashMap::new()).await; let url = format!("{}/health", server.listen_address()); @@ -1810,7 +1810,7 @@ Content-Type: application/json\r let query = "query"; let operation_name = "operationName"; - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let (server, client) = init(expectations).await; let url = format!("{}", server.listen_address()); let response = client @@ -1828,7 +1828,7 @@ Content-Type: application/json\r #[test(tokio::test)] async fn it_doesnt_display_disabled_home_page() -> Result<(), ApolloRouterError> { - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let conf = Configuration::builder() .server( crate::configuration::Server::builder() @@ -1857,7 +1857,7 @@ Content-Type: application/json\r #[test(tokio::test)] async fn it_answers_to_custom_endpoint() -> Result<(), ApolloRouterError> { - let expectations = MockRouterService::new(); + let expectations = MockSupergraphService::new(); let plugin_handler = Handler::new( service_fn(|req: stages::http::Request| async move { Ok::<_, BoxError>(http_ext::Response { @@ -1935,7 +1935,7 @@ Content-Type: application/json\r #[test(tokio::test)] async fn it_checks_the_shape_of_router_request() -> Result<(), ApolloRouterError> { - let mut expectations = MockRouterService::new(); + let mut expectations = MockSupergraphService::new(); expectations .expect_service_call() .times(2) @@ -2002,7 +2002,7 @@ Content-Type: application/json\r #[tokio::test] async fn cors_origin_default() -> Result<(), ApolloRouterError> { - let (server, client) = init(MockRouterService::new()).await; + let (server, client) = init(MockSupergraphService::new()).await; let url = format!("{}/", server.listen_address()); let response = @@ -2027,7 +2027,7 @@ Content-Type: application/json\r ) .build(); let (server, client) = - init_with_config(MockRouterService::new(), conf, HashMap::new()).await; + init_with_config(MockSupergraphService::new(), conf, HashMap::new()).await; let url = format!("{}/", server.listen_address()); let response = @@ -2054,7 +2054,7 @@ Content-Type: application/json\r ) .build(); let (server, client) = - init_with_config(MockRouterService::new(), conf, HashMap::new()).await; + init_with_config(MockSupergraphService::new(), conf, HashMap::new()).await; let url = format!("{}/", server.listen_address()); let response = request_cors_with_origin(&client, url.as_str(), valid_origin).await; @@ -2085,7 +2085,7 @@ Content-Type: application/json\r ) .build(); let (server, client) = - init_with_config(MockRouterService::new(), conf, HashMap::new()).await; + init_with_config(MockSupergraphService::new(), conf, HashMap::new()).await; let url = format!("{}/", server.listen_address()); // regex tests diff --git a/apollo-router/src/layers/map_future_with_context.rs b/apollo-router/src/layers/map_future_with_context.rs index c7c39f3fb2..c1835add1c 100644 --- a/apollo-router/src/layers/map_future_with_context.rs +++ b/apollo-router/src/layers/map_future_with_context.rs @@ -85,21 +85,21 @@ mod test { use tower::ServiceExt; use crate::layers::ServiceBuilderExt; - use crate::plugin::test::MockRouterService; - use crate::RouterRequest; - use crate::RouterResponse; + use crate::plugin::test::MockSupergraphService; + use crate::SupergraphRequest; + use crate::SupergraphResponse; #[tokio::test] async fn test_layer() -> Result<(), BoxError> { - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); mock_service .expect_call() .once() - .returning(|_| Ok(RouterResponse::fake_builder().build().unwrap())); + .returning(|_| Ok(SupergraphResponse::fake_builder().build().unwrap())); let mut service = ServiceBuilder::new() .map_future_with_context( - |req: &RouterRequest| { + |req: &SupergraphRequest| { req.originating_request .headers() .get("hello") @@ -107,7 +107,7 @@ mod test { .unwrap() }, |ctx: HeaderValue, resp| async move { - let resp: Result = resp.await; + let resp: Result = resp.await; resp.map(|mut response| { response.response.headers_mut().insert("hello", ctx.clone()); response @@ -121,7 +121,7 @@ mod test { .await .unwrap() .call( - RouterRequest::fake_builder() + SupergraphRequest::fake_builder() .header("hello", "world") .build() .unwrap(), diff --git a/apollo-router/src/layers/mod.rs b/apollo-router/src/layers/mod.rs index ec3912c4f2..2104b2d5f6 100644 --- a/apollo-router/src/layers/mod.rs +++ b/apollo-router/src/layers/mod.rs @@ -54,15 +54,15 @@ pub trait ServiceBuilderExt: Sized { /// # use tower_service::Service; /// # use tracing::info_span; /// # use apollo_router::graphql::Response; - /// # use apollo_router::stages::router; + /// # use apollo_router::stages::supergraph; /// # use apollo_router::layers::ServiceBuilderExt; - /// # fn test(service: router::BoxService) { + /// # fn test(service: supergraph::BoxService) { /// //TODO This doc has highlighted a couple of issues that need to be resolved /// //let _ = ServiceBuilder::new() /// // .cache(Cache::builder().time_to_live(Duration::from_secs(1)).max_capacity(100).build(), - /// // |req: &RouterRequest| req.originating_request.headers().get("cache_key"), - /// // |resp: &RouterResponse| &resp.response.body(), - /// // |req: RouterRequest, cached: &ResponseBody| RouterResponse::builder() + /// // |req: &SupergraphRequest| req.originating_request.headers().get("cache_key"), + /// // |resp: &SupergraphResponse| &resp.response.body(), + /// // |req: SupergraphRequest, cached: &ResponseBody| SupergraphResponse::builder() /// // .context(req.context) /// // .data(cached.clone()) //TODO builder should take ResponseBody /// // .build().unwrap()) //TODO make response function fallible @@ -101,13 +101,13 @@ pub trait ServiceBuilderExt: Sized { /// # use tower::ServiceBuilder; /// # use tower_service::Service; /// # use tracing::info_span; - /// # use apollo_router::stages::router; + /// # use apollo_router::stages::supergraph; /// # use apollo_router::layers::ServiceBuilderExt; - /// # fn test(service: router::BoxService) { + /// # fn test(service: supergraph::BoxService) { /// let _ = ServiceBuilder::new() - /// .checkpoint(|req: router::Request|{ + /// .checkpoint(|req: supergraph::Request|{ /// if req.originating_request.method() == Method::GET { - /// Ok(ControlFlow::Break(router::Response::builder() + /// Ok(ControlFlow::Break(supergraph::Response::builder() /// .data("Only get requests allowed") /// .context(req.context) /// .build()?)) @@ -161,14 +161,14 @@ pub trait ServiceBuilderExt: Sized { /// # use tower::ServiceBuilder; /// # use tower_service::Service; /// # use tracing::info_span; - /// # use apollo_router::stages::router; + /// # use apollo_router::stages::supergraph; /// # use apollo_router::layers::ServiceBuilderExt; - /// # fn test(service: router::BoxService) { + /// # fn test(service: supergraph::BoxService) { /// let _ = ServiceBuilder::new() - /// .checkpoint_async(|req: router::Request| + /// .checkpoint_async(|req: supergraph::Request| /// async { /// if req.originating_request.method() == Method::GET { - /// Ok(ControlFlow::Break(router::Response::builder() + /// Ok(ControlFlow::Break(supergraph::Response::builder() /// .data("Only get requests allowed") /// .context(req.context) /// .build()?)) @@ -206,9 +206,9 @@ pub trait ServiceBuilderExt: Sized { /// # use tower::ServiceBuilder; /// # use tower_service::Service; /// # use tracing::info_span; - /// # use apollo_router::stages::router; + /// # use apollo_router::stages::supergraph; /// # use apollo_router::layers::ServiceBuilderExt; - /// # fn test(service: router::BoxService) { + /// # fn test(service: supergraph::BoxService) { /// let _ = ServiceBuilder::new() /// .buffered() /// .service(service); @@ -235,9 +235,9 @@ pub trait ServiceBuilderExt: Sized { /// # use tower::ServiceBuilder; /// # use tower_service::Service; /// # use tracing::info_span; - /// # use apollo_router::stages::router; + /// # use apollo_router::stages::supergraph; /// # use apollo_router::layers::ServiceBuilderExt; - /// # fn test(service: router::BoxService) { + /// # fn test(service: supergraph::BoxService) { /// let instrumented = ServiceBuilder::new() /// .instrument(|_request| info_span!("query_planning")) /// .service(service); @@ -272,12 +272,12 @@ pub trait ServiceBuilderExt: Sized { /// # use tower_service::Service; /// # use tracing::info_span; /// # use apollo_router::Context; - /// # use apollo_router::stages::router; + /// # use apollo_router::stages::supergraph; /// # use apollo_router::layers::ServiceBuilderExt; - /// # fn test(service: router::BoxService) { - /// let _ : router::BoxService = ServiceBuilder::new() + /// # fn test(service: supergraph::BoxService) { + /// let _ : supergraph::BoxService = ServiceBuilder::new() /// .map_future_with_context( - /// |req: &router::Request| req.context.clone(), + /// |req: &supergraph::Request| req.context.clone(), /// |ctx : Context, fut| async { fut.await }) /// .service(service) /// .boxed(); @@ -334,13 +334,13 @@ pub trait ServiceExt: Service { /// # use tower_service::Service; /// # use tracing::info_span; /// # use apollo_router::Context; - /// # use apollo_router::stages::router; + /// # use apollo_router::stages::supergraph; /// # use apollo_router::layers::ServiceBuilderExt; /// # use apollo_router::layers::ServiceExt as ApolloServiceExt; - /// # fn test(service: router::BoxService) { - /// let _ : router::BoxService = service + /// # fn test(service: supergraph::BoxService) { + /// let _ : supergraph::BoxService = service /// .map_future_with_context( - /// |req: &router::Request| req.context.clone(), + /// |req: &supergraph::Request| req.context.clone(), /// |ctx : Context, fut| async { fut.await } /// ) /// .boxed(); diff --git a/apollo-router/src/plugin/mod.rs b/apollo-router/src/plugin/mod.rs index fb9870b2db..141b377656 100644 --- a/apollo-router/src/plugin/mod.rs +++ b/apollo-router/src/plugin/mod.rs @@ -42,8 +42,8 @@ use crate::layers::ServiceBuilderExt; use crate::stages; use crate::stages::execution; use crate::stages::query_planner; -use crate::stages::router; use crate::stages::subgraph; +use crate::stages::supergraph; type InstanceFactory = fn(&serde_json::Value, Arc) -> BoxFuture, BoxError>>; @@ -163,9 +163,9 @@ pub trait Plugin: Send + Sync + 'static + Sized { fn activate(&mut self) {} /// This service runs at the very beginning and very end of the request lifecycle. - /// Define router_service if your customization needs to interact at the earliest or latest point possible. + /// Define supergraph_service if your customization needs to interact at the earliest or latest point possible. /// For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further. - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { service } @@ -228,9 +228,9 @@ pub(crate) trait DynPlugin: Send + Sync + 'static { /// This service runs at the very beginning and very end of the request lifecycle. /// It's the entrypoint of every requests and also the last hook before sending the response. - /// Define router_service if your customization needs to interact at the earliest or latest point possible. + /// Define supergraph_service if your customization needs to interact at the earliest or latest point possible. /// For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further. - fn router_service(&self, service: router::BoxService) -> router::BoxService; + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService; /// This service handles generating the query plan for each incoming request. /// Define `query_planner_service` if your customization needs to interact with query planning functionality (for example, to log query plan details). @@ -275,8 +275,8 @@ where self.activate() } - fn router_service(&self, service: router::BoxService) -> router::BoxService { - self.router_service(service) + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { + self.supergraph_service(service) } fn query_planner_service( diff --git a/apollo-router/src/plugin/test/mod.rs b/apollo-router/src/plugin/test/mod.rs index 6956036e2d..2733d06598 100644 --- a/apollo-router/src/plugin/test/mod.rs +++ b/apollo-router/src/plugin/test/mod.rs @@ -10,8 +10,8 @@ use std::sync::Arc; pub use mock::subgraph::MockSubgraph; pub use service::MockExecutionService; pub use service::MockQueryPlannerService; -pub use service::MockRouterService; pub use service::MockSubgraphService; +pub use service::MockSupergraphService; use tower::util::BoxService; use tower::BoxError; use tower::Service; diff --git a/apollo-router/src/plugin/test/service.rs b/apollo-router/src/plugin/test/service.rs index b631e509e3..b8cca03a5d 100644 --- a/apollo-router/src/plugin/test/service.rs +++ b/apollo-router/src/plugin/test/service.rs @@ -3,10 +3,10 @@ use crate::ExecutionRequest; use crate::ExecutionResponse; use crate::QueryPlannerRequest; use crate::QueryPlannerResponse; -use crate::RouterRequest; -use crate::RouterResponse; use crate::SubgraphRequest; use crate::SubgraphResponse; +use crate::SupergraphRequest; +use crate::SupergraphResponse; /// Build a mock service handler for the router pipeline. macro_rules! mock_service { @@ -43,7 +43,7 @@ macro_rules! mock_service { }; } -mock_service!(Router, RouterRequest, RouterResponse); +mock_service!(Supergraph, SupergraphRequest, SupergraphResponse); mock_service!(QueryPlanner, QueryPlannerRequest, QueryPlannerResponse); mock_service!(Execution, ExecutionRequest, ExecutionResponse); mock_service!(Subgraph, SubgraphRequest, SubgraphResponse); diff --git a/apollo-router/src/plugins/csrf.rs b/apollo-router/src/plugins/csrf.rs index 6fc59866da..7fe7f0bda0 100644 --- a/apollo-router/src/plugins/csrf.rs +++ b/apollo-router/src/plugins/csrf.rs @@ -14,9 +14,9 @@ use crate::layers::ServiceBuilderExt; use crate::plugin::Plugin; use crate::plugin::PluginInit; use crate::register_plugin; -use crate::stages::router; -use crate::RouterRequest; -use crate::RouterResponse; +use crate::stages::supergraph; +use crate::SupergraphRequest; +use crate::SupergraphResponse; /// CSRF Configuration. #[derive(Deserialize, Debug, Clone, JsonSchema)] @@ -101,11 +101,11 @@ impl Plugin for Csrf { }) } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { if !self.config.unsafe_disabled { let required_headers = self.config.required_headers.clone(); ServiceBuilder::new() - .checkpoint(move |req: RouterRequest| { + .checkpoint(move |req: SupergraphRequest| { if is_preflighted(&req, required_headers.as_slice()) { tracing::trace!("request is preflighted"); Ok(ControlFlow::Continue(req)) @@ -119,7 +119,7 @@ impl Plugin for Csrf { NON_PREFLIGHTED_CONTENT_TYPES.join(", "), required_headers.join(", ") )).build(); - let res = RouterResponse::builder() + let res = SupergraphResponse::builder() .error(error) .status_code(StatusCode::BAD_REQUEST) .context(req.context) @@ -143,7 +143,7 @@ impl Plugin for Csrf { // - The only headers added by javascript code are part of the cors safelisted request headers (Accept,Accept-Language,Content-Language,Content-Type, and simple Range // // Given the first step is covered in our web browser, we'll take care of the two other steps below: -fn is_preflighted(req: &RouterRequest, required_headers: &[String]) -> bool { +fn is_preflighted(req: &SupergraphRequest, required_headers: &[String]) -> bool { let headers = req.originating_request.headers(); content_type_requires_preflight(headers) || recommended_header_is_provided(headers, required_headers) @@ -231,18 +231,18 @@ mod csrf_tests { use tower::ServiceExt; use super::*; - use crate::plugin::test::MockRouterService; + use crate::plugin::test::MockSupergraphService; #[tokio::test] async fn it_lets_preflighted_request_pass_through() { let config = CSRFConfig::default(); - let with_preflight_content_type = RouterRequest::fake_builder() + let with_preflight_content_type = SupergraphRequest::fake_builder() .header("content-type", "application/json") .build() .unwrap(); assert_accepted(config.clone(), with_preflight_content_type).await; - let with_preflight_header = RouterRequest::fake_builder() + let with_preflight_header = SupergraphRequest::fake_builder() .header("apollo-require-preflight", "this-is-a-test") .build() .unwrap(); @@ -252,7 +252,7 @@ mod csrf_tests { #[tokio::test] async fn it_rejects_non_preflighted_headers_request() { let config = CSRFConfig::default(); - let mut non_preflighted_request = RouterRequest::fake_builder().build().unwrap(); + let mut non_preflighted_request = SupergraphRequest::fake_builder().build().unwrap(); // fake_builder defaults to `Content-Type: application/json`, // specifically to avoid the case we’re testing here. non_preflighted_request @@ -265,13 +265,13 @@ mod csrf_tests { #[tokio::test] async fn it_rejects_non_preflighted_content_type_request() { let config = CSRFConfig::default(); - let non_preflighted_request = RouterRequest::fake_builder() + let non_preflighted_request = SupergraphRequest::fake_builder() .header("content-type", "text/plain") .build() .unwrap(); assert_rejected(config.clone(), non_preflighted_request).await; - let non_preflighted_request = RouterRequest::fake_builder() + let non_preflighted_request = SupergraphRequest::fake_builder() .header("content-type", "text/plain; charset=utf8") .build() .unwrap(); @@ -284,14 +284,14 @@ mod csrf_tests { unsafe_disabled: true, ..Default::default() }; - let non_preflighted_request = RouterRequest::fake_builder().build().unwrap(); + let non_preflighted_request = SupergraphRequest::fake_builder().build().unwrap(); assert_accepted(config, non_preflighted_request).await } - async fn assert_accepted(config: CSRFConfig, request: RouterRequest) { - let mut mock_service = MockRouterService::new(); + async fn assert_accepted(config: CSRFConfig, request: SupergraphRequest) { + let mut mock_service = MockSupergraphService::new(); mock_service.expect_call().times(1).returning(move |_| { - Ok(RouterResponse::fake_builder() + Ok(SupergraphResponse::fake_builder() .data(json!({ "test": 1234_u32 })) .build() .unwrap()) @@ -300,7 +300,7 @@ mod csrf_tests { let service_stack = Csrf::new(PluginInit::new(config, Default::default())) .await .unwrap() - .router_service(mock_service.boxed()); + .supergraph_service(mock_service.boxed()); let res = service_stack .oneshot(request) .await @@ -313,11 +313,11 @@ mod csrf_tests { assert_eq!(res.data.unwrap(), json!({ "test": 1234_u32 })); } - async fn assert_rejected(config: CSRFConfig, request: RouterRequest) { + async fn assert_rejected(config: CSRFConfig, request: SupergraphRequest) { let service_stack = Csrf::new(PluginInit::new(config, Default::default())) .await .unwrap() - .router_service(MockRouterService::new().boxed()); + .supergraph_service(MockSupergraphService::new().boxed()); let res = service_stack .oneshot(request) .await @@ -329,7 +329,7 @@ mod csrf_tests { assert_eq!( 1, res.errors.len(), - "expected one(1) error in the RouterResponse, found {}\n{:?}", + "expected one(1) error in the SupergraphResponse, found {}\n{:?}", res.errors.len(), res.errors ); diff --git a/apollo-router/src/plugins/expose_query_plan.rs b/apollo-router/src/plugins/expose_query_plan.rs index 8d2f842e1f..36696b7abc 100644 --- a/apollo-router/src/plugins/expose_query_plan.rs +++ b/apollo-router/src/plugins/expose_query_plan.rs @@ -14,8 +14,8 @@ use crate::register_plugin; use crate::services::QueryPlannerContent; use crate::services::QueryPlannerRequest; use crate::services::QueryPlannerResponse; -use crate::services::RouterRequest; -use crate::services::RouterResponse; +use crate::services::SupergraphRequest; +use crate::services::SupergraphResponse; const EXPOSE_QUERY_PLAN_HEADER_NAME: &str = "Apollo-Expose-Query-Plan"; const ENABLE_EXPOSE_QUERY_PLAN_ENV: &str = "APOLLO_EXPOSE_QUERY_PLAN"; @@ -63,20 +63,20 @@ impl Plugin for ExposeQueryPlan { .boxed() } - fn router_service( + fn supergraph_service( &self, - service: BoxService, - ) -> BoxService { + service: BoxService, + ) -> BoxService { let conf_enabled = self.enabled; service - .map_future_with_context(move |req: &RouterRequest| { + .map_future_with_context(move |req: &SupergraphRequest| { let is_enabled = conf_enabled && req.originating_request.headers().get(EXPOSE_QUERY_PLAN_HEADER_NAME) == Some(&HeaderValue::from_static("true")); if is_enabled { req.context.insert(ENABLED_CONTEXT_KEY, true).unwrap(); } (req.originating_request.body().query.clone(), is_enabled) }, move |(query, is_enabled): (Option, bool), f| async move { - let mut res: Result = f.await; + let mut res: Result = f.await; res = match res { Ok(mut res) => { if is_enabled { @@ -148,7 +148,7 @@ mod tests { async fn build_mock_router( plugin: Box, - ) -> BoxCloneService { + ) -> BoxCloneService { let mut extensions = Object::new(); extensions.insert("test", Value::String(ByteString::from("value"))); @@ -209,9 +209,9 @@ mod tests { async fn execute_router_test( query: &str, body: &Response, - mut router_service: BoxCloneService, + mut router_service: BoxCloneService, ) { - let request = RouterRequest::fake_builder() + let request = SupergraphRequest::fake_builder() .query(query.to_string()) .variable("first", 2usize) .header(EXPOSE_QUERY_PLAN_HEADER_NAME, "true") diff --git a/apollo-router/src/plugins/include_subgraph_errors.rs b/apollo-router/src/plugins/include_subgraph_errors.rs index 7e24b9ddbc..ca8fae30c1 100644 --- a/apollo-router/src/plugins/include_subgraph_errors.rs +++ b/apollo-router/src/plugins/include_subgraph_errors.rs @@ -98,9 +98,9 @@ mod test { use crate::plugin::test::MockSubgraph; use crate::plugin::DynPlugin; use crate::PluggableRouterServiceBuilder; - use crate::RouterRequest; - use crate::RouterResponse; use crate::Schema; + use crate::SupergraphRequest; + use crate::SupergraphResponse; static UNREDACTED_PRODUCT_RESPONSE: Lazy = Lazy::new(|| { serde_json::from_str(r#"{"data": {"topProducts":null}, "errors":[{"message": "couldn't find mock for query", "locations": [], "path": null, "extensions": { "test": "value" }}]}"#).unwrap() @@ -130,9 +130,9 @@ mod test { async fn execute_router_test( query: &str, body: &Response, - mut router_service: BoxCloneService, + mut router_service: BoxCloneService, ) { - let request = RouterRequest::fake_builder() + let request = SupergraphRequest::fake_builder() .query(query.to_string()) .variable("first", 2usize) .build() @@ -153,7 +153,7 @@ mod test { async fn build_mock_router( plugin: Box, - ) -> BoxCloneService { + ) -> BoxCloneService { let mut extensions = Object::new(); extensions.insert("test", Value::String(ByteString::from("value"))); diff --git a/apollo-router/src/plugins/rhai.rs b/apollo-router/src/plugins/rhai.rs index d31419bd9d..b43d1baf87 100644 --- a/apollo-router/src/plugins/rhai.rs +++ b/apollo-router/src/plugins/rhai.rs @@ -51,8 +51,8 @@ use crate::register_plugin; use crate::Context; use crate::ExecutionRequest; use crate::ExecutionResponse; -use crate::RouterRequest; -use crate::RouterResponse; +use crate::SupergraphRequest; +use crate::SupergraphResponse; trait OptionDance { fn with_mut(&self, f: impl FnOnce(&mut T) -> R) -> R; @@ -88,8 +88,8 @@ impl OptionDance for SharedMut { } mod router { - pub(crate) use crate::stages::router::*; - pub(crate) type Response = super::RhaiRouterResponse; + pub(crate) use crate::stages::supergraph::*; + pub(crate) type Response = super::RhaiSupergraphResponse; } mod query_planner { @@ -327,12 +327,12 @@ impl Plugin for Rhai { Ok(Self { ast, engine }) } - fn router_service(&self, service: router::BoxService) -> router::BoxService { - const FUNCTION_NAME_SERVICE: &str = "router_service"; + fn supergraph_service(&self, service: router::BoxService) -> router::BoxService { + const FUNCTION_NAME_SERVICE: &str = "supergraph_service"; if !self.ast_has_function(FUNCTION_NAME_SERVICE) { return service; } - tracing::debug!("router_service function found"); + tracing::debug!("supergraph_service function found"); let shared_service = Arc::new(Mutex::new(Some(service))); if let Err(error) = self.run_rhai_service( FUNCTION_NAME_SERVICE, @@ -543,7 +543,7 @@ pub(crate) struct RhaiExecutionResponse { response: http_ext::Response, } -pub(crate) struct RhaiRouterResponse { +pub(crate) struct RhaiSupergraphResponse { context: Context, response: http_ext::Response, } @@ -666,15 +666,15 @@ impl ServiceStep { //gen_map_request!(router, service, rhai_service, callback); service.replace(|service| { ServiceBuilder::new() - .checkpoint(move |request: RouterRequest| { + .checkpoint(move |request: SupergraphRequest| { // Let's define a local function to build an error response fn failure_message( context: Context, msg: String, status: StatusCode, - ) -> Result, BoxError> + ) -> Result, BoxError> { - let res = RouterResponse::error_builder() + let res = SupergraphResponse::error_builder() .errors(vec![Error { message: msg, ..Default::default() @@ -799,7 +799,7 @@ impl ServiceStep { // gen_map_response!(router, service, rhai_service, callback); service.replace(|service| { BoxService::new(service.and_then( - |router_response: RouterResponse| async move { + |router_response: SupergraphResponse| async move { // Let's define a local function to build an error response // XXX: This isn't ideal. We already have a response, so ideally we'd // like to append this error into the existing response. However, @@ -810,8 +810,8 @@ impl ServiceStep { context: Context, msg: String, status: StatusCode, - ) -> RouterResponse { - let res = RouterResponse::error_builder() + ) -> SupergraphResponse { + let res = SupergraphResponse::error_builder() .errors(vec![Error { message: msg, ..Default::default() @@ -825,7 +825,7 @@ impl ServiceStep { // we split the response stream into headers+first response, then a stream of deferred responses // for which we will implement mapping later - let RouterResponse { response, context } = router_response; + let SupergraphResponse { response, context } = router_response; let (parts, stream) = http::Response::from(response).into_parts(); let (first, rest) = stream.into_future().await; @@ -837,7 +837,7 @@ impl ServiceStep { )); } - let response = RhaiRouterResponse { + let response = RhaiSupergraphResponse { context, response: http::Response::from_parts( parts, @@ -880,7 +880,8 @@ impl ServiceStep { let mut guard = shared_response.lock().unwrap(); let response_opt = guard.take(); - let RhaiRouterResponse { context, response } = response_opt.unwrap(); + let RhaiSupergraphResponse { context, response } = + response_opt.unwrap(); let (parts, body) = http::Response::from(response).into_parts(); //FIXME we should also map over the stream of future responses @@ -889,7 +890,7 @@ impl ServiceStep { once(ready(body)).chain(rest).boxed(), ) .into(); - Ok(RouterResponse { context, response }) + Ok(SupergraphResponse { context, response }) }, )) }) @@ -1379,20 +1380,20 @@ mod tests { use super::*; use crate::http_ext; use crate::plugin::test::MockExecutionService; - use crate::plugin::test::MockRouterService; + use crate::plugin::test::MockSupergraphService; use crate::plugin::DynPlugin; use crate::Context; - use crate::RouterRequest; - use crate::RouterResponse; + use crate::SupergraphRequest; + use crate::SupergraphResponse; #[tokio::test] async fn rhai_plugin_router_service() -> Result<(), BoxError> { - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); mock_service .expect_call() .times(1) - .returning(move |req: RouterRequest| { - Ok(RouterResponse::fake_builder() + .returning(move |req: SupergraphRequest| { + Ok(SupergraphResponse::fake_builder() .header("x-custom-header", "CUSTOM_VALUE") .context(req.context) .build() @@ -1408,10 +1409,10 @@ mod tests { ) .await .unwrap(); - let mut router_service = dyn_plugin.router_service(BoxService::new(mock_service)); + let mut router_service = dyn_plugin.supergraph_service(BoxService::new(mock_service)); let context = Context::new(); context.insert("test", 5i64).unwrap(); - let router_req = RouterRequest::fake_builder().context(context).build()?; + let router_req = SupergraphRequest::fake_builder().context(context).build()?; let mut router_resp = router_service.ready().await?.call(router_req).await?; assert_eq!(router_resp.response.status(), 200); diff --git a/apollo-router/src/plugins/telemetry/metrics/apollo.rs b/apollo-router/src/plugins/telemetry/metrics/apollo.rs index f9e6a0d0f2..dff03f8629 100644 --- a/apollo-router/src/plugins/telemetry/metrics/apollo.rs +++ b/apollo-router/src/plugins/telemetry/metrics/apollo.rs @@ -257,7 +257,7 @@ mod test { use crate::plugins::telemetry::Telemetry; use crate::plugins::telemetry::STUDIO_EXCLUDE; use crate::Context; - use crate::RouterRequest; + use crate::SupergraphRequest; use crate::TestHarness; #[tokio::test] @@ -361,7 +361,7 @@ mod test { .build() .await? .oneshot( - RouterRequest::fake_builder() + SupergraphRequest::fake_builder() .header("name_header", "test_client") .header("version_header", "1.0-test") .query(query) diff --git a/apollo-router/src/plugins/telemetry/metrics/mod.rs b/apollo-router/src/plugins/telemetry/metrics/mod.rs index eb92f0b52e..b7f0db8cb5 100644 --- a/apollo-router/src/plugins/telemetry/metrics/mod.rs +++ b/apollo-router/src/plugins/telemetry/metrics/mod.rs @@ -29,7 +29,7 @@ use crate::plugin::serde::deserialize_regex; use crate::plugin::Handler; use crate::plugins::telemetry::config::MetricsCommon; use crate::plugins::telemetry::metrics::apollo::Sender; -use crate::services::RouterResponse; +use crate::services::SupergraphResponse; use crate::stages; use crate::Context; @@ -253,8 +253,8 @@ impl ErrorsForward { impl AttributesForwardConf { pub(crate) async fn get_attributes_from_router_response( &self, - response: RouterResponse, - ) -> (RouterResponse, HashMap) { + response: SupergraphResponse, + ) -> (SupergraphResponse, HashMap) { let mut attributes = HashMap::new(); // Fill from static @@ -325,7 +325,7 @@ impl AttributesForwardConf { ) .into(); - (RouterResponse { context, response }, attributes) + (SupergraphResponse { context, response }, attributes) } /// Get attributes from context diff --git a/apollo-router/src/plugins/telemetry/mod.rs b/apollo-router/src/plugins/telemetry/mod.rs index 9474f4e885..01585b614e 100644 --- a/apollo-router/src/plugins/telemetry/mod.rs +++ b/apollo-router/src/plugins/telemetry/mod.rs @@ -69,15 +69,15 @@ use crate::register_plugin; use crate::stages; use crate::stages::execution; use crate::stages::query_planner; -use crate::stages::router; use crate::stages::subgraph; +use crate::stages::supergraph; use crate::Context; use crate::ExecutionRequest; use crate::QueryPlannerRequest; -use crate::RouterRequest; -use crate::RouterResponse; use crate::SubgraphRequest; use crate::SubgraphResponse; +use crate::SupergraphRequest; +use crate::SupergraphResponse; pub(crate) mod apollo; pub(crate) mod config; @@ -165,17 +165,17 @@ impl Plugin for Telemetry { Self::new_common::(init.config, None).await } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { let metrics_sender = self.apollo_metrics_sender.clone(); let metrics = BasicMetrics::new(&self.meter_provider); let config = Arc::new(self.config.clone()); let config_map_res = config.clone(); ServiceBuilder::new() - .instrument(Self::router_service_span( + .instrument(Self::supergraph_service_span( config.apollo.clone().unwrap_or_default(), )) .map_future_with_context( - move |req: &RouterRequest| { + move |req: &SupergraphRequest| { Self::populate_context(config.clone(), req); req.context.clone() }, @@ -185,7 +185,7 @@ impl Plugin for Telemetry { let sender = metrics_sender.clone(); let start = Instant::now(); async move { - let mut result: Result = fut.await; + let mut result: Result = fut.await; result = Self::update_metrics( config.clone(), ctx.clone(), @@ -744,11 +744,13 @@ impl Telemetry { ) } - fn router_service_span(config: apollo::Config) -> impl Fn(&RouterRequest) -> Span + Clone { + fn supergraph_service_span( + config: apollo::Config, + ) -> impl Fn(&SupergraphRequest) -> Span + Clone { let client_name_header = config.client_name_header; let client_version_header = config.client_version_header; - move |request: &RouterRequest| { + move |request: &SupergraphRequest| { let http_request = &request.originating_request; let headers = http_request.headers(); let query = http_request.body().query.clone().unwrap_or_default(); @@ -850,9 +852,9 @@ impl Telemetry { config: Arc, context: Context, metrics: BasicMetrics, - result: Result, + result: Result, request_duration: Duration, - ) -> Result { + ) -> Result { let mut metric_attrs = context .get::<_, HashMap>(ATTRIBUTES) .ok() @@ -906,7 +908,7 @@ impl Telemetry { res } - fn populate_context(config: Arc, req: &RouterRequest) { + fn populate_context(config: Arc, req: &SupergraphRequest) { let apollo_config = config.apollo.clone().unwrap_or_default(); let context = &req.context; let http_request = &req.originating_request; @@ -1016,13 +1018,13 @@ mod tests { use crate::graphql::Request; use crate::http_ext; use crate::json_ext::Object; - use crate::plugin::test::MockRouterService; use crate::plugin::test::MockSubgraphService; + use crate::plugin::test::MockSupergraphService; use crate::plugin::DynPlugin; use crate::services::SubgraphRequest; use crate::services::SubgraphResponse; - use crate::RouterRequest; - use crate::RouterResponse; + use crate::SupergraphRequest; + use crate::SupergraphResponse; #[tokio::test(flavor = "multi_thread")] async fn plugin_registered() { @@ -1187,12 +1189,12 @@ mod tests { #[tokio::test(flavor = "multi_thread")] async fn it_test_prometheus_metrics() { - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); mock_service .expect_call() .times(1) - .returning(move |req: RouterRequest| { - Ok(RouterResponse::fake_builder() + .returning(move |req: SupergraphRequest| { + Ok(SupergraphResponse::fake_builder() .context(req.context) .header("x-custom", "coming_from_header") .data(json!({"data": {"my_value": 2usize}})) @@ -1338,10 +1340,10 @@ mod tests { ) .await .unwrap(); - let mut router_service = dyn_plugin.router_service(BoxService::new(mock_service)); - let router_req = RouterRequest::fake_builder().header("test", "my_value_set"); + let mut supergraph_service = dyn_plugin.supergraph_service(BoxService::new(mock_service)); + let router_req = SupergraphRequest::fake_builder().header("test", "my_value_set"); - let _router_response = router_service + let _router_response = supergraph_service .ready() .await .unwrap() diff --git a/apollo-router/src/plugins/traffic_shaping/mod.rs b/apollo-router/src/plugins/traffic_shaping/mod.rs index d72c1c4d6e..5c9f236eb9 100644 --- a/apollo-router/src/plugins/traffic_shaping/mod.rs +++ b/apollo-router/src/plugins/traffic_shaping/mod.rs @@ -39,8 +39,8 @@ use crate::plugins::traffic_shaping::deduplication::QueryDeduplicationLayer; use crate::register_plugin; use crate::services::subgraph_service::Compression; use crate::stages::query_planner; -use crate::stages::router; use crate::stages::subgraph; +use crate::stages::supergraph; use crate::QueryPlannerRequest; use crate::SubgraphRequest; @@ -173,7 +173,7 @@ impl Plugin for TrafficShaping { }) } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { ServiceBuilder::new() .layer(TimeoutLayer::new( self.config @@ -276,13 +276,13 @@ mod test { use super::*; use crate::graphql::Response; use crate::json_ext::Object; - use crate::plugin::test::MockRouterService; use crate::plugin::test::MockSubgraph; + use crate::plugin::test::MockSupergraphService; use crate::plugin::DynPlugin; use crate::PluggableRouterServiceBuilder; - use crate::RouterRequest; - use crate::RouterResponse; use crate::Schema; + use crate::SupergraphRequest; + use crate::SupergraphResponse; static EXPECTED_RESPONSE: Lazy = Lazy::new(|| { serde_json::from_str(r#"{"data":{"topProducts":[{"upc":"1","name":"Table","reviews":[{"id":"1","product":{"name":"Table"},"author":{"id":"1","name":"Ada Lovelace"}},{"id":"4","product":{"name":"Table"},"author":{"id":"2","name":"Alan Turing"}}]},{"upc":"2","name":"Couch","reviews":[{"id":"2","product":{"name":"Couch"},"author":{"id":"1","name":"Ada Lovelace"}}]}]}}"#).unwrap() @@ -293,9 +293,9 @@ mod test { async fn execute_router_test( query: &str, body: &Response, - mut router_service: BoxCloneService, + mut router_service: BoxCloneService, ) { - let request = RouterRequest::fake_builder() + let request = SupergraphRequest::fake_builder() .query(query.to_string()) .variable("first", 2usize) .build() @@ -316,7 +316,7 @@ mod test { async fn build_mock_router_with_variable_dedup_optimization( plugin: Box, - ) -> BoxCloneService { + ) -> BoxCloneService { let mut extensions = Object::new(); extensions.insert("test", Value::String(ByteString::from("value"))); @@ -516,12 +516,12 @@ mod test { .unwrap(); let plugin = get_traffic_shaping_plugin(&config).await; - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); mock_service.expect_clone().returning(|| { - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); mock_service.expect_call().times(0..2).returning(move |_| { - Ok(RouterResponse::fake_builder() + Ok(SupergraphResponse::fake_builder() .data(json!({ "test": 1234_u32 })) .build() .unwrap()) @@ -530,8 +530,8 @@ mod test { }); let _response = plugin - .router_service(mock_service.clone().boxed()) - .oneshot(RouterRequest::fake_builder().build().unwrap()) + .supergraph_service(mock_service.clone().boxed()) + .oneshot(SupergraphRequest::fake_builder().build().unwrap()) .await .unwrap() .next_response() @@ -539,14 +539,14 @@ mod test { .unwrap(); assert!(plugin - .router_service(mock_service.clone().boxed()) - .oneshot(RouterRequest::fake_builder().build().unwrap()) + .supergraph_service(mock_service.clone().boxed()) + .oneshot(SupergraphRequest::fake_builder().build().unwrap()) .await .is_err()); tokio::time::sleep(Duration::from_millis(300)).await; let _response = plugin - .router_service(mock_service.clone().boxed()) - .oneshot(RouterRequest::fake_builder().build().unwrap()) + .supergraph_service(mock_service.clone().boxed()) + .oneshot(SupergraphRequest::fake_builder().build().unwrap()) .await .unwrap() .next_response() diff --git a/apollo-router/src/services/layers/apq.rs b/apollo-router/src/services/layers/apq.rs index 1cff8a77d6..e20a4d9944 100644 --- a/apollo-router/src/services/layers/apq.rs +++ b/apollo-router/src/services/layers/apq.rs @@ -19,8 +19,8 @@ use tower::Service; use crate::cache::DeduplicatingCache; use crate::layers::async_checkpoint::AsyncCheckpointService; use crate::layers::DEFAULT_BUFFER_SIZE; -use crate::RouterRequest; -use crate::RouterResponse; +use crate::SupergraphRequest; +use crate::SupergraphResponse; /// A persisted query. #[derive(Deserialize, Clone, Debug)] @@ -45,16 +45,19 @@ impl APQLayer { impl Layer for APQLayer where - S: Service + Send + 'static, - >::Future: Send + 'static, + S: Service + Send + 'static, + >::Future: Send + 'static, { type Service = AsyncCheckpointService< - Buffer, + Buffer, BoxFuture< 'static, - Result>::Response, RouterRequest>, BoxError>, + Result< + ControlFlow<>::Response, SupergraphRequest>, + BoxError, + >, >, - RouterRequest, + SupergraphRequest, >; fn layer(&self, service: S) -> Self::Service { @@ -112,7 +115,7 @@ where })) .unwrap(), }]; - let res = RouterResponse::builder() + let res = SupergraphResponse::builder() .data(Value::default()) .errors(errors) .context(req.context) @@ -128,7 +131,10 @@ where as BoxFuture< 'static, Result< - ControlFlow<>::Response, RouterRequest>, + ControlFlow< + >::Response, + SupergraphRequest, + >, BoxError, >, > @@ -155,7 +161,7 @@ mod apq_tests { use super::*; use crate::error::Error; use crate::graphql::Response; - use crate::plugin::test::MockRouterService; + use crate::plugin::test::MockSupergraphService; use crate::Context; #[tokio::test] @@ -179,7 +185,7 @@ mod apq_tests { .unwrap(), }; - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); // the first one should have lead to an APQ error // claiming the server doesn't have a query string for a given hash // it should have not been forwarded to our mock service @@ -197,7 +203,7 @@ mod apq_tests { assert!(body.query.is_some()); - Ok(RouterResponse::fake_builder() + Ok(SupergraphResponse::fake_builder() .build() .expect("expecting valid request")) }); @@ -224,7 +230,7 @@ mod apq_tests { hash.as_slice() )); - Ok(RouterResponse::fake_builder() + Ok(SupergraphResponse::fake_builder() .build() .expect("expecting valid request")) }); @@ -240,17 +246,17 @@ mod apq_tests { }), )]); - let hash_only = RouterRequest::fake_builder() + let hash_only = SupergraphRequest::fake_builder() .extensions(extensions.clone()) .build() .expect("expecting valid request"); - let second_hash_only = RouterRequest::fake_builder() + let second_hash_only = SupergraphRequest::fake_builder() .extensions(extensions.clone()) .build() .expect("expecting valid request"); - let with_query = RouterRequest::fake_builder() + let with_query = SupergraphRequest::fake_builder() .extensions(extensions) .query("{__typename}".to_string()) .build() @@ -294,7 +300,7 @@ mod apq_tests { .unwrap(), }; - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); // the first one should have lead to an APQ error // claiming the server doesn't have a query string for a given hash // it should have not been forwarded to our mock service @@ -311,7 +317,7 @@ mod apq_tests { assert!(body.query.is_some()); - Ok(RouterResponse::fake_builder() + Ok(SupergraphResponse::fake_builder() .build() .expect("expecting valid request")) }); @@ -330,21 +336,21 @@ mod apq_tests { }), )]); - let request_builder = RouterRequest::fake_builder().extensions(extensions.clone()); + let request_builder = SupergraphRequest::fake_builder().extensions(extensions.clone()); let hash_only = request_builder .context(Context::new()) .build() .expect("expecting valid request"); - let request_builder = RouterRequest::fake_builder().extensions(extensions.clone()); + let request_builder = SupergraphRequest::fake_builder().extensions(extensions.clone()); let second_hash_only = request_builder .context(Context::new()) .build() .expect("expecting valid request"); - let request_builder = RouterRequest::fake_builder().extensions(extensions); + let request_builder = SupergraphRequest::fake_builder().extensions(extensions); let with_query = request_builder .query("{__typename}".to_string()) diff --git a/apollo-router/src/services/layers/ensure_query_presence.rs b/apollo-router/src/services/layers/ensure_query_presence.rs index 10783f3880..d540052d7d 100644 --- a/apollo-router/src/services/layers/ensure_query_presence.rs +++ b/apollo-router/src/services/layers/ensure_query_presence.rs @@ -1,4 +1,4 @@ -//! Ensure that a [`RouterRequest`] contains a query. +//! Ensure that a [`SupergraphRequest`] contains a query. //! //! See [`Layer`] and [`Service`] for more details. //! @@ -13,23 +13,23 @@ use tower::Layer; use tower::Service; use crate::layers::sync_checkpoint::CheckpointService; -use crate::RouterRequest; -use crate::RouterResponse; +use crate::SupergraphRequest; +use crate::SupergraphResponse; #[derive(Default)] pub(crate) struct EnsureQueryPresence {} impl Layer for EnsureQueryPresence where - S: Service + Send + 'static, - >::Future: Send + 'static, - >::Error: Into + Send + 'static, + S: Service + Send + 'static, + >::Future: Send + 'static, + >::Error: Into + Send + 'static, { - type Service = CheckpointService; + type Service = CheckpointService; fn layer(&self, service: S) -> Self::Service { CheckpointService::new( - |req: RouterRequest| { + |req: SupergraphRequest| { // A query must be available at this point let query = req.originating_request.body().query.as_ref(); if query.is_none() || query.unwrap().trim().is_empty() { @@ -41,7 +41,7 @@ where }]; //We do not copy headers from the request to the response as this may lead to leakable of sensitive data - let res = RouterResponse::builder() + let res = SupergraphResponse::builder() .data(Value::default()) .errors(errors) .status_code(StatusCode::BAD_REQUEST) @@ -63,20 +63,20 @@ mod ensure_query_presence_tests { use tower::ServiceExt; use super::*; - use crate::plugin::test::MockRouterService; + use crate::plugin::test::MockSupergraphService; #[tokio::test] async fn it_works_with_query() { - let mut mock_service = MockRouterService::new(); + let mut mock_service = MockSupergraphService::new(); mock_service.expect_call().times(1).returning(move |_req| { - Ok(RouterResponse::fake_builder() + Ok(SupergraphResponse::fake_builder() .build() .expect("expecting valid request")) }); let service_stack = EnsureQueryPresence::default().layer(mock_service); - let request: crate::RouterRequest = RouterRequest::fake_builder() + let request: crate::SupergraphRequest = SupergraphRequest::fake_builder() .query("{__typename}".to_string()) .build() .expect("expecting valid request"); @@ -88,9 +88,9 @@ mod ensure_query_presence_tests { async fn it_fails_on_empty_query() { let expected_error = "Must provide query string."; - let service_stack = EnsureQueryPresence::default().layer(MockRouterService::new()); + let service_stack = EnsureQueryPresence::default().layer(MockSupergraphService::new()); - let request: crate::RouterRequest = RouterRequest::fake_builder() + let request: crate::SupergraphRequest = SupergraphRequest::fake_builder() .query("".to_string()) .build() .expect("expecting valid request"); @@ -111,9 +111,9 @@ mod ensure_query_presence_tests { async fn it_fails_on_no_query() { let expected_error = "Must provide query string."; - let service_stack = EnsureQueryPresence::default().layer(MockRouterService::new()); + let service_stack = EnsureQueryPresence::default().layer(MockSupergraphService::new()); - let request: crate::RouterRequest = RouterRequest::fake_builder() + let request: crate::SupergraphRequest = SupergraphRequest::fake_builder() .build() .expect("expecting valid request"); diff --git a/apollo-router/src/services/mod.rs b/apollo-router/src/services/mod.rs index 85b1ed85c0..1e31a4ce95 100644 --- a/apollo-router/src/services/mod.rs +++ b/apollo-router/src/services/mod.rs @@ -20,8 +20,8 @@ use static_assertions::assert_impl_all; use tower::BoxError; pub(crate) use self::execution_service::*; -pub(crate) use self::router_service::*; pub(crate) use self::subgraph_service::*; +pub(crate) use self::supergraph_service::*; use crate::error::Error; use crate::graphql::Request; use crate::graphql::Response; @@ -38,14 +38,14 @@ mod execution_service; pub mod http_ext; pub(crate) mod layers; pub(crate) mod new_service; -mod router_service; pub(crate) mod subgraph_service; +mod supergraph_service; -assert_impl_all!(RouterRequest: Send); +assert_impl_all!(SupergraphRequest: Send); /// Represents the router processing step of the processing pipeline. /// /// This consists of the parsed graphql Request, HTTP headers and contextual data for extensions. -pub struct RouterRequest { +pub struct SupergraphRequest { /// Original request to the Router. pub originating_request: http_ext::Request, @@ -53,7 +53,7 @@ pub struct RouterRequest { pub context: Context, } -impl From> for RouterRequest { +impl From> for SupergraphRequest { fn from(originating_request: http_ext::Request) -> Self { Self { originating_request, @@ -63,10 +63,10 @@ impl From> for RouterRequest { } #[buildstructor::buildstructor] -impl RouterRequest { - /// This is the constructor (or builder) to use when constructing a real RouterRequest. +impl SupergraphRequest { + /// This is the constructor (or builder) to use when constructing a real SupergraphRequest. /// - /// Required parameters are required in non-testing code to create a RouterRequest. + /// Required parameters are required in non-testing code to create a SupergraphRequest. #[allow(clippy::too_many_arguments)] #[builder(visibility = "pub")] fn new( @@ -78,7 +78,7 @@ impl RouterRequest { headers: MultiMap, uri: Uri, method: Method, - ) -> Result { + ) -> Result { let extensions: Object = extensions .into_iter() .map(|(name, value)| (ByteString::from(name), value)) @@ -109,10 +109,10 @@ impl RouterRequest { }) } - /// This is the constructor (or builder) to use when constructing a "fake" RouterRequest. + /// This is the constructor (or builder) to use when constructing a "fake" SupergraphRequest. /// /// This does not enforce the provision of the data that is required for a fully functional - /// RouterRequest. It's usually enough for testing, when a fully constructed RouterRequest is + /// SupergraphRequest. It's usually enough for testing, when a fully constructed SupergraphRequest is /// difficult to construct and not required for the purposes of the test. /// /// In addition, fake requests are expected to be valid, and will panic if given invalid values. @@ -124,14 +124,14 @@ impl RouterRequest { extensions: HashMap, context: Option, mut headers: MultiMap, - ) -> Result { + ) -> Result { // Avoid testing requests getting blocked by the CSRF-prevention plugin headers .entry(IntoHeaderName::HeaderName(http::header::CONTENT_TYPE)) .or_insert(IntoHeaderValue::HeaderValue(HeaderValue::from_static( "application/json", ))); - RouterRequest::new( + SupergraphRequest::new( query, operation_name, variables, @@ -150,7 +150,7 @@ impl RouterRequest { extensions: HashMap, context: Option, headers: MultiMap, - ) -> Result { + ) -> Result { let query = " query TopProducts($first: Int) { topProducts(first: $first) { @@ -177,20 +177,20 @@ impl RouterRequest { } } -assert_impl_all!(RouterResponse: Send); +assert_impl_all!(SupergraphResponse: Send); /// [`Context`] and [`http_ext::Response`] for the response. /// /// This consists of the response body and the context. -pub struct RouterResponse { +pub struct SupergraphResponse { pub response: http_ext::Response>, pub context: Context, } #[buildstructor::buildstructor] -impl RouterResponse { - /// This is the constructor (or builder) to use when constructing a real RouterResponse.. +impl SupergraphResponse { + /// This is the constructor (or builder) to use when constructing a real SupergraphResponse.. /// - /// Required parameters are required in non-testing code to create a RouterResponse.. + /// Required parameters are required in non-testing code to create a SupergraphResponse.. #[allow(clippy::too_many_arguments)] #[builder(visibility = "pub")] fn new( @@ -239,10 +239,10 @@ impl RouterResponse { }) } - /// This is the constructor (or builder) to use when constructing a "fake" RouterResponse. + /// This is the constructor (or builder) to use when constructing a "fake" SupergraphResponse. /// /// This does not enforce the provision of the data that is required for a fully functional - /// RouterResponse. It's usually enough for testing, when a fully constructed RouterResponse is + /// SupergraphResponse. It's usually enough for testing, when a fully constructed SupergraphResponse is /// difficult to construct and not required for the purposes of the test. /// /// In addition, fake responses are expected to be valid, and will panic if given invalid values. @@ -257,7 +257,7 @@ impl RouterResponse { headers: MultiMap, context: Option, ) -> Result { - RouterResponse::new( + SupergraphResponse::new( data, path, errors, @@ -268,7 +268,7 @@ impl RouterResponse { ) } - /// This is the constructor (or builder) to use when constructing a RouterResponse that represents a global error. + /// This is the constructor (or builder) to use when constructing a SupergraphResponse that represents a global error. /// It has no path and no response data. /// This is useful for things such as authentication errors. #[builder(visibility = "pub")] @@ -278,7 +278,7 @@ impl RouterResponse { headers: MultiMap, context: Context, ) -> Result { - RouterResponse::new( + SupergraphResponse::new( Default::default(), None, errors, @@ -297,7 +297,7 @@ impl RouterResponse { } } -impl RouterResponse { +impl SupergraphResponse { pub async fn next_response(&mut self) -> Option { self.response.body_mut().next().await } @@ -309,11 +309,11 @@ impl RouterResponse { Self { response, context } } - pub fn map(self, f: F) -> RouterResponse + pub fn map(self, f: F) -> SupergraphResponse where F: FnOnce(BoxStream<'static, Response>) -> BoxStream<'static, Response>, { - RouterResponse { + SupergraphResponse { context: self.context, response: self.response.map(f), } @@ -659,10 +659,10 @@ pub struct ExecutionResponse { #[buildstructor::buildstructor] impl ExecutionResponse { - /// This is the constructor (or builder) to use when constructing a real RouterRequest. + /// This is the constructor (or builder) to use when constructing a real SupergraphRequest. /// /// The parameters are not optional, because in a live situation all of these properties must be - /// set and be correct to create a RouterRequest. + /// set and be correct to create a SupergraphRequest. #[builder(visibility = "pub")] fn new( label: Option, @@ -800,12 +800,12 @@ mod test { use crate::graphql; use crate::Context; - use crate::RouterRequest; - use crate::RouterResponse; + use crate::SupergraphRequest; + use crate::SupergraphResponse; #[test] - fn router_request_builder() { - let request = RouterRequest::builder() + fn supergraph_request_builder() { + let request = SupergraphRequest::builder() .header("a", "b") .header("a", "c") .uri(Uri::from_static("http://example.com")) @@ -863,8 +863,8 @@ mod test { } #[tokio::test] - async fn router_response_builder() { - let mut response = RouterResponse::builder() + async fn supergraph_response_builder() { + let mut response = SupergraphResponse::builder() .header("a", "b") .header("a", "c") .context(Context::new()) diff --git a/apollo-router/src/services/router_service.rs b/apollo-router/src/services/supergraph_service.rs similarity index 94% rename from apollo-router/src/services/router_service.rs rename to apollo-router/src/services/supergraph_service.rs index 893454509b..ee5a92084d 100644 --- a/apollo-router/src/services/router_service.rs +++ b/apollo-router/src/services/supergraph_service.rs @@ -47,9 +47,9 @@ use crate::ExecutionRequest; use crate::ExecutionResponse; use crate::QueryPlannerRequest; use crate::QueryPlannerResponse; -use crate::RouterRequest; -use crate::RouterResponse; use crate::Schema; +use crate::SupergraphRequest; +use crate::SupergraphResponse; /// An [`IndexMap`] of available plugins. pub(crate) type Plugins = IndexMap>; @@ -80,7 +80,7 @@ impl RouterService Service +impl Service for RouterService where QueryPlannerService: Service @@ -90,7 +90,7 @@ where QueryPlannerService::Future: Send + 'static, ExecutionFactory: ExecutionServiceFactory, { - type Response = RouterResponse; + type Response = SupergraphResponse; type Error = BoxError; type Future = BoxFuture<'static, Result>; @@ -104,7 +104,7 @@ where .poll_ready(cx) } - fn call(&mut self, req: RouterRequest) -> Self::Future { + fn call(&mut self, req: SupergraphRequest) -> Self::Future { // Consume our cloned services and allow ownership to be transferred to the async block. let mut planning = self.ready_query_planner_service.take().unwrap(); let execution = self.execution_service_factory.new_service(); @@ -132,7 +132,7 @@ where match content { QueryPlannerContent::Introspection { response } => Ok( - RouterResponse::new_from_graphql_response(*response, context), + SupergraphResponse::new_from_graphql_response(*response, context), ), QueryPlannerContent::IntrospectionDisabled => { let mut resp = http::Response::new( @@ -147,7 +147,7 @@ where ); *resp.status_mut() = StatusCode::BAD_REQUEST; - Ok(RouterResponse { + Ok(SupergraphResponse { response: resp.into(), context, }) @@ -156,7 +156,7 @@ where let is_deferred = plan.root.contains_defer(); if let Some(err) = query.validate_variables(body, &schema).err() { - Ok(RouterResponse::new_from_graphql_response(err, context)) + Ok(SupergraphResponse::new_from_graphql_response(err, context)) } else { let operation_name = body.operation_name.clone(); @@ -171,7 +171,7 @@ where .await?; let (parts, response_stream) = http::Response::from(response).into_parts(); - Ok(RouterResponse { + Ok(SupergraphResponse { context, response: http::Response::from_parts( parts, @@ -223,7 +223,7 @@ where _ => StatusCode::INTERNAL_SERVER_ERROR, }; - Ok(RouterResponse::builder() + Ok(SupergraphResponse::builder() .errors(errors) .status_code(status_code) .context(context_cloned) @@ -407,10 +407,10 @@ impl RouterCreator { pub(crate) fn make( &self, ) -> impl Service< - RouterRequest, - Response = RouterResponse, + SupergraphRequest, + Response = SupergraphResponse, Error = BoxError, - Future = BoxFuture<'static, Result>, + Future = BoxFuture<'static, Result>, > + Send { ServiceBuilder::new() .layer(self.apq.clone()) @@ -428,7 +428,7 @@ impl RouterCreator { .schema(self.schema.clone()) .build(), ), - |acc, (_, e)| e.router_service(acc), + |acc, (_, e)| e.supergraph_service(acc), ), ) } @@ -437,7 +437,7 @@ impl RouterCreator { #[cfg(test)] pub(crate) fn test_service( &self, - ) -> tower::util::BoxCloneService { + ) -> tower::util::BoxCloneService { Buffer::new(self.make(), 512).boxed_clone() } } diff --git a/apollo-router/src/stages.rs b/apollo-router/src/stages.rs index eb8d9b50fb..df738dcd38 100644 --- a/apollo-router/src/stages.rs +++ b/apollo-router/src/stages.rs @@ -10,11 +10,11 @@ pub mod http { pub type Result = std::result::Result; } -pub mod router { +pub mod supergraph { use tower::BoxError; - pub use crate::services::RouterRequest as Request; - pub use crate::services::RouterResponse as Response; + pub use crate::services::SupergraphRequest as Request; + pub use crate::services::SupergraphResponse as Response; pub type BoxService = tower::util::BoxService; pub type BoxCloneService = tower::util::BoxCloneService; pub type Result = std::result::Result; diff --git a/apollo-router/src/test_harness.rs b/apollo-router/src/test_harness.rs index 52272b5de7..cf9ac07a3a 100644 --- a/apollo-router/src/test_harness.rs +++ b/apollo-router/src/test_harness.rs @@ -12,8 +12,8 @@ use crate::router_factory::RouterServiceConfigurator; use crate::router_factory::YamlRouterServiceFactory; use crate::stages::execution; use crate::stages::query_planner; -use crate::stages::router; use crate::stages::subgraph; +use crate::stages::supergraph; use crate::Schema; /// Builder for the part of an Apollo Router that handles GraphQL requests, as a [`tower::Service`]. @@ -36,13 +36,13 @@ use crate::Schema; /// Example making a single request: /// /// ``` -/// use apollo_router::stages::router; +/// use apollo_router::stages::supergraph; /// use apollo_router::TestHarness; /// use tower::util::ServiceExt; /// /// # #[tokio::main] async fn main() -> Result<(), tower::BoxError> { /// let config = serde_json::json!({"server": {"introspection": false}}); -/// let request = router::Request::fake_builder() +/// let request = supergraph::Request::fake_builder() /// // Request building here /// .build() /// .unwrap(); @@ -129,10 +129,10 @@ impl<'a> TestHarness<'a> { self } - /// Adds an ad-hoc plugin that has [`Plugin::router_service`] implemented with `callback`. - pub fn extra_router_plugin( + /// Adds an ad-hoc plugin that has [`Plugin::supergraph_service`] implemented with `callback`. + pub fn extra_supergraph_plugin( self, - callback: impl Fn(router::BoxService) -> router::BoxService + Send + Sync + 'static, + callback: impl Fn(supergraph::BoxService) -> supergraph::BoxService + Send + Sync + 'static, ) -> Self { self.extra_plugin(RouterServicePlugin(callback)) } @@ -176,7 +176,7 @@ impl<'a> TestHarness<'a> { } /// Builds the GraphQL service - pub async fn build(self) -> Result { + pub async fn build(self) -> Result { let builder = if self.schema.is_none() { self.extra_subgraph_plugin(|subgraph_name, default| match subgraph_name { "products" => canned::products_subgraph().boxed(), @@ -224,7 +224,7 @@ struct SubgraphServicePlugin(F); #[async_trait::async_trait] impl Plugin for RouterServicePlugin where - F: 'static + Send + Sync + Fn(router::BoxService) -> router::BoxService, + F: 'static + Send + Sync + Fn(supergraph::BoxService) -> supergraph::BoxService, { type Config = (); @@ -232,7 +232,7 @@ where unreachable!() } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { (self.0)(service) } } diff --git a/apollo-router/tests/fixtures/test.rhai b/apollo-router/tests/fixtures/test.rhai index d2e2a5ae91..f44dd44b84 100644 --- a/apollo-router/tests/fixtures/test.rhai +++ b/apollo-router/tests/fixtures/test.rhai @@ -1,11 +1,11 @@ // This is a test used for rhai plugin -fn router_service(service) { - let response = Fn("router_response"); +fn supergraph_service(service) { + let response = Fn("supergraph_response"); service.map_response(response); } -fn router_response(response) { +fn supergraph_response(response) { if response.headers["x-custom-header"] == "CUSTOM_VALUE" { response.headers["coucou"] = "hello"; } diff --git a/apollo-router/tests/fixtures/test_callbacks.rhai b/apollo-router/tests/fixtures/test_callbacks.rhai index 1544810c1e..edec0ef728 100644 --- a/apollo-router/tests/fixtures/test_callbacks.rhai +++ b/apollo-router/tests/fixtures/test_callbacks.rhai @@ -1,7 +1,7 @@ // This is a test used to make sure each callback is called -fn router_service(service) { - log_info("router_service setup"); +fn supergraph_service(service) { + log_info("supergraph_service setup"); service.map_request(|request| { log_info("from_router_request"); }); diff --git a/apollo-router/tests/integration_tests.rs b/apollo-router/tests/integration_tests.rs index 7b38b3d6a3..a1c2125c0f 100644 --- a/apollo-router/tests/integration_tests.rs +++ b/apollo-router/tests/integration_tests.rs @@ -12,8 +12,8 @@ use apollo_router::graphql::Request; use apollo_router::http_ext; use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; -use apollo_router::stages::router; use apollo_router::stages::subgraph; +use apollo_router::stages::supergraph; use apollo_router::Context; use apollo_router::_private::TelemetryPlugin; use http::Method; @@ -267,7 +267,7 @@ async fn queries_should_work_with_compression() { .build() .expect("expecting valid request"); - let request = router::Request { + let request = supergraph::Request { originating_request: http_request, context: Context::new(), }; @@ -301,7 +301,7 @@ async fn queries_should_work_over_post() { .build() .expect("expecting valid request"); - let request = router::Request { + let request = supergraph::Request { originating_request: http_request, context: Context::new(), }; @@ -413,7 +413,7 @@ async fn mutation_should_work_over_post() { .build() .expect("expecting valid request"); - let request = router::Request { + let request = supergraph::Request { originating_request: http_request, context: Context::new(), }; @@ -662,13 +662,13 @@ async fn query_node( } async fn query_rust( - request: router::Request, + request: supergraph::Request, ) -> (apollo_router::graphql::Response, CountingServiceRegistry) { query_rust_with_config(request, serde_json::json!({})).await } async fn query_rust_with_config( - request: router::Request, + request: supergraph::Request, config: serde_json::Value, ) -> (apollo_router::graphql::Response, CountingServiceRegistry) { let (router, counting_registry) = setup_router_and_registry(config).await; @@ -677,7 +677,7 @@ async fn query_rust_with_config( async fn setup_router_and_registry( config: serde_json::Value, -) -> (router::BoxCloneService, CountingServiceRegistry) { +) -> (supergraph::BoxCloneService, CountingServiceRegistry) { let config = serde_json::from_value(config).unwrap(); let counting_registry = CountingServiceRegistry::new(); let telemetry = TelemetryPlugin::new_with_subscriber( @@ -705,8 +705,8 @@ async fn setup_router_and_registry( } async fn query_with_router( - router: router::BoxCloneService, - request: router::Request, + router: supergraph::BoxCloneService, + request: supergraph::Request, ) -> graphql::Response { router .oneshot(request) diff --git a/apollo-router/tests/rhai_tests.rs b/apollo-router/tests/rhai_tests.rs index b67e042f57..5e49e83090 100644 --- a/apollo-router/tests/rhai_tests.rs +++ b/apollo-router/tests/rhai_tests.rs @@ -1,4 +1,4 @@ -use apollo_router::stages::router; +use apollo_router::stages::supergraph; use apollo_router::TestHarness; use tower::ServiceExt; @@ -26,7 +26,7 @@ async fn all_rhai_callbacks_are_invoked() { .build() .await .unwrap(); - let request = router::Request::fake_builder() + let request = supergraph::Request::fake_builder() .query("{ topProducts { name } }") .build() .unwrap(); @@ -39,7 +39,7 @@ async fn all_rhai_callbacks_are_invoked() { .unwrap(); dbg!(_response); for expected_log in [ - "router_service setup", + "supergraph_service setup", "from_router_request", "from_router_response", "query_planner_service setup", diff --git a/apollo-router/tests/snapshots/integration_tests__traced_basic_composition.snap b/apollo-router/tests/snapshots/integration_tests__traced_basic_composition.snap index a711527d8a..aa12ef4934 100644 --- a/apollo-router/tests/snapshots/integration_tests__traced_basic_composition.snap +++ b/apollo-router/tests/snapshots/integration_tests__traced_basic_composition.snap @@ -1,6 +1,5 @@ --- source: apollo-router/tests/integration_tests.rs -assertion_line: 161 expression: get_spans() --- { @@ -929,15 +928,15 @@ expression: get_spans() } } }, - "apollo_router::services::router_service::format_response": { - "name": "apollo_router::services::router_service::format_response", + "apollo_router::services::supergraph_service::format_response": { + "name": "apollo_router::services::supergraph_service::format_response", "record": { "entries": [], "metadata": { "name": "format_response", - "target": "apollo_router::services::router_service", + "target": "apollo_router::services::supergraph_service", "level": "DEBUG", - "module_path": "apollo_router::services::router_service", + "module_path": "apollo_router::services::supergraph_service", "fields": { "names": [] } diff --git a/apollo-router/tests/snapshots/integration_tests__traced_basic_request.snap b/apollo-router/tests/snapshots/integration_tests__traced_basic_request.snap index cdaded0ed0..5bb33140e5 100644 --- a/apollo-router/tests/snapshots/integration_tests__traced_basic_request.snap +++ b/apollo-router/tests/snapshots/integration_tests__traced_basic_request.snap @@ -1,6 +1,5 @@ --- source: apollo-router/tests/integration_tests.rs -assertion_line: 147 expression: get_spans() --- { @@ -337,15 +336,15 @@ expression: get_spans() } } }, - "apollo_router::services::router_service::format_response": { - "name": "apollo_router::services::router_service::format_response", + "apollo_router::services::supergraph_service::format_response": { + "name": "apollo_router::services::supergraph_service::format_response", "record": { "entries": [], "metadata": { "name": "format_response", - "target": "apollo_router::services::router_service", + "target": "apollo_router::services::supergraph_service", "level": "DEBUG", - "module_path": "apollo_router::services::router_service", + "module_path": "apollo_router::services::supergraph_service", "fields": { "names": [] } diff --git a/docs/source/customizations/native.mdx b/docs/source/customizations/native.mdx index 2e2c87a11c..cac6d5c75c 100644 --- a/docs/source/customizations/native.mdx +++ b/docs/source/customizations/native.mdx @@ -33,7 +33,7 @@ Most plugins should start by including the following set of `use` declarations: use apollo_router::plugin::Plugin; use apollo_router::{ register_plugin, ExecutionRequest, ExecutionResponse, QueryPlannerRequest, - QueryPlannerResponse, RouterRequest, RouterResponse, SubgraphRequest, SubgraphResponse, + QueryPlannerResponse, SupergraphRequest, SupergraphResponse, SubgraphRequest, SubgraphResponse, }; use schemars::JsonSchema; use serde::Deserialize; @@ -95,7 +95,7 @@ impl Plugin for HelloWorld { // Only define the hooks you need to modify. Each default hook // implementation returns its associated service with no changes. - fn router_service( + fn supergraph_service( &mut self, service: router::BoxService, ) -> router::BoxService { @@ -140,7 +140,7 @@ To define custom logic for a service hook, you can use [`ServiceBuilder`](https: use tower::ServiceBuilderExt; use apollo_router::ServiceBuilderExt as ApolloServiceBuilderExt; -fn router_service( +fn supergraph_service( &mut self, service: router::BoxService, ) -> router::BoxService { diff --git a/docs/source/customizations/overview.mdx b/docs/source/customizations/overview.mdx index 8d08ed497b..9223181626 100644 --- a/docs/source/customizations/overview.mdx +++ b/docs/source/customizations/overview.mdx @@ -60,12 +60,12 @@ Each Apollo Router service has a corresponding function that a customization can | Service | Function | Description | |---------|----------|-------------| -| `RouterService` | `router_service` |

This service runs at the very beginning and very end of the request lifecycle.

Define `router_service` if your customization needs to interact at the earliest or latest point possible. For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further.

| +| `SupergraphService` | `supergraph_service` |

This service runs at the very beginning and very end of the request lifecycle.

Define `supergraph_service` if your customization needs to interact at the earliest or latest point possible. For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further.

| | `QueryPlannerService` | `query_planner_service` |

This service handles generating the query plan for each incoming request.

Define `query_planner_service` if your customization needs to interact with query planning functionality (for example, to log query plan details).

| | `ExecutionService` | `execution_service` |

This service handles initiating the execution of a query plan after it's been generated.

Define `execution_service` if your customization includes logic to govern execution (for example, if you want to block a particular query based on a policy decision).

| | `SubgraphService` | `subgraph_service` | This service handles communication between the Apollo Router and your subgraphs. Define `subgraph_service` to configure this communication (for example, to dynamically add headers to pass to a subgraph). | -> _Most_ customizations use `router_service` and/or `subgraph_service`, whereas the other service functions are less common. +> _Most_ customizations use `supergraph_service` and/or `subgraph_service`, whereas the other service functions are less common. Each service has a request and response data-structure that holds: * A context object that was created at the start of the request and is propagated throughout the entire request lifecycle. It holds: diff --git a/docs/source/customizations/rhai.mdx b/docs/source/customizations/rhai.mdx index c518a273a8..b5405f2964 100644 --- a/docs/source/customizations/rhai.mdx +++ b/docs/source/customizations/rhai.mdx @@ -50,7 +50,7 @@ This section covers functionality that the router explicitly exposes to Rhai. The execution state of all router rhai scripts contains a constant, `apollo_start`, which may be used for relative timing operations. (Consider it similar to the `Epoch` in Unix environments.) ```javascript -fn router_service(service) { +fn supergraph_service(service) { // Define a closure to process our response let f = |response| { let start = apollo_start.elapsed; @@ -84,11 +84,11 @@ If you wish to indicate to the client that an error has occurred, Rhai supports For example: ```javascript -fn router_service(service) { +fn supergraph_service(service) { // Define a closure to process our response let f = |response| { // Something goes wrong during response processing... - throw "an error occurred setting up the router_service..."); + throw "an error occurred setting up the supergraph_service..."); }; // Map our response using our closure service.map_response(f); @@ -99,7 +99,7 @@ fn router_service(service) { Similar to native Rust plugins, Rhai scripts can hook into the Apollo Router's [four services](./overview/#how-customizations-work) that handle requests. Just like native Rust plugins, Rhai scripts use a single hook for each service. Like native Rust plugins, the script author can then choose to map requests/response and generally configure the service for different behaviour. - - `router_service` + - `supergraph_service` - `query_planner_service` - `execution_service` - `subgraph_service` @@ -109,7 +109,7 @@ Each of these hooks is optional. Define only the functions you want to use custo Each function takes a single parameter: `service`, this is typed for each of the different services. The various service functions are not required to return anything. If they do, the return is ignored. ```javascript -fn router_service(service) {} +fn supergraph_service(service) {} fn query_planner_service(service) {} fn execution_service(service) {} fn subgraph_service(service) {} @@ -126,7 +126,7 @@ These can be invoked as methods on the supplied service object and are expected For example: ```javascript -fn router_service(service) { +fn supergraph_service(service) { // Define a closure to process our response let f = |response| { // Log out any errors we may have @@ -226,7 +226,7 @@ request.subgraph.headers.x-my-new-header = 42.to_string(); #### request.body.query -The request query is accessible. If modified make sure to do this before QueryPlanning is performed (i.e.: `router_service()` or `query_planner_service()`) or the modification will have no effect on the query. For example, let's modify the query at the router_service stage and turn it into a completely invalid query. +The request query is accessible. If modified make sure to do this before query planning is performed (i.e.: `supergraph_service()` or `query_planner_service()`) or the modification will have no effect on the query. For example, let's modify the query at the supergraph_service stage and turn it into a completely invalid query. ```javascript print(`${request.body.query}`); // log the query before modification @@ -350,8 +350,8 @@ This example illustrates how to register router request handling. ```javascript -// At the router_service stage, register callbacks for processing requests -fn router_service(service) { +// At the supergraph_service stage, register callbacks for processing requests +fn supergraph_service(service) { const request_callback = Fn("process_request"); // This is standard Rhai functionality for creating a function pointer service.map_request(request_callback); // Register the callback } @@ -367,9 +367,9 @@ fn process_request(request) { This example manipulates headers and the request context: ```javascript -// At the router_service stage, register callbacks for processing requests and +// At the supergraph_service stage, register callbacks for processing requests and // responses. -fn router_service(service) { +fn supergraph_service(service) { const request_callback = Fn("process_request"); // This is standard Rhai functionality for creating a function pointer service.map_request(request_callback); // Register the request callback const response_callback = Fn("process_response"); // This is standard Rhai functionality for creating a function pointer diff --git a/examples/add-timestamp-header/src/add_timestamp_header.rhai b/examples/add-timestamp-header/src/add_timestamp_header.rhai index aeda3b10b5..fb103d1bb3 100644 --- a/examples/add-timestamp-header/src/add_timestamp_header.rhai +++ b/examples/add-timestamp-header/src/add_timestamp_header.rhai @@ -3,7 +3,7 @@ // Call map_request/map_response for our service and pass in strings with the names // of the functions to callback -fn router_service(service) { +fn supergraph_service(service) { print("registering callbacks for operation timing"); const request_callback = Fn("process_request"); diff --git a/examples/add-timestamp-header/src/main.rs b/examples/add-timestamp-header/src/main.rs index c4464f238f..4e9fa59e09 100644 --- a/examples/add-timestamp-header/src/main.rs +++ b/examples/add-timestamp-header/src/main.rs @@ -13,27 +13,27 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { use apollo_router::plugin::test; - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use http::StatusCode; use tower::util::ServiceExt; #[tokio::test] async fn test_router_service_adds_timestamp_header() { - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); // create a mock service we will use to test our plugin - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let expected_mock_response_data = "response created within the mock"; // Let's set up our mock to make sure it will be called once mock_service.expect_clone().return_once(move || { - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); mock_service .expect_call() .once() - .returning(move |req: router::Request| { + .returning(move |req: supergraph::Request| { // Preserve our context from request to response - Ok(router::Response::fake_builder() + Ok(supergraph::Response::fake_builder() .context(req.context) .data(expected_mock_response_data) .build() @@ -51,13 +51,13 @@ mod tests { let test_harness = apollo_router::TestHarness::builder() .configuration_json(config) .unwrap() - .extra_router_plugin(move |_| mock_service.clone().boxed()) + .extra_supergraph_plugin(move |_| mock_service.clone().boxed()) .build() .await .unwrap(); // Let's create a request with our operation name - let request_with_appropriate_name = router::Request::canned_builder() + let request_with_appropriate_name = supergraph::Request::canned_builder() .operation_name("me".to_string()) .build() .unwrap(); diff --git a/examples/async-auth/README.md b/examples/async-auth/README.md index dc00e01b42..fdbb41ccb6 100644 --- a/examples/async-auth/README.md +++ b/examples/async-auth/README.md @@ -14,7 +14,7 @@ authentication server. `checkpoint` and `checkpoint_async` allow you to halt request and return immediately. This is particularly useful for authentication. ```rust - fn router_service( + fn supergraph_service( &mut self, service: router::BoxService, ) -> router::BoxService { diff --git a/examples/async-auth/src/allow_client_id_from_file.rs b/examples/async-auth/src/allow_client_id_from_file.rs index 5233ffebb0..9c14bf1174 100644 --- a/examples/async-auth/src/allow_client_id_from_file.rs +++ b/examples/async-auth/src/allow_client_id_from_file.rs @@ -6,7 +6,7 @@ use apollo_router::layers::ServiceBuilderExt; use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; -use apollo_router::stages::router; +use apollo_router::stages::supergraph; use http::StatusCode; use schemars::JsonSchema; use serde::Deserialize; @@ -46,7 +46,7 @@ impl Plugin for AllowClientIdFromFile { // While this is not the most performant and efficient usecase, // We could easily change the place where the file list is stored, // switching the async file read with an async http request - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { let header_key = self.header.clone(); // async_checkpoint is an async function. // this means it will run whenever the service `await`s it @@ -58,14 +58,14 @@ impl Plugin for AllowClientIdFromFile { // see https://rust-lang.github.io/async-book/03_async_await/01_chapter.html#async-lifetimes for more information let allowed_ids_path = self.allowed_ids_path.clone(); - let handler = move |req: router::Request| { + let handler = move |req: supergraph::Request| { // If we set a res, then we are going to break execution // If not, we are continuing let mut res = None; if !req.originating_request.headers().contains_key(&header_key) { // Prepare an HTTP 401 response with a GraphQL error message res = Some( - router::Response::error_builder() + supergraph::Response::error_builder() .error(graphql::Error { message: format!("Missing '{header_key}' header"), ..Default::default() @@ -98,7 +98,7 @@ impl Plugin for AllowClientIdFromFile { if !allowed_clients.contains(&client_id.to_string()) { // Prepare an HTTP 403 response with a GraphQL error message res = Some( - router::Response::builder() + supergraph::Response::builder() .data(Value::default()) .error(graphql::Error { message: "client-id is not allowed".to_string(), @@ -114,7 +114,7 @@ impl Plugin for AllowClientIdFromFile { Err(_not_a_string_error) => { // Prepare an HTTP 400 response with a GraphQL error message res = Some( - router::Response::error_builder() + supergraph::Response::error_builder() .error(graphql::Error { message: format!("'{header_key}' value is not a string"), ..Default::default() @@ -175,7 +175,7 @@ mod tests { use apollo_router::plugin::test; use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use apollo_router::TestHarness; use http::StatusCode; use serde_json::json; @@ -212,7 +212,7 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know AllowClientIdFromFile did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, AllowClientIdFromFile is `decorating` or `wrapping` our mock_service. let init = PluginInit::new( @@ -225,10 +225,10 @@ mod tests { let service_stack = AllowClientIdFromFile::new(init) .await .expect("couldn't create AllowClientIdFromFile") - .router_service(mock_service.boxed()); + .supergraph_service(mock_service.boxed()); // Let's create a request without a client id... - let request_without_client_id = router::Request::fake_builder() + let request_without_client_id = supergraph::Request::fake_builder() .build() .expect("expecting valid request"); @@ -256,7 +256,7 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know AllowClientIdFromFile did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, AllowClientIdFromFile is `decorating` or `wrapping` our mock_service. let init = PluginInit::new( @@ -269,10 +269,10 @@ mod tests { let service_stack = AllowClientIdFromFile::new(init) .await .expect("couldn't create AllowClientIdFromFile") - .router_service(mock_service.boxed()); + .supergraph_service(mock_service.boxed()); // Let's create a request with a not allowed client id... - let request_with_unauthorized_client_id = router::Request::fake_builder() + let request_with_unauthorized_client_id = supergraph::Request::fake_builder() .header("x-client-id", "invalid_client_id") .build() .expect("expecting valid request"); @@ -300,16 +300,16 @@ mod tests { let valid_client_id = "jeremy"; // create a mock service we will use to test our plugin - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let expected_mock_response_data = "response created within the mock"; // Let's set up our mock to make sure it will be called once, with the expected operation_name mock_service .expect_call() .times(1) - .returning(move |req: router::Request| { + .returning(move |req: supergraph::Request| { assert_eq!( valid_client_id, // we're ok with unwrap's here because we're running a test @@ -322,7 +322,7 @@ mod tests { .unwrap() ); // let's return the expected data - Ok(router::Response::fake_builder() + Ok(supergraph::Response::fake_builder() .data(expected_mock_response_data) .build() .unwrap()) @@ -339,10 +339,10 @@ mod tests { let service_stack = AllowClientIdFromFile::new(init) .await .expect("couldn't create AllowClientIdFromFile") - .router_service(mock_service.boxed()); + .supergraph_service(mock_service.boxed()); // Let's create a request with an valid client id... - let request_with_valid_client_id = router::Request::fake_builder() + let request_with_valid_client_id = supergraph::Request::fake_builder() .header("x-client-id", valid_client_id) .build() .expect("expecting valid request"); diff --git a/examples/context/src/context_data.rs b/examples/context/src/context_data.rs index 471c2c826d..04fa3e6ef9 100644 --- a/examples/context/src/context_data.rs +++ b/examples/context/src/context_data.rs @@ -1,8 +1,8 @@ use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; -use apollo_router::stages::router; use apollo_router::stages::subgraph; +use apollo_router::stages::supergraph; use http::StatusCode; use tower::BoxError; use tower::ServiceBuilder; @@ -41,12 +41,12 @@ impl Plugin for ContextData { Ok(Self::default()) } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { // `ServiceBuilder` provides us with `map_request` and `map_response` methods. // // These allow basic interception and transformation of request and response messages. ServiceBuilder::new() - .map_request(|req: router::Request| { + .map_request(|req: supergraph::Request| { // Populate a value in context for use later. // Context values must be serializable to serde_json::Value. if let Err(e) = req.context.insert("incoming_data", "world!".to_string()) { diff --git a/examples/cookies-to-headers/src/main.rs b/examples/cookies-to-headers/src/main.rs index 298c6cdebe..a104cf20a9 100644 --- a/examples/cookies-to-headers/src/main.rs +++ b/examples/cookies-to-headers/src/main.rs @@ -33,8 +33,8 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { use apollo_router::plugin::test; - use apollo_router::stages::router; use apollo_router::stages::subgraph; + use apollo_router::stages::supergraph; use http::StatusCode; use tower::util::ServiceExt; @@ -86,7 +86,7 @@ mod tests { .configuration_json(config) .unwrap() .extra_subgraph_plugin(move |_, _| mock_service.clone().boxed()) - .extra_router_plugin(|service| { + .extra_supergraph_plugin(|service| { service .map_response(|response| { let mock_data = response.context.get("mock_data").unwrap(); @@ -101,7 +101,7 @@ mod tests { .await .unwrap(); - let request_with_appropriate_cookies = router::Request::canned_builder() + let request_with_appropriate_cookies = supergraph::Request::canned_builder() .header("cookie", "yummy_cookie=choco;tasty_cookie=strawberry") .build() .unwrap(); diff --git a/examples/embedded/src/main.rs b/examples/embedded/src/main.rs index b97185c6ff..302fec3821 100644 --- a/examples/embedded/src/main.rs +++ b/examples/embedded/src/main.rs @@ -1,4 +1,4 @@ -use apollo_router::stages::router; +use apollo_router::stages::supergraph; use apollo_router::TestHarness; use tower::ServiceExt; @@ -12,7 +12,7 @@ async fn main() -> Result<(), tower::BoxError> { .await?; // ...then create a GraphQL request... - let request = router::Request::fake_builder() + let request = supergraph::Request::fake_builder() .query(r#"query Query { me { name } }"#) .build() .expect("expecting valid request"); diff --git a/examples/forbid-anonymous-operations/README.md b/examples/forbid-anonymous-operations/README.md index babfc1406e..ebc75cf65c 100644 --- a/examples/forbid-anonymous-operations/README.md +++ b/examples/forbid-anonymous-operations/README.md @@ -12,7 +12,7 @@ cargo run -- -s ../graphql/supergraph.graphql -c ./router.yaml `checkpoint` and `checkpoint_async` allow you to halt request and return immediately. This is particularly useful for authentication. ```rust - fn router_service( + fn supergraph_service( &mut self, service: router::BoxService, ) -> router::BoxService { diff --git a/examples/forbid-anonymous-operations/src/forbid_anonymous_operations.rs b/examples/forbid-anonymous-operations/src/forbid_anonymous_operations.rs index a9788cddbb..befd9fdea3 100644 --- a/examples/forbid-anonymous-operations/src/forbid_anonymous_operations.rs +++ b/examples/forbid-anonymous-operations/src/forbid_anonymous_operations.rs @@ -5,7 +5,7 @@ use apollo_router::layers::ServiceBuilderExt; use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; -use apollo_router::stages::router; +use apollo_router::stages::supergraph; use http::StatusCode; use tower::BoxError; use tower::ServiceBuilder; @@ -30,15 +30,15 @@ impl Plugin for ForbidAnonymousOperations { } // Forbidding anonymous operations can happen at the very beginning of our GraphQL request lifecycle. - // We will thus put the logic it in the `router_service` section of our plugin. - fn router_service(&self, service: router::BoxService) -> router::BoxService { + // We will thus put the logic it in the `supergraph_service` section of our plugin. + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { // `ServiceBuilder` provides us with a `checkpoint` method. // // This method allows us to return ControlFlow::Continue(request) if we want to let the request through, // or ControlFlow::Return(response) with a crafted response if we don't want the request to go through. ServiceBuilder::new() - .checkpoint(|req: router::Request| { - // The http_request is stored in a `RouterRequest` context. + .checkpoint(|req: supergraph::Request| { + // The http_request is stored in a `SupergraphRequest` context. // Its `body()` is an `apollo_router::Request`, that contains: // - Zero or one query // - Zero or one operation_name @@ -54,7 +54,7 @@ impl Plugin for ForbidAnonymousOperations { tracing::error!("Operation is not allowed!"); // Prepare an HTTP 400 response with a GraphQL error message - let res = router::Response::error_builder() + let res = supergraph::Response::error_builder() .error(graphql::Error { message: "Anonymous operations are not allowed".to_string(), ..Default::default() @@ -94,7 +94,7 @@ mod tests { use apollo_router::graphql; use apollo_router::plugin::test; use apollo_router::plugin::Plugin; - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use http::StatusCode; use serde_json::json; use tower::ServiceExt; @@ -126,14 +126,14 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know ForbidAnonymousOperations did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, ForbidAnonymousOperations is `decorating` or `wrapping` our mock_service. let service_stack = - ForbidAnonymousOperations::default().router_service(mock_service.boxed()); + ForbidAnonymousOperations::default().supergraph_service(mock_service.boxed()); // Let's create a request without an operation name... - let request_without_any_operation_name = router::Request::fake_builder() + let request_without_any_operation_name = supergraph::Request::fake_builder() .build() .expect("expecting valid request"); @@ -161,14 +161,14 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know ForbidAnonymousOperations did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, ForbidAnonymousOperations is `decorating` or `wrapping` our mock_service. let service_stack = - ForbidAnonymousOperations::default().router_service(mock_service.boxed()); + ForbidAnonymousOperations::default().supergraph_service(mock_service.boxed()); // Let's create a request with an empty operation name... - let request_with_empty_operation_name = router::Request::fake_builder() + let request_with_empty_operation_name = supergraph::Request::fake_builder() .operation_name("".to_string()) .build() .expect("expecting valid request"); @@ -196,16 +196,16 @@ mod tests { let operation_name = "validOperationName"; // create a mock service we will use to test our plugin - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let expected_mock_response_data = "response created within the mock"; // Let's set up our mock to make sure it will be called once, with the expected operation_name mock_service .expect_call() .times(1) - .returning(move |req: router::Request| { + .returning(move |req: supergraph::Request| { assert_eq!( operation_name, // we're ok with unwrap's here because we're running a test @@ -217,7 +217,7 @@ mod tests { .unwrap() ); // let's return the expected data - Ok(router::Response::fake_builder() + Ok(supergraph::Response::fake_builder() .data(expected_mock_response_data) .build() .unwrap()) @@ -225,10 +225,10 @@ mod tests { // In this service_stack, ForbidAnonymousOperations is `decorating` or `wrapping` our mock_service. let service_stack = - ForbidAnonymousOperations::default().router_service(mock_service.boxed()); + ForbidAnonymousOperations::default().supergraph_service(mock_service.boxed()); // Let's create a request with an valid operation name... - let request_with_operation_name = router::Request::fake_builder() + let request_with_operation_name = supergraph::Request::fake_builder() .operation_name(operation_name) .build() .expect("expecting valid request"); diff --git a/examples/hello-world/src/hello_world.rs b/examples/hello-world/src/hello_world.rs index e6cd3ce462..a596e8fedb 100644 --- a/examples/hello-world/src/hello_world.rs +++ b/examples/hello-world/src/hello_world.rs @@ -3,8 +3,8 @@ use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; use apollo_router::stages::execution; use apollo_router::stages::query_planner; -use apollo_router::stages::router; use apollo_router::stages::subgraph; +use apollo_router::stages::supergraph; use schemars::JsonSchema; use serde::Deserialize; use tower::BoxError; @@ -34,7 +34,7 @@ impl Plugin for HelloWorld { }) } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { // Say hello when our service is added to the router_service // stage of the router plugin pipeline. #[cfg(test)] diff --git a/examples/jwt-auth/README.md b/examples/jwt-auth/README.md index 76e8a9c06b..a0ac11deda 100644 --- a/examples/jwt-auth/README.md +++ b/examples/jwt-auth/README.md @@ -15,7 +15,7 @@ cargo run -- -s ../graphql/supergraph.graphql -c ./router.yaml `checkpoint` and `checkpoint_async` allow you to halt request and return immediately. This is particularly useful for authentication. ```rust - fn router_service( + fn supergraph_service( &mut self, service: router::BoxService, ) -> router::BoxService { diff --git a/examples/jwt-auth/src/jwt.rs b/examples/jwt-auth/src/jwt.rs index 4c473e5454..c5244c15e6 100644 --- a/examples/jwt-auth/src/jwt.rs +++ b/examples/jwt-auth/src/jwt.rs @@ -68,7 +68,7 @@ use apollo_router::layers::ServiceBuilderExt; use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; -use apollo_router::stages::router; +use apollo_router::stages::supergraph; use apollo_router::Context; use http::header::AUTHORIZATION; use http::StatusCode; @@ -209,7 +209,7 @@ impl Plugin for JwtAuth { }) } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { // We are going to use the `jwt-simple` crate for our JWT verification. // The crate provides straightforward support for the popular JWT algorithms. @@ -227,15 +227,15 @@ impl Plugin for JwtAuth { let max_token_life = self.max_token_life; ServiceBuilder::new() - .checkpoint(move |req: router::Request| { + .checkpoint(move |req: supergraph::Request| { // We are going to do a lot of similar checking so let's define a local function // to help reduce repetition fn failure_message( context: Context, msg: String, status: StatusCode, - ) -> Result, BoxError> { - let res = router::Response::error_builder() + ) -> Result, BoxError> { + let res = supergraph::Response::error_builder() .errors(vec![graphql::Error { message: msg, ..Default::default() @@ -388,7 +388,7 @@ mod tests { use apollo_router::graphql; use apollo_router::plugin::test; use apollo_router::plugin::Plugin; - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use super::*; @@ -420,13 +420,13 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know JwtAuth did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, JwtAuth is `decorating` or `wrapping` our mock_service. - let service_stack = JwtAuth::default().router_service(mock_service.boxed()); + let service_stack = JwtAuth::default().supergraph_service(mock_service.boxed()); // Let's create a request without an authorization header - let request_without_any_authorization_header = router::Request::fake_builder() + let request_without_any_authorization_header = supergraph::Request::fake_builder() .build() .expect("expecting valid request"); @@ -454,13 +454,13 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know JwtAuth did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, JwtAuth is `decorating` or `wrapping` our mock_service. - let service_stack = JwtAuth::default().router_service(mock_service.boxed()); + let service_stack = JwtAuth::default().supergraph_service(mock_service.boxed()); // Let's create a request with a badly formatted authorization header - let request_with_no_bearer_in_auth = router::Request::fake_builder() + let request_with_no_bearer_in_auth = supergraph::Request::fake_builder() .header("authorization", "should start with Bearer") .build() .expect("expecting valid request"); @@ -489,13 +489,13 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know JwtAuth did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, JwtAuth is `decorating` or `wrapping` our mock_service. - let service_stack = JwtAuth::default().router_service(mock_service.boxed()); + let service_stack = JwtAuth::default().supergraph_service(mock_service.boxed()); // Let's create a request with a badly formatted authorization header - let request_with_too_many_spaces_in_auth = router::Request::fake_builder() + let request_with_too_many_spaces_in_auth = supergraph::Request::fake_builder() .header("authorization", "Bearer ") .build() .expect("expecting valid request"); @@ -524,14 +524,14 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know JwtAuth did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // In this service_stack, JwtAuth is `decorating` or `wrapping` our mock_service. - let service_stack = JwtAuth::default().router_service(mock_service.boxed()); + let service_stack = JwtAuth::default().supergraph_service(mock_service.boxed()); // Let's create a request with a properly formatted authorization header // Note: (The token isn't valid, but the format is...) - let request_with_appropriate_auth = router::Request::fake_builder() + let request_with_appropriate_auth = supergraph::Request::fake_builder() .header("authorization", "Bearer atoken") .build() .expect("expecting valid request"); @@ -560,16 +560,16 @@ mod tests { #[tokio::test] async fn test_hmac_jwtauth_accepts_valid_tokens() { // create a mock service we will use to test our plugin - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let expected_mock_response_data = "response created within the mock"; // Let's set up our mock to make sure it will be called once mock_service .expect_call() .once() - .returning(move |req: router::Request| { + .returning(move |req: supergraph::Request| { // Let's make sure our request contains (some of) our JWTClaims let claims: JWTClaims = req .context @@ -580,7 +580,7 @@ mod tests { assert_eq!(claims.subject, Some("subject".to_string())); assert_eq!(claims.jwt_id, Some("jwt_id".to_string())); assert_eq!(claims.nonce, Some("nonce".to_string())); - Ok(router::Response::fake_builder() + Ok(supergraph::Response::fake_builder() .data(expected_mock_response_data) .build() .expect("expecting valid request")) @@ -599,7 +599,7 @@ mod tests { .await .expect("valid configuration should succeed"); - let service_stack = jwt_auth.router_service(mock_service.boxed()); + let service_stack = jwt_auth.supergraph_service(mock_service.boxed()); let verifier = HS256Key::from_bytes(hex::decode(key).unwrap().as_ref()); let mut audiences = HashSet::new(); @@ -614,7 +614,7 @@ mod tests { let token = verifier.authenticate(claims).unwrap(); // Let's create a request with a properly formatted authorization header - let request_with_appropriate_auth = router::Request::fake_builder() + let request_with_appropriate_auth = supergraph::Request::fake_builder() .header("authorization", &format!("Bearer {token}")) .build() .expect("expecting valid request"); @@ -641,7 +641,7 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know JwtAuth did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // Create valid configuration for testing HMAC algorithm HS256 let key = "629709bdc3bd794312ccc3a1c47beb03ac7310bc02d32d4587e59b5ad81c99ba"; @@ -656,7 +656,7 @@ mod tests { .await .expect("valid configuration should succeed"); - let service_stack = jwt_auth.router_service(mock_service.boxed()); + let service_stack = jwt_auth.supergraph_service(mock_service.boxed()); let verifier = HS256Key::from_bytes(hex::decode(key).unwrap().as_ref()); // Generate a token which has an overly generous life span @@ -664,7 +664,7 @@ mod tests { let token = verifier.authenticate(claims).unwrap(); // Let's create a request with a properly formatted authorization header - let request_with_appropriate_auth = router::Request::fake_builder() + let request_with_appropriate_auth = supergraph::Request::fake_builder() .header("authorization", format!("Bearer {token}")) .build() .expect("expecting valid request"); @@ -693,7 +693,7 @@ mod tests { // It does not have any behavior, because we do not expect it to be called. // If it is called, the test will panic, // letting us know JwtAuth did not behave as expected. - let mock_service = test::MockRouterService::new(); + let mock_service = test::MockSupergraphService::new(); // Create valid configuration for testing HMAC algorithm HS256 let key = "629709bdc3bd794312ccc3a1c47beb03ac7310bc02d32d4587e59b5ad81c99ba"; @@ -710,7 +710,7 @@ mod tests { .await .expect("valid configuration should succeed"); - let service_stack = jwt_auth.router_service(mock_service.boxed()); + let service_stack = jwt_auth.supergraph_service(mock_service.boxed()); let verifier = HS256Key::from_bytes(hex::decode(key).unwrap().as_ref()); // Generate a token which has a short life span @@ -719,7 +719,7 @@ mod tests { let token = verifier.authenticate(claims).unwrap(); // Let's create a request with a properly formatted authorization header - let request_with_appropriate_auth = router::Request::fake_builder() + let request_with_appropriate_auth = supergraph::Request::fake_builder() .header("authorization", format!("Bearer {token}")) .build() .expect("expecting valid request"); diff --git a/examples/op-name-to-header/src/main.rs b/examples/op-name-to-header/src/main.rs index 5f0e3f33ef..ed416cca2b 100644 --- a/examples/op-name-to-header/src/main.rs +++ b/examples/op-name-to-header/src/main.rs @@ -13,25 +13,25 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { use apollo_router::plugin::test; - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use http::StatusCode; use tower::util::ServiceExt; #[tokio::test] async fn test_subgraph_processes_operation_name() { // create a mock service we will use to test our plugin - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let expected_mock_response_data = "response created within the mock"; // Let's set up our mock to make sure it will be called once mock_service.expect_clone().return_once(move || { - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); mock_service .expect_call() .once() - .returning(move |req: router::Request| { + .returning(move |req: supergraph::Request| { // Let's make sure our request contains our new header assert_eq!( req.originating_request @@ -40,7 +40,7 @@ mod tests { .expect("X-operation-name is present"), "me" ); - Ok(router::Response::fake_builder() + Ok(supergraph::Response::fake_builder() .data(expected_mock_response_data) .build() .unwrap()) @@ -57,13 +57,13 @@ mod tests { let test_harness = apollo_router::TestHarness::builder() .configuration_json(config) .unwrap() - .extra_router_plugin(move |_| mock_service.clone().boxed()) + .extra_supergraph_plugin(move |_| mock_service.clone().boxed()) .build() .await .unwrap(); // Let's create a request with our operation name - let request_with_appropriate_name = router::Request::canned_builder() + let request_with_appropriate_name = supergraph::Request::canned_builder() .operation_name("me".to_string()) .build() .unwrap(); diff --git a/examples/op-name-to-header/src/op_name_to_header.rhai b/examples/op-name-to-header/src/op_name_to_header.rhai index 3a6091b4c2..a31bfd9a70 100644 --- a/examples/op-name-to-header/src/op_name_to_header.rhai +++ b/examples/op-name-to-header/src/op_name_to_header.rhai @@ -1,6 +1,6 @@ // Call map_request with our service and pass in a string with the name // of the function to callback -fn router_service(service) { +fn supergraph_service(service) { print("registering request callback to add operation name to a header"); const request_callback = Fn("process_request"); map_request(service, request_callback); diff --git a/examples/rhai-data-response-mutate/src/main.rs b/examples/rhai-data-response-mutate/src/main.rs index 631bdba9e0..c7a4eea369 100644 --- a/examples/rhai-data-response-mutate/src/main.rs +++ b/examples/rhai-data-response-mutate/src/main.rs @@ -12,7 +12,7 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use apollo_router::Context; use http::StatusCode; use tower::util::ServiceExt; @@ -32,7 +32,7 @@ mod tests { .await .unwrap(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let _expected_mock_response_data = "response created within the mock"; // ... Call our test harness @@ -41,14 +41,14 @@ mod tests { let context: Option = None; let mut service_response = test_harness .oneshot( - router::Request::fake_builder() + supergraph::Request::fake_builder() .header("name_header", "test_client") .header("version_header", "1.0-test") .query(query) .and_operation_name(operation_name) .and_context(context) .build() - .expect("a valid RouterRequest"), + .expect("a valid SupergraphRequest"), ) .await .expect("a router response"); diff --git a/examples/rhai-data-response-mutate/src/rhai_data_response_mutate.rhai b/examples/rhai-data-response-mutate/src/rhai_data_response_mutate.rhai index fc517cbb0c..5f961ce034 100644 --- a/examples/rhai-data-response-mutate/src/rhai_data_response_mutate.rhai +++ b/examples/rhai-data-response-mutate/src/rhai_data_response_mutate.rhai @@ -1,10 +1,10 @@ // This example illustrates how to interact with responses to // modify the data returned. -// At the router_service stage, register callbacks for processing +// At the supergraph_service stage, register callbacks for processing // responses. We are using a closure here, but it could be a // function if we chose (see execution_service). -fn router_service(service) { +fn supergraph_service(service) { let f = |response| { print(response.body.data); print(response.body.data.me.name); @@ -18,7 +18,7 @@ fn router_service(service) { // At the execution_service stage, register callbacks for processing // responses. We are using a function here, but we could use a -// closure if we chose (see router_service). +// closure if we chose (see supergraph_service). fn execution_service(service) { const response_callback = Fn("process_response"); service.map_response(response_callback); diff --git a/examples/rhai-error-response-mutate/src/main.rs b/examples/rhai-error-response-mutate/src/main.rs index cfe1fcebfe..324015c14f 100644 --- a/examples/rhai-error-response-mutate/src/main.rs +++ b/examples/rhai-error-response-mutate/src/main.rs @@ -12,7 +12,7 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use apollo_router::Context; use http::StatusCode; use tower::util::ServiceExt; @@ -32,7 +32,7 @@ mod tests { .await .unwrap(); - // The expected reply is going to be JSON returned in the RouterResponse { error } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { error } section. let _expected_mock_response_error = "error created within the mock"; // ... Call our test harness @@ -41,14 +41,14 @@ mod tests { let context: Option = None; let mut service_response = test_harness .oneshot( - router::Request::fake_builder() + supergraph::Request::fake_builder() .header("name_header", "test_client") .header("version_header", "1.0-test") .query(query) .and_operation_name(operation_name) .and_context(context) .build() - .expect("a valid RouterRequest"), + .expect("a valid SupergraphRequest"), ) .await .expect("a router response"); diff --git a/examples/rhai-error-response-mutate/src/rhai_error_response_mutate.rhai b/examples/rhai-error-response-mutate/src/rhai_error_response_mutate.rhai index e1261db85d..606c7b4250 100644 --- a/examples/rhai-error-response-mutate/src/rhai_error_response_mutate.rhai +++ b/examples/rhai-error-response-mutate/src/rhai_error_response_mutate.rhai @@ -1,10 +1,10 @@ // This example illustrates how to interact with responses to // modify the errors returned. -// At the router_service stage, register callbacks for processing +// At the supergraph_service stage, register callbacks for processing // responses. We are using a closure here, but it could be a // function if we chose. -fn router_service(service) { +fn supergraph_service(service) { let f = |response| { // Log out the errors we receive print(response.body.errors); diff --git a/examples/rhai-logging/src/main.rs b/examples/rhai-logging/src/main.rs index 885a6989c8..c4898710e6 100644 --- a/examples/rhai-logging/src/main.rs +++ b/examples/rhai-logging/src/main.rs @@ -14,26 +14,26 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { use apollo_router::plugin::test; - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use http::StatusCode; use tower::util::ServiceExt; #[tokio::test] async fn test_subgraph_processes_operation_name() { // create a mock service we will use to test our plugin - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let expected_mock_response_data = "response created within the mock"; // Let's set up our mock to make sure it will be called once mock_service.expect_clone().return_once(move || { - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); mock_service .expect_call() .once() - .returning(move |_req: router::Request| { - Ok(router::Response::fake_builder() + .returning(move |_req: supergraph::Request| { + Ok(supergraph::Response::fake_builder() .data(expected_mock_response_data) .build() .unwrap()) @@ -50,13 +50,13 @@ mod tests { let test_harness = apollo_router::TestHarness::builder() .configuration_json(config) .unwrap() - .extra_router_plugin(move |_| mock_service.clone().boxed()) + .extra_supergraph_plugin(move |_| mock_service.clone().boxed()) .build() .await .unwrap(); // Let's create a request with our operation name - let request_with_appropriate_name = router::Request::canned_builder() + let request_with_appropriate_name = supergraph::Request::canned_builder() .operation_name("me".to_string()) .build() .unwrap(); diff --git a/examples/rhai-logging/src/rhai_logging.rhai b/examples/rhai-logging/src/rhai_logging.rhai index 01d3687dd6..fd313f2ea4 100644 --- a/examples/rhai-logging/src/rhai_logging.rhai +++ b/examples/rhai-logging/src/rhai_logging.rhai @@ -15,9 +15,9 @@ // one or perhaps two services and may only be interested in manipulating // requests or responses. -// At the router_service stage, register callbacks for processing requests and +// At the supergraph_service stage, register callbacks for processing requests and // responses. -fn router_service(service) { +fn supergraph_service(service) { const request_callback = Fn("process_request"); service.map_request(request_callback); const response_callback = Fn("process_response"); diff --git a/examples/rhai-subgraph-request-log/src/main.rs b/examples/rhai-subgraph-request-log/src/main.rs index 8db62705ad..d6d48fb5aa 100644 --- a/examples/rhai-subgraph-request-log/src/main.rs +++ b/examples/rhai-subgraph-request-log/src/main.rs @@ -12,7 +12,7 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use apollo_router::Context; use http::StatusCode; use tower::util::ServiceExt; @@ -32,7 +32,7 @@ mod tests { .await .unwrap(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let _expected_mock_response_data = "response created within the mock"; // ... Call our test harness @@ -41,14 +41,14 @@ mod tests { let context: Option = None; let mut service_response = test_harness .oneshot( - router::Request::fake_builder() + supergraph::Request::fake_builder() .header("name_header", "test_client") .header("version_header", "1.0-test") .query(query) .and_operation_name(operation_name) .and_context(context) .build() - .expect("a valid RouterRequest"), + .expect("a valid SupergraphRequest"), ) .await .expect("a router response"); diff --git a/examples/rhai-surrogate-cache-key/src/main.rs b/examples/rhai-surrogate-cache-key/src/main.rs index f9e0939940..8d9b6edd77 100644 --- a/examples/rhai-surrogate-cache-key/src/main.rs +++ b/examples/rhai-surrogate-cache-key/src/main.rs @@ -12,7 +12,7 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { - use apollo_router::stages::router; + use apollo_router::stages::supergraph; use apollo_router::Context; use http::StatusCode; use tower::util::ServiceExt; @@ -32,7 +32,7 @@ mod tests { .await .unwrap(); - // The expected reply is going to be JSON returned in the RouterResponse { data } section. + // The expected reply is going to be JSON returned in the SupergraphResponse { data } section. let _expected_mock_response_data = "response created within the mock"; // ... Call our test harness @@ -41,14 +41,14 @@ mod tests { let context: Option = None; let mut service_response = test_harness .oneshot( - router::Request::fake_builder() + supergraph::Request::fake_builder() .header("name_header", "test_client") .header("version_header", "1.0-test") .query(query) .and_operation_name(operation_name) .and_context(context) .build() - .expect("a valid RouterRequest"), + .expect("a valid SupergraphRequest"), ) .await .expect("a router response"); diff --git a/examples/rhai-surrogate-cache-key/src/rhai_surrogate_cache_key.rhai b/examples/rhai-surrogate-cache-key/src/rhai_surrogate_cache_key.rhai index 74785340b1..dbef68040c 100644 --- a/examples/rhai-surrogate-cache-key/src/rhai_surrogate_cache_key.rhai +++ b/examples/rhai-surrogate-cache-key/src/rhai_surrogate_cache_key.rhai @@ -1,10 +1,10 @@ // This example illustrates how to interact with responses to // modify the data returned. -// At the router_service stage, register callbacks for processing +// At the supergraph_service stage, register callbacks for processing // responses. We are using a closure here, but it could be a // function if we chose (see execution_service). -fn router_service(service) { +fn supergraph_service(service) { let map_callback = |response| { try { // Extract our surrogate key from context diff --git a/examples/status-code-propagation/src/propagate_status_code.rs b/examples/status-code-propagation/src/propagate_status_code.rs index 2a8c86fdf3..ee5f3026fa 100644 --- a/examples/status-code-propagation/src/propagate_status_code.rs +++ b/examples/status-code-propagation/src/propagate_status_code.rs @@ -1,8 +1,8 @@ use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; -use apollo_router::stages::router; use apollo_router::stages::subgraph; +use apollo_router::stages::supergraph; use http::StatusCode; use schemars::JsonSchema; use serde::Deserialize; @@ -61,7 +61,7 @@ impl Plugin for PropagateStatusCode { } // At this point, all subgraph_services will have pushed their status codes if they match the `watch list`. - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { service .map_response(move |mut res| { if let Some(code) = res @@ -91,8 +91,8 @@ mod tests { use apollo_router::plugin::test; use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; - use apollo_router::stages::router; use apollo_router::stages::subgraph; + use apollo_router::stages::supergraph; use http::StatusCode; use serde_json::json; use tower::ServiceExt; @@ -205,23 +205,22 @@ mod tests { #[tokio::test] async fn router_service_override_status_code() { - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); - mock_service - .expect_call() - .times(1) - .returning(move |router_request: router::Request| { + mock_service.expect_call().times(1).returning( + move |router_request: supergraph::Request| { let context = router_request.context; // Insert several status codes which shall override the router response status context .insert(&"status_code".to_string(), json!(500u16)) .expect("couldn't insert status_code"); - Ok(router::Response::fake_builder() + Ok(supergraph::Response::fake_builder() .context(context) .build() .unwrap()) - }); + }, + ); // StatusCode::INTERNAL_SERVER_ERROR should have precedence here let init = PluginInit::new( @@ -233,9 +232,9 @@ mod tests { let service_stack = PropagateStatusCode::new(init) .await .expect("couldn't create plugin") - .router_service(mock_service.boxed()); + .supergraph_service(mock_service.boxed()); - let router_request = router::Request::fake_builder() + let router_request = supergraph::Request::fake_builder() .build() .expect("expecting valid request"); @@ -251,19 +250,18 @@ mod tests { #[tokio::test] async fn router_service_do_not_override_status_code() { - let mut mock_service = test::MockRouterService::new(); + let mut mock_service = test::MockSupergraphService::new(); - mock_service - .expect_call() - .times(1) - .returning(move |router_request: router::Request| { + mock_service.expect_call().times(1).returning( + move |router_request: supergraph::Request| { let context = router_request.context; // Don't insert any StatusCode - Ok(router::Response::fake_builder() + Ok(supergraph::Response::fake_builder() .context(context) .build() .unwrap()) - }); + }, + ); // In this service_stack, PropagateStatusCode is `decorating` or `wrapping` our mock_service. let init = PluginInit::new( @@ -275,9 +273,9 @@ mod tests { let service_stack = PropagateStatusCode::new(init) .await .expect("couldn't create plugin") - .router_service(mock_service.boxed()); + .supergraph_service(mock_service.boxed()); - let router_request = router::Request::fake_builder() + let router_request = supergraph::Request::fake_builder() .build() .expect("expecting valid request"); diff --git a/examples/supergraph_sdl/src/supergraph_sdl.rs b/examples/supergraph_sdl/src/supergraph_sdl.rs index 978c04890c..8b68d67df5 100644 --- a/examples/supergraph_sdl/src/supergraph_sdl.rs +++ b/examples/supergraph_sdl/src/supergraph_sdl.rs @@ -4,7 +4,7 @@ use apollo_compiler::ApolloCompiler; use apollo_router::plugin::Plugin; use apollo_router::plugin::PluginInit; use apollo_router::register_plugin; -use apollo_router::stages::router; +use apollo_router::stages::supergraph; use tower::BoxError; use tower::ServiceBuilder; use tower::ServiceExt; @@ -27,14 +27,14 @@ impl Plugin for SupergraphSDL { }) } - fn router_service(&self, service: router::BoxService) -> router::BoxService { + fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService { // Clone our supergraph_sdl for use in map_request let supergraph_sdl = self.supergraph_sdl.clone(); // `ServiceBuilder` provides us with `map_request` and `map_response` methods. // // These allow basic interception and transformation of request and response messages. ServiceBuilder::new() - .map_request(move |req: router::Request| { + .map_request(move |req: supergraph::Request| { // If we have a query if let Some(query) = &req.originating_request.body().query { // Compile our supergraph_sdl and query