Skip to main content

mockql_core/schema/
introspection.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//! Schema loading via GraphQL introspection.
16
17use crate::Header;
18use cynic::http::CynicReqwestError;
19use cynic::http::ReqwestExt;
20use cynic_introspection::CapabilitySet;
21use cynic_introspection::IntrospectionQuery;
22use cynic_introspection::SchemaError;
23use cynic_introspection::SpecificationVersion;
24use reqwest::Client;
25use reqwest::StatusCode;
26use reqwest::Url;
27use reqwest::header::HeaderMap;
28
29/// Loads a validated Apollo schema by executing the standard introspection query.
30pub async fn load_schema_with_introspection(
31  url: &Url,
32  headers: &[Header],
33  client: &Client,
34) -> Result<String, IntrospectionError> {
35  let introspection_result =
36    match execute_instrospection_query(url, headers, client, SpecificationVersion::October2021.capabilities()).await {
37      Ok(introspection_result) => introspection_result,
38      Err(IntrospectionError::GraphqlErrors(_)) => {
39        // If the server returned GraphQL execution errors, try again with the June 2018 query.
40        execute_instrospection_query(url, headers, client, SpecificationVersion::June2018.capabilities()).await?
41      }
42      Err(error) => return Err(error),
43    };
44
45  Ok(
46    introspection_result
47      .into_schema()
48      .map_err(IntrospectionError::from)?
49      .to_sdl(),
50  )
51}
52
53pub async fn execute_instrospection_query(
54  url: &Url,
55  headers: &[Header],
56  client: &Client,
57  capability_set: CapabilitySet,
58) -> Result<IntrospectionQuery, IntrospectionError> {
59  let response = client
60    .post(url.clone())
61    .headers(headers.iter().cloned().collect::<HeaderMap>())
62    .run_graphql(IntrospectionQuery::with_capabilities(capability_set))
63    .await
64    .map_err(IntrospectionError::from)?;
65
66  if let Some(errors) = response.errors {
67    return Err(IntrospectionError::GraphqlErrors(format!("{errors:?}")));
68  }
69
70  response.data.ok_or(IntrospectionError::MissingSchema)
71}
72
73/// Errors raised while resolving a schema through GraphQL introspection.
74#[derive(Debug, thiserror::Error)]
75pub enum IntrospectionError {
76  /// The HTTP request failed before a response could be received.
77  #[error("introspection request failed: {0}")]
78  Request(#[source] reqwest::Error),
79  /// The server returned a non-success HTTP status.
80  #[error("introspection request returned HTTP status: {status}, body: {body}")]
81  HttpStatus {
82    /// HTTP status code returned by the introspection endpoint.
83    status: StatusCode,
84    /// Response body returned alongside the HTTP status.
85    body: String,
86  },
87  /// The server returned JSON that could not be decoded.
88  #[error("introspection response was not valid JSON: {0}")]
89  Json(#[source] serde_json::Error),
90  /// The introspection payload did not contain `data.__schema`.
91  #[error("introspection response did not contain a schema")]
92  MissingSchema,
93  /// The introspection response contained GraphQL execution errors.
94  #[error("introspection response contained GraphQL errors: {0}")]
95  GraphqlErrors(String),
96  /// The introspection response could not be converted into schema SDL.
97  #[error("failed to convert introspection response: {0}")]
98  Conversion(String),
99  /// Apollo rejected the reconstructed schema document.
100  #[error("failed to build Apollo schema: {0}")]
101  Schema(String),
102}
103
104impl From<CynicReqwestError> for IntrospectionError {
105  fn from(error: CynicReqwestError) -> Self {
106    match error {
107      CynicReqwestError::ReqwestError(error) => Self::Request(error),
108      CynicReqwestError::ErrorResponse(status, body) => Self::HttpStatus { status, body },
109    }
110  }
111}
112
113impl From<SchemaError> for IntrospectionError {
114  fn from(error: SchemaError) -> Self {
115    match error {
116      SchemaError::IntrospectionQueryFailed => Self::MissingSchema,
117      _ => Self::Conversion(error.to_string()),
118    }
119  }
120}