Skip to main content

mockql_core/
service.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 and execution entry points for mock-aware GraphQL requests.
16
17use crate::Header;
18use crate::graphql::GraphQLResponse;
19use crate::graphql::mock_response_prompt::MockResponsePrompt;
20use crate::graphql::mock_response_prompt::SerializationFormat;
21use crate::graphql::response_merger::ResponseMerger;
22use crate::graphql::response_merger::ResponseMergerError;
23use crate::graphql::response_validator::ResponseValidationError;
24use crate::graphql::response_validator::ResponseValidator;
25use crate::llm_provider::ProviderConfig;
26use crate::llm_provider::ProviderError;
27use crate::llm_provider::generate_mock_response;
28use crate::planner::MockPlanner;
29use crate::planner::SplitError;
30use crate::planner::SplitResult;
31use crate::upstream::UpstreamError;
32use crate::upstream::execute_graphql;
33use apollo_compiler::ExecutableDocument;
34use apollo_compiler::Schema;
35use apollo_compiler::response::ExecutionResponse;
36use apollo_compiler::validation::Valid;
37use reqwest::Client;
38use reqwest::Url;
39use serde_json_bytes::ByteString;
40use serde_json_bytes::Map;
41use serde_json_bytes::Value;
42use std::sync::Arc;
43use std::time::Duration;
44use thiserror::Error;
45
46const MAX_VALIDATION_RETRIES: usize = 3;
47const MAX_PROVIDER_RETRIES: usize = 3;
48const PROVIDER_RETRY_DELAY: Duration = Duration::from_secs(1);
49
50/// Execution strategy selected for a request after planning.
51#[derive(Debug, Clone)]
52pub enum MockPlan {
53  /// The operation contains no mocks and should be executed upstream.
54  NoMocks,
55  /// The operation is a pure introspection query answered from the local schema.
56  Introspection(ExecutionResponse),
57  /// The operation should be handled entirely by a mock provider.
58  FullMock(MockResponsePrompt),
59  /// The operation should combine upstream data with generated mock data.
60  PartialMock {
61    /// Prompt used to ask the provider for the mocked portion.
62    prompt: MockResponsePrompt,
63    /// Upstream operation to execute before merging in mock data.
64    upstream_operation: String,
65  },
66}
67
68impl From<SplitResult> for MockPlan {
69  fn from(split_result: SplitResult) -> Self {
70    match split_result {
71      SplitResult::NoMocks => MockPlan::NoMocks,
72      SplitResult::Introspection(response) => MockPlan::Introspection(response),
73      SplitResult::FullMock { prompt, .. } => MockPlan::FullMock(prompt),
74      SplitResult::PartialMock {
75        prompt,
76        upstream_operation,
77        ..
78      } => MockPlan::PartialMock {
79        prompt,
80        upstream_operation,
81      },
82    }
83  }
84}
85
86/// Inputs required to fully execute a request.
87#[derive(Debug, Clone)]
88pub struct MockServiceRequest {
89  /// GraphQL operation text.
90  pub operation: String,
91  /// Optional operation name for multi-operation documents.
92  pub operation_name: Option<String>,
93  /// Variables supplied to the operation.
94  pub variables: Map<ByteString, Value>,
95  /// Optional schema extension payload applied before planning.
96  pub schema_extension: Option<Value>,
97  /// Upstream GraphQL server URL for passthrough execution.
98  pub graphql_url: Url,
99  /// Headers sent to the upstream GraphQL server.
100  pub graphql_headers: Vec<Header>,
101  /// Provider configuration used for mock generation.
102  pub provider: ProviderConfig,
103}
104
105#[buildstructor::buildstructor]
106impl MockServiceRequest {
107  /// Constructs a new [`MockServiceRequest`].
108  #[builder(visibility = "pub")]
109  fn new(
110    operation: String,
111    operation_name: Option<String>,
112    variables: Map<ByteString, Value>,
113    schema_extension: Option<Value>,
114    graphql_url: Url,
115    graphql_headers: Vec<Header>,
116    provider: ProviderConfig,
117  ) -> Self {
118    Self {
119      operation,
120      operation_name,
121      variables,
122      schema_extension,
123      graphql_url,
124      graphql_headers,
125      provider,
126    }
127  }
128}
129
130/// Plans and executes GraphQL operations that may contain `@mock` directives.
131#[derive(Debug)]
132pub struct MockService {
133  planner: MockPlanner,
134  client: Client,
135}
136
137/// Errors raised while planning or executing a request.
138#[derive(Debug, Error)]
139pub enum ServiceError {
140  /// Planning failed before any external I/O occurred.
141  #[error(transparent)]
142  Split(#[from] SplitError),
143  /// Mock provider execution failed.
144  #[error(transparent)]
145  Provider(#[from] ProviderError),
146  /// Upstream GraphQL execution failed.
147  #[error(transparent)]
148  Upstream(#[from] UpstreamError),
149  /// Partial-response merging failed.
150  #[error(transparent)]
151  Merge(#[from] ResponseMergerError),
152  /// Generated response validation failed.
153  #[error(transparent)]
154  ResponseValidation(#[from] ResponseValidationError),
155}
156
157fn is_retryable_provider_error(error: &ProviderError) -> bool {
158  match error {
159    ProviderError::Http(error) => error.is_timeout() || error.is_connect() || error.is_body(),
160    ProviderError::UnexpectedStatus { status, .. } => {
161      *status == reqwest::StatusCode::REQUEST_TIMEOUT
162        || *status == reqwest::StatusCode::TOO_MANY_REQUESTS
163        || status.is_server_error()
164    }
165    _ => false,
166  }
167}
168
169async fn generate_and_validate_mock_response(
170  provider: &ProviderConfig,
171  mut prompt: MockResponsePrompt,
172  validator: &ResponseValidator,
173  document: &Valid<ExecutableDocument>,
174  operation_name: Option<&str>,
175  variables: &Map<ByteString, Value>,
176) -> Result<GraphQLResponse, ServiceError> {
177  let mut provider_retries = 0;
178  let mut validation_retries = 0;
179  loop {
180    let mut response = match generate_mock_response(provider, &prompt).await {
181      Ok(response) => response,
182      Err(error) if is_retryable_provider_error(&error) => {
183        if provider_retries >= MAX_PROVIDER_RETRIES {
184          return Err(error.into());
185        }
186
187        provider_retries += 1;
188        if std::env::var("MOCKQL_DEBUG").is_ok() {
189          eprintln!("provider failed; retrying ({provider_retries}/{MAX_PROVIDER_RETRIES}): {error}");
190        }
191        tokio::time::sleep(PROVIDER_RETRY_DELAY).await;
192        continue;
193      }
194      Err(error @ ProviderError::InvalidJson(_)) => {
195        if validation_retries >= MAX_VALIDATION_RETRIES {
196          return Err(error.into());
197        }
198
199        validation_retries += 1;
200        if std::env::var("MOCKQL_DEBUG").is_ok() {
201          eprintln!(
202            "provider returned invalid JSON; retrying ({validation_retries}/{MAX_VALIDATION_RETRIES}): {error}"
203          );
204        }
205        let feedback = serde_json::json!({ "message": error.to_string() }).to_string();
206        prompt = prompt.with_validation_feedback(feedback);
207        continue;
208      }
209      Err(error) => return Err(error.into()),
210    };
211    if std::env::var("MOCKQL_DEBUG").is_ok() {
212      eprintln!(
213        "LLM response: {}",
214        serde_json::to_string(&response).unwrap_or_else(|_| format!("{response:?}"))
215      );
216    }
217    let validation = response
218      .data
219      .as_ref()
220      .ok_or(ResponseValidationError::InvalidData)
221      .and_then(|data| validator.validate(document, operation_name, variables, data));
222
223    match validation {
224      Ok(data) => {
225        response.data = Some(data);
226        return Ok(response);
227      }
228      Err(error) => {
229        if validation_retries >= MAX_VALIDATION_RETRIES {
230          return Err(error.into());
231        }
232
233        let feedback = match &error {
234          ResponseValidationError::Execution(errors) => serde_json::to_string(errors)
235            .unwrap_or_else(|_| serde_json::json!({ "message": error.to_string() }).to_string()),
236          ResponseValidationError::InvalidData => serde_json::json!({ "message": error.to_string() }).to_string(),
237          ResponseValidationError::InvalidRequest(_) => return Err(error.into()),
238        };
239
240        validation_retries += 1;
241        if std::env::var("MOCKQL_DEBUG").is_ok() {
242          eprintln!(
243            "mock response validation failed; retrying ({validation_retries}/{MAX_VALIDATION_RETRIES}): {error}"
244          );
245        }
246        prompt = prompt.with_validation_feedback(feedback);
247      }
248    }
249  }
250}
251
252impl MockService {
253  /// Creates a new service for a validated schema and shared upstream client.
254  pub fn new(schema: Arc<Valid<Schema>>, serialization_format: SerializationFormat, client: Client) -> Self {
255    Self {
256      planner: MockPlanner::new(schema, serialization_format),
257      client,
258    }
259  }
260
261  /// Builds a [`MockPlan`].
262  pub fn plan(
263    &self,
264    operation: &str,
265    operation_name: Option<&str>,
266    variables: &Map<ByteString, Value>,
267    schema_extension: Option<&Value>,
268  ) -> Result<MockPlan, ServiceError> {
269    Ok(
270      self
271        .planner
272        .split_operation(operation, operation_name, variables, schema_extension)?
273        .into(),
274    )
275  }
276
277  /// Executes a request using upstream GraphQL, a mock provider, or both.
278  pub async fn execute(&self, request: MockServiceRequest) -> Result<GraphQLResponse, ServiceError> {
279    let plan = self.planner.split_operation(
280      request.operation.as_str(),
281      request.operation_name.as_deref(),
282      &request.variables,
283      request.schema_extension.as_ref(),
284    )?;
285
286    match plan {
287      SplitResult::Introspection(response) => Ok(GraphQLResponse {
288        data: response.data.map(Value::Object),
289        errors: response
290          .errors
291          .into_iter()
292          .filter_map(|e| serde_json_bytes::to_value(e).ok())
293          .collect(),
294        extensions: Map::new(),
295      }),
296      SplitResult::NoMocks => execute_graphql(
297        &self.client,
298        request.graphql_url,
299        &request.graphql_headers,
300        &request.operation,
301        request.operation_name.as_deref(),
302        &request.variables,
303      )
304      .await
305      .map_err(ServiceError::from),
306      SplitResult::FullMock {
307        prompt,
308        validator,
309        document,
310      } => {
311        generate_and_validate_mock_response(
312          &request.provider,
313          prompt,
314          &validator,
315          &document,
316          request.operation_name.as_deref(),
317          &request.variables,
318        )
319        .await
320      }
321      SplitResult::PartialMock {
322        prompt,
323        validator,
324        document,
325        original_document,
326        upstream_operation: passthrough_operation,
327      } => {
328        let mut upstream_response = execute_graphql(
329          &self.client,
330          request.graphql_url,
331          &request.graphql_headers,
332          &passthrough_operation,
333          request.operation_name.as_deref(),
334          &request.variables,
335        )
336        .await?;
337        if upstream_response.data.as_ref().is_none_or(Value::is_null) {
338          return Ok(upstream_response);
339        }
340        let contextual_prompt = prompt.with_partial_response(upstream_response.data.clone());
341        let mut mock_response = generate_and_validate_mock_response(
342          &request.provider,
343          contextual_prompt,
344          &validator,
345          &document,
346          request.operation_name.as_deref(),
347          &request.variables,
348        )
349        .await?;
350        ResponseMerger::merge(&mut upstream_response, &mut mock_response)?;
351        upstream_response.data = Some(
352          validator.validate(
353            &original_document,
354            request.operation_name.as_deref(),
355            &request.variables,
356            upstream_response
357              .data
358              .as_ref()
359              .ok_or(ResponseValidationError::InvalidData)?,
360          )?,
361        );
362        Ok(upstream_response)
363      }
364    }
365  }
366}
367
368#[cfg(test)]
369mod tests {
370  use super::*;
371  use serde_json_bytes::Map;
372
373  fn test_service(schema_sdl: &str) -> MockService {
374    let schema = Schema::builder()
375      .parse(
376        "directive @mock(hint: String) on QUERY | MUTATION | FIELD",
377        "mock-directive.graphql",
378      )
379      .parse(schema_sdl, "schema.graphql")
380      .build()
381      .unwrap();
382    let schema = Arc::new(schema.validate().unwrap());
383    let client = Client::builder().timeout(Duration::from_secs(30)).build().unwrap();
384    MockService::new(schema, Default::default(), client)
385  }
386
387  #[test]
388  fn new_builds_service() {
389    let service = test_service("type Query { hello: String }");
390    assert!(matches!(
391      service.plan("{ hello }", None, &Map::new(), None),
392      Ok(MockPlan::NoMocks)
393    ));
394  }
395
396  #[test]
397  fn plan_without_mocks_returns_no_mocks() {
398    let service = test_service("type Query { hello: String }");
399    let plan = service
400      .plan("{ hello }", None, &Map::new(), None)
401      .expect("plan should succeed");
402    assert!(matches!(plan, MockPlan::NoMocks));
403  }
404
405  #[test]
406  fn plan_full_mock_returns_full_mock() {
407    let service = test_service("type Query { hello: String }");
408    let plan = service
409      .plan("{ hello @mock }", None, &Map::new(), None)
410      .expect("plan should succeed");
411    assert!(matches!(plan, MockPlan::FullMock(_)));
412  }
413
414  #[test]
415  fn plan_partial_mock_returns_partial_mock() {
416    let service = test_service(
417      r"
418        type Query { me: User }
419        type User { id: ID name: String }
420      ",
421    );
422    let plan = service
423      .plan("{ me { id name @mock } }", None, &Map::new(), None)
424      .expect("plan should succeed");
425    assert!(matches!(plan, MockPlan::PartialMock { .. }));
426  }
427
428  #[test]
429  fn plan_introspection_returns_introspection() {
430    let service = test_service("type Query { hello: String }");
431    let plan = service
432      .plan("{ __schema { queryType { name } } }", None, &Map::new(), None)
433      .expect("plan should succeed");
434    assert!(matches!(plan, MockPlan::Introspection(_)));
435  }
436}