hive-router 0.0.69

GraphQL router/gateway for Federation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::{sync::Arc, vec};

use futures_util::stream;
use graphql_tools::validation::utils::ValidationError;
use hive_router_internal::http::ReadBodyStreamError;
use hive_router_plan_executor::{
    coprocessor::CoprocessorError,
    execution::{
        error::PlanExecutionError, jwt_forward::JwtForwardingError, plan::FailedExecutionResult,
    },
    headers::errors::HeaderRuleRuntimeError,
    hooks::on_graphql_error::handle_graphql_errors_with_plugins,
    plugin_context::PluginContext,
    request_context::{RequestContextError, RequestContextExt},
    response::graphql_error::GraphQLError,
};
use hive_router_query_planner::{
    ast::normalization::error::NormalizationError, planner::PlannerError,
};
use http::{header, HeaderValue};
use http::{HeaderName, Method, StatusCode};
use ntex::{
    http::ResponseBuilder,
    web::{self, error::QueryPayloadError, HttpRequest},
};
use strum::IntoStaticStr;

use crate::{
    jwt::errors::JwtError,
    pipeline::{
        authorization::AuthorizationError,
        header::{ResponseMode, StreamContentType},
        multipart_subscribe::{
            self, APOLLO_MULTIPART_HTTP_CONTENT_TYPE, INCREMENTAL_DELIVERY_CONTENT_TYPE,
        },
        progressive_override::LabelEvaluationError,
        sse,
    },
    RouterSharedState,
};

pub type PipelineErrorAdditionalHeaders = Vec<(HeaderName, HeaderValue)>;

#[derive(Debug, thiserror::Error, IntoStaticStr)]
pub enum PipelineError {
    // HTTP-related errors
    #[error("Unsupported HTTP method: {0}")]
    #[strum(serialize = "METHOD_NOT_ALLOWED")]
    UnsupportedHttpMethod(Method),
    #[error("Header '{0}' has invalid value")]
    #[strum(serialize = "INVALID_HEADER")]
    InvalidHeaderValue(HeaderName),
    #[error("Content-Type header is missing")]
    #[strum(serialize = "MISSING_CONTENT_TYPE_HEADER")]
    MissingContentTypeHeader,
    #[error("Content-Type header is not supported")]
    #[strum(serialize = "UNSUPPORTED_CONTENT_TYPE")]
    UnsupportedContentType,

    // GET Specific pipeline errors
    #[error("Missing query parameter: {0}")]
    #[strum(serialize = "MISSING_QUERY_PARAM")]
    GetMissingQueryParam(&'static str),
    #[error("Cannot perform mutations over GET")]
    #[strum(serialize = "MUTATION_NOT_ALLOWED_OVER_HTTP_GET")]
    MutationNotAllowedOverHttpGet,
    #[error("Failed to parse query parameters")]
    #[strum(serialize = "UNPROCESSABLE_QUERY_PARAMS")]
    GetUnprocessableQueryParams(#[from] QueryPayloadError),

    // GraphQL-specific errors
    #[error("Failed to parse GraphQL request payload")]
    #[strum(serialize = "BAD_REQUEST")]
    FailedToParseBody(sonic_rs::Error),
    #[error("Failed to parse GraphQL variables JSON")]
    #[strum(serialize = "BAD_REQUEST")]
    FailedToParseVariables(sonic_rs::Error),
    #[error("Failed to parse GraphQL extensions JSON")]
    #[strum(serialize = "BAD_REQUEST")]
    FailedToParseExtensions(sonic_rs::Error),
    #[error("Failed to parse GraphQL operation: {0}")]
    #[strum(serialize = "GRAPHQL_PARSE_FAILED")]
    FailedToParseOperation(#[from] Arc<graphql_tools::parser::query::ParseError>),
    #[error("Persisted document not found: {0}")]
    #[strum(serialize = "PERSISTED_DOCUMENT_NOT_FOUND")]
    PersistedDocumentNotFound(String),
    #[error("Persisted document id is required")]
    #[strum(serialize = "PERSISTED_DOCUMENT_ID_REQUIRED")]
    PersistedDocumentIdRequired,
    #[error("{0}")]
    #[strum(serialize = "PERSISTED_DOCUMENT_EXTRACTION_FAILED")]
    PersistedDocumentExtraction(String),
    #[error("{0}")]
    #[strum(serialize = "PERSISTED_DOCUMENT_RESOLUTION_FAILED")]
    PersistedDocumentResolution(String),
    #[error("Failed to minify parsed GraphQL operation: {0}")]
    #[strum(serialize = "GRAPHQL_PARSE_MINIFY_FAILED")]
    FailedToMinifyParsedOperation(String),
    #[error("Failed to normalize GraphQL operation")]
    #[strum(serialize = "OPERATION_RESOLUTION_FAILURE")]
    NormalizationError(#[from] Arc<NormalizationError>),
    #[error("Failed to collect GraphQL variables: {0}")]
    #[strum(serialize = "BAD_USER_INPUT")]
    VariablesCoercionError(String),
    #[error("Validation errors")]
    #[strum(serialize = "GRAPHQL_VALIDATION_FAILED")]
    ValidationErrors(Arc<Vec<ValidationError>>),
    #[error("Authorization failed")]
    #[strum(serialize = "UNAUTHORIZED_OPERATION")]
    AuthorizationFailed(Vec<AuthorizationError>),
    #[error("Failed to execute a plan: {0}")]
    #[strum(serialize = "PLAN_EXECUTION_FAILED")]
    PlanExecutionError(#[from] PlanExecutionError),
    #[error("Failed to produce a plan: {0}")]
    #[strum(serialize = "QUERY_PLAN_BUILD_FAILED")]
    PlannerError(#[from] Arc<PlannerError>),
    #[error(transparent)]
    #[strum(serialize = "OVERRIDE_LABEL_EVALUATION_FAILED")]
    LabelEvaluationError(#[from] LabelEvaluationError),

    // HTTP Security-related errors
    #[error("Required CSRF header(s) not present")]
    #[strum(serialize = "CSRF_PREVENTION_FAILED")]
    CsrfPreventionFailed,

    // JWT-auth plugin errors
    #[error(transparent)]
    #[strum(serialize = "JWT_ERROR")]
    JwtError(#[from] JwtError),
    #[error("Failed to forward jwt: {0}")]
    #[strum(serialize = "JWT_FORWARDING_ERROR")]
    JwtForwardingError(#[from] JwtForwardingError),

    // Introspection permission errors
    #[error("Failed to evaluate introspection expression: {0}")]
    #[strum(serialize = "INTROSPECTION_PERMISSION_EVALUATION_ERROR")]
    IntrospectionPermissionEvaluationError(String),
    #[error("Introspection queries are disabled")]
    #[strum(serialize = "INTROSPECTION_DISABLED")]
    IntrospectionDisabled,

    // Subscription-related errors
    #[error("Subscriptions are not supported")]
    #[strum(serialize = "SUBSCRIPTIONS_NOT_SUPPORTED")]
    SubscriptionsNotSupported,
    #[error("Subscriptions are not supported over accepted transport(s)")]
    #[strum(serialize = "SUBSCRIPTIONS_TRANSPORT_NOT_SUPPORTED")]
    SubscriptionsTransportNotSupported,

    #[error(transparent)]
    #[strum(serialize = "READ_BODY_STREAM_ERROR")]
    ReadBodyStreamError(#[from] ReadBodyStreamError),

    #[error("Request timed out")]
    #[strum(serialize = "GATEWAY_TIMEOUT")]
    TimeoutError,

    #[error(transparent)]
    #[strum(serialize = "HEADER_PROPAGATION_FAILURE")]
    HeaderPropagation(#[from] HeaderRuleRuntimeError),

    #[error("Failed to serialize the query plan: {0}")]
    #[strum(serialize = "QUERY_PLAN_SERIALIZATION_FAILED")]
    QueryPlanSerializationFailed(sonic_rs::Error),

    #[error("No supergraph available yet, unable to process request")]
    #[strum(serialize = "NO_SUPERGRAPH_AVAILABLE")]
    NoSupergraphAvailable {
        response_headers: PipelineErrorAdditionalHeaders,
    },

    // Demand Control
    #[error("Operation estimated cost exceeds max cost")]
    #[strum(serialize = "COST_ESTIMATED_TOO_EXPENSIVE")]
    CostEstimatedTooExpensive {
        response_headers: PipelineErrorAdditionalHeaders,
    },

    #[error(
        "Exactly one slicing argument is required for field '{field_name}', but found {found}"
    )]
    #[strum(serialize = "COST_INVALID_SLICING_ARGUMENTS")]
    CostInvalidSlicingArguments { field_name: String, found: usize },

    #[error(transparent)]
    CoprocessorError(#[from] CoprocessorError),

    #[error("Request context error")]
    RequestContextError(#[from] RequestContextError),
}

#[derive(Clone, Debug, thiserror::Error)]
pub enum ParserCacheError {
    #[error("Failed to parse GraphQL operation: {0}")]
    ParseError(Arc<graphql_tools::parser::query::ParseError>),
    #[error("Failed to minify parsed GraphQL operation: {0}")]
    MinifyError(String),
    #[error("Validation errors")]
    ValidationErrors(Arc<Vec<ValidationError>>),
}

impl From<Arc<ParserCacheError>> for PipelineError {
    fn from(value: Arc<ParserCacheError>) -> Self {
        match value.as_ref() {
            ParserCacheError::ParseError(err) => PipelineError::FailedToParseOperation(err.clone()),
            ParserCacheError::MinifyError(err) => {
                PipelineError::FailedToMinifyParsedOperation(err.clone())
            }
            ParserCacheError::ValidationErrors(errs) => {
                PipelineError::ValidationErrors(errs.clone())
            }
        }
    }
}

impl PipelineError {
    pub fn additional_response_headers(&self) -> Option<&Vec<(HeaderName, HeaderValue)>> {
        match self {
            PipelineError::CostEstimatedTooExpensive { response_headers } => Some(response_headers),
            PipelineError::NoSupergraphAvailable { response_headers } => Some(response_headers),
            _ => None,
        }
    }

    pub fn graphql_error_code(&self) -> &'static str {
        match self {
            Self::JwtError(err) => err.error_code(),
            Self::PlanExecutionError(err) => err.error_code(),
            Self::ReadBodyStreamError(err) => err.error_code(),
            Self::CoprocessorError(err) => err.error_code(),
            _ => self.into(),
        }
    }

    pub fn graphql_error_message(&self) -> String {
        match self {
            Self::PlannerError(_) => "Unexpected error".to_string(),
            Self::CoprocessorError(_) => "Internal server error".to_string(),
            _ => self.to_string(),
        }
    }

    pub fn default_status_code(&self, prefer_ok: bool) -> StatusCode {
        match (self, prefer_ok) {
            (Self::PlannerError(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
            (Self::PlanExecutionError(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
            (Self::LabelEvaluationError(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
            (Self::JwtForwardingError(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
            (Self::UnsupportedHttpMethod(_), _) => StatusCode::METHOD_NOT_ALLOWED,
            (Self::InvalidHeaderValue(_), _) => StatusCode::BAD_REQUEST,
            (Self::GetUnprocessableQueryParams(_), _) => StatusCode::BAD_REQUEST,
            (Self::GetMissingQueryParam(_), _) => StatusCode::BAD_REQUEST,
            (Self::FailedToParseBody(_), _) => StatusCode::BAD_REQUEST,
            (Self::FailedToParseVariables(_), _) => StatusCode::BAD_REQUEST,
            (Self::FailedToParseExtensions(_), _) => StatusCode::BAD_REQUEST,
            (Self::PersistedDocumentNotFound(_), false) => StatusCode::BAD_REQUEST,
            (Self::PersistedDocumentNotFound(_), true) => StatusCode::OK,
            (Self::PersistedDocumentIdRequired, false) => StatusCode::BAD_REQUEST,
            (Self::PersistedDocumentIdRequired, true) => StatusCode::OK,
            (Self::PersistedDocumentExtraction(_), false) => StatusCode::BAD_REQUEST,
            (Self::PersistedDocumentExtraction(_), true) => StatusCode::OK,
            (Self::PersistedDocumentResolution(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
            (Self::FailedToParseOperation(_), false) => StatusCode::BAD_REQUEST,
            (Self::FailedToParseOperation(_), true) => StatusCode::OK,
            (Self::FailedToMinifyParsedOperation(_), false) => StatusCode::BAD_REQUEST,
            (Self::FailedToMinifyParsedOperation(_), true) => StatusCode::OK,
            (Self::NormalizationError(_), _) => StatusCode::BAD_REQUEST,
            (Self::VariablesCoercionError(_), false) => StatusCode::BAD_REQUEST,
            (Self::VariablesCoercionError(_), true) => StatusCode::OK,
            (Self::MutationNotAllowedOverHttpGet, _) => StatusCode::METHOD_NOT_ALLOWED,
            (Self::ValidationErrors(_), true) => StatusCode::OK,
            (Self::ValidationErrors(_), false) => StatusCode::BAD_REQUEST,
            (Self::CostEstimatedTooExpensive { .. }, true) => StatusCode::OK,
            (Self::CostEstimatedTooExpensive { .. }, false) => StatusCode::BAD_REQUEST,
            (Self::CostInvalidSlicingArguments { .. }, true) => StatusCode::OK,
            (Self::CostInvalidSlicingArguments { .. }, false) => StatusCode::BAD_REQUEST,
            (Self::AuthorizationFailed(_), _) => StatusCode::FORBIDDEN,
            (Self::MissingContentTypeHeader, _) => StatusCode::NOT_ACCEPTABLE,
            (Self::UnsupportedContentType, _) => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            (Self::CsrfPreventionFailed, _) => StatusCode::FORBIDDEN,
            (Self::JwtError(err), _) => err.status_code(),
            (Self::IntrospectionPermissionEvaluationError(_), _) => {
                StatusCode::INTERNAL_SERVER_ERROR
            }
            (Self::IntrospectionDisabled, _) => StatusCode::FORBIDDEN,
            (Self::SubscriptionsNotSupported, _) => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            (Self::SubscriptionsTransportNotSupported, _) => StatusCode::NOT_ACCEPTABLE,
            (Self::ReadBodyStreamError(err), _) => err.status_code(),
            (Self::TimeoutError, _) => StatusCode::GATEWAY_TIMEOUT,
            (Self::HeaderPropagation(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
            (Self::QueryPlanSerializationFailed(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
            (Self::NoSupergraphAvailable { .. }, _) => StatusCode::SERVICE_UNAVAILABLE,
            (Self::CoprocessorError(err), _) => err.status_code(),
            (Self::RequestContextError(_), _) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

#[inline]
pub fn handle_pipeline_error(
    err: PipelineError,
    req: &HttpRequest,
    shared_state: &RouterSharedState,
    response_mode: &ResponseMode,
) -> web::HttpResponse {
    let status = if matches!(response_mode, ResponseMode::StreamOnly(_)) {
        // alwats status OK for streaming response modes, because we accept
        // the stream and then stream the error from within the stream by default
        StatusCode::OK
    } else {
        let prefer_ok = response_mode.prefer_status_ok_for_errors();
        err.default_status_code(prefer_ok)
    };

    let mut res = ResponseBuilder::new(status);

    if let Some(headers) = err.additional_response_headers() {
        for (name, value) in headers {
            res.header(name, value);
        }
    }

    let mut errors = match err {
        PipelineError::ValidationErrors(ref validation_errors) => {
            validation_errors.iter().map(|error| error.into()).collect()
        }
        PipelineError::AuthorizationFailed(ref authorization_errors) => authorization_errors
            .iter()
            .map(|error| error.into())
            .collect(),
        PipelineError::CostEstimatedTooExpensive { .. } => {
            vec![GraphQLError::from_message_and_code(
                err.graphql_error_message(),
                "COST_ESTIMATED_TOO_EXPENSIVE",
            )]
        }
        _ => {
            let code = err.graphql_error_code();
            let message = err.graphql_error_message();
            let graphql_error = GraphQLError::from_message_and_code(message, code);

            vec![graphql_error]
        }
    };

    if let Some(plugins) = &shared_state.plugins {
        let plugin_context = req.extensions().get::<Arc<PluginContext>>().cloned();
        let request_context = req.read_request_context().ok();
        if let (Some(plugin_context), Some(request_context)) = (plugin_context, request_context) {
            let (new_errors, new_status_code) = handle_graphql_errors_with_plugins(
                plugins,
                plugin_context.as_ref(),
                &request_context,
                errors,
                status,
            );
            errors = new_errors;
            res.status(new_status_code);
        }
    }

    if let Some(error_recorder) = shared_state
        .telemetry_context
        .metrics
        .graphql
        .error_recorder()
    {
        error_recorder
            .record_errors(|| errors.iter().map(|error| error.extensions.code.as_deref()));
    }

    let data = FailedExecutionResult { errors }.serialize();

    match response_mode {
        ResponseMode::SingleOnly(content_type) | ResponseMode::Dual(content_type, _) => res
            .header(header::CONTENT_TYPE, content_type.as_ref())
            .body(data),
        ResponseMode::StreamOnly(StreamContentType::IncrementalDelivery) => res
            .header(
                header::CONTENT_TYPE,
                http::HeaderValue::from_static(INCREMENTAL_DELIVERY_CONTENT_TYPE),
            )
            .streaming(multipart_subscribe::create_incremental_delivery_stream(
                Box::pin(stream::once(async move { data })),
            )),
        ResponseMode::StreamOnly(StreamContentType::SSE) => res
            .header(
                header::CONTENT_TYPE,
                http::HeaderValue::from_static("text/event-stream"),
            )
            .streaming(sse::create_stream(
                Box::pin(stream::once(async move { data })),
                std::time::Duration::from_secs(10),
            )),
        ResponseMode::StreamOnly(StreamContentType::ApolloMultipartHTTP) => res
            .header(
                header::CONTENT_TYPE,
                http::HeaderValue::from_static(APOLLO_MULTIPART_HTTP_CONTENT_TYPE),
            )
            .streaming(multipart_subscribe::create_apollo_multipart_http_stream(
                Box::pin(stream::once(async move { data })),
                std::time::Duration::from_secs(10),
            )),
        ResponseMode::Laboratory => {
            unreachable!(
                "Laboratory can not be a response mode because Laboratory requests can not execute operations"
            )
        }
    }
}