Skip to main content

mockql_core/
planner.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Planning helpers for mock-aware GraphQL requests.
16
17use crate::MinifyExt;
18use crate::graphql::abstract_typename_injector::add_typename_to_abstract_types;
19use crate::graphql::mock_directive_extractor::MockDirectiveExtractor;
20use crate::graphql::mock_directive_extractor::MockDirectiveExtractorError;
21use crate::graphql::mock_directive_extractor::MockScenario;
22use crate::graphql::mock_response_prompt::MockResponsePrompt;
23use crate::graphql::mock_response_prompt::SerializationFormat;
24use crate::graphql::operation_field_filter::FilterMode;
25use crate::graphql::operation_field_filter::OperationFieldFilter;
26use crate::graphql::response_validator::ResponseValidator;
27use crate::graphql::schema_filter::SchemaFilter;
28use crate::graphql::schema_filter::SchemaFilterError;
29use apollo_compiler::ExecutableDocument;
30use apollo_compiler::Schema;
31use apollo_compiler::parser::FileId;
32use apollo_compiler::response::ExecutionResponse;
33use apollo_compiler::validation::Valid;
34use serde_json_bytes::ByteString;
35use serde_json_bytes::Map;
36use serde_json_bytes::Value;
37use std::sync::Arc;
38use thiserror::Error;
39
40#[derive(Debug)]
41pub(crate) struct MockPlanner {
42  schema: Arc<Valid<Schema>>,
43  response_validator: ResponseValidator,
44  schema_filter: SchemaFilter,
45  mock_directive_extractor: MockDirectiveExtractor,
46  serialization_format: SerializationFormat,
47}
48
49/// Internal result of splitting an operation into passthrough and mocked portions.
50#[derive(Debug)]
51pub(crate) enum SplitResult {
52  /// The operation contains no mocks and should be forwarded upstream as-is.
53  NoMocks,
54  /// The operation is a pure introspection query answered from the local schema.
55  Introspection(ExecutionResponse),
56  /// The full operation should be satisfied by a mock provider.
57  FullMock {
58    /// Prompt describing the response to generate.
59    prompt: MockResponsePrompt,
60    /// Schema-bound validator for the generated response.
61    validator: ResponseValidator,
62    /// Operation document.
63    document: Valid<ExecutableDocument>,
64  },
65  /// The operation should be split between upstream execution and provider generation.
66  PartialMock {
67    /// Prompt describing the portion that should be mocked.
68    prompt: MockResponsePrompt,
69    /// Schema-bound validator for the generated response.
70    validator: ResponseValidator,
71    /// Operation document.
72    document: Valid<ExecutableDocument>,
73    /// Original operation document used to validate the merged response.
74    original_document: Box<Valid<ExecutableDocument>>,
75    /// GraphQL operation that should be executed upstream before merging.
76    upstream_operation: String,
77  },
78}
79
80/// Errors raised while analyzing how an operation should be split.
81#[derive(Debug, Error)]
82pub enum SplitError {
83  /// `@mock` directive extraction failed.
84  #[error("failed to extract mock directives: {0}")]
85  MockExtraction(#[from] MockDirectiveExtractorError),
86  /// The operation could not be filtered into include or exclude variants.
87  #[error("failed to filter operation fields: {0}")]
88  OperationFilter(String),
89  /// The prompt operation could not be selected for abstract type augmentation.
90  #[error("failed to inject abstract type names: {0}")]
91  AbstractTypenameInjection(String),
92  /// The schema could not be minimized for the target operation.
93  #[error("failed to filter schema: {0}")]
94  SchemaFilter(#[from] SchemaFilterError),
95  /// A provided schema extension was invalid.
96  #[error("schema extension failed: {0}")]
97  SchemaExtension(#[from] ExtendSchemaError),
98  /// The schema extension input value was invalid.
99  #[error("invalid schema extension: {0}")]
100  SchemaExtensionInput(String),
101}
102
103#[derive(Debug, Error)]
104pub enum ExtendSchemaError {
105  #[error("failed to build extended schema: {0:?}")]
106  Build(Vec<String>),
107  #[error("failed to validate extended schema: {0:?}")]
108  Validate(Vec<String>),
109}
110
111impl MockPlanner {
112  pub(crate) fn new(schema: Arc<Valid<Schema>>, serialization_format: SerializationFormat) -> Self {
113    Self {
114      response_validator: ResponseValidator::new(schema.clone()),
115      schema_filter: SchemaFilter::new(schema.clone()),
116      mock_directive_extractor: MockDirectiveExtractor::new(schema.clone()),
117      schema,
118      serialization_format,
119    }
120  }
121
122  pub(crate) fn split_operation(
123    &self,
124    query: &str,
125    operation_name: Option<&str>,
126    variables: &Map<ByteString, Value>,
127    schema_extension: Option<&Value>,
128  ) -> Result<SplitResult, SplitError> {
129    match schema_extension {
130      None => self.split_operation_inner(query, operation_name, variables),
131      Some(Value::String(extended_sdl)) if !extended_sdl.as_str().is_empty() => self
132        .with_extended_schema(extended_sdl.as_str())?
133        .split_operation_inner(query, operation_name, variables),
134      Some(_) => Err(SplitError::SchemaExtensionInput(
135        "schemaExtension must be a non-empty string".to_string(),
136      )),
137    }
138  }
139
140  fn split_operation_inner(
141    &self,
142    operation: &str,
143    operation_name: Option<&str>,
144    variables: &Map<ByteString, Value>,
145  ) -> Result<SplitResult, SplitError> {
146    let scenario = self.mock_directive_extractor.extract(operation, operation_name)?;
147    let (document, mocked_fields, is_partial) = match scenario {
148      MockScenario::NoMocks => return Ok(SplitResult::NoMocks),
149      MockScenario::Introspection(response) => return Ok(SplitResult::Introspection(response)),
150      MockScenario::OperationMocked {
151        document,
152        mocked_fields,
153        ..
154      }
155      | MockScenario::AllTopLevelFieldsMocked {
156        document,
157        mocked_fields,
158      } => (document, mocked_fields, false),
159      MockScenario::PartialMocked {
160        document,
161        mocked_fields,
162      } => (document, mocked_fields, true),
163    };
164    let original_document = document.clone();
165
166    let (to_mock_document, upstream_operation) = if is_partial {
167      let paths: Vec<String> = mocked_fields.iter().map(|field| field.path.clone()).collect();
168      let operation_field_filter = OperationFieldFilter::new(&document, &paths);
169      let filter = |mode: FilterMode| {
170        operation_field_filter
171          .filter(operation_name, mode)
172          .map_err(|error| SplitError::OperationFilter(format!("{error:?}")))
173      };
174
175      let filtered_document = filter(FilterMode::Include)?;
176      let excluded_document = filter(FilterMode::Exclude)?;
177      (
178        filtered_document,
179        Some(excluded_document.serialize().no_indent().to_string()),
180      )
181    } else {
182      (document, None)
183    };
184    let to_mock_operation = add_typename_to_abstract_types(&self.schema, to_mock_document.clone(), operation_name)
185      .map_err(|error| SplitError::AbstractTypenameInjection(format!("{error:?}")))?
186      .serialize()
187      .no_indent()
188      .to_string();
189
190    let prompt = MockResponsePrompt::builder()
191      .graphql_schema(self.schema_filter.filter(&to_mock_operation, operation_name)?.minify())
192      .graphql_operation(to_mock_operation)
193      .mocked_fields(mocked_fields)
194      .variables(variables.clone())
195      .format(self.serialization_format)
196      .build();
197
198    match upstream_operation {
199      Some(upstream_operation) => Ok(SplitResult::PartialMock {
200        prompt,
201        validator: self.response_validator.clone(),
202        document: to_mock_document,
203        original_document: Box::new(original_document),
204        upstream_operation,
205      }),
206      None => Ok(SplitResult::FullMock {
207        prompt,
208        validator: self.response_validator.clone(),
209        document: to_mock_document,
210      }),
211    }
212  }
213
214  fn with_extended_schema(&self, extension_sdl: &str) -> Result<Self, ExtendSchemaError> {
215    let mut builder = Schema::builder();
216    for (index, (file_id, source)) in self.schema.sources.iter().enumerate() {
217      if *file_id != FileId::BUILT_IN {
218        builder = builder.parse(source.source_text(), format!("schema-{index}.graphql"));
219      }
220    }
221    let schema = builder
222      .parse(extension_sdl, "schema-extension.graphql")
223      .build()
224      .map_err(|error| ExtendSchemaError::Build(error.errors.iter().map(|d| d.error.to_string()).collect()))?
225      .validate()
226      .map_err(|error| ExtendSchemaError::Validate(error.errors.iter().map(|d| d.error.to_string()).collect()))?;
227
228    Ok(Self::new(Arc::new(schema), self.serialization_format))
229  }
230}