spikard-graphql 0.16.1

GraphQL support for Spikard with async-graphql integration
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! GraphQL HTTP handler integration with Spikard
//!
//! This module provides HTTP request handling for GraphQL queries and mutations,
//! implementing the `Handler` trait for integration with Spikard's HTTP server
//! and tower-http middleware stack.

use crate::GraphQLExecutor;
use crate::error::GraphQLError;
use axum::{
    body::Body,
    http::{Request, Response, StatusCode},
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use spikard_http::{Handler, HandlerResult, RequestData};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

/// Maximum allowed GraphQL query size (1MB)
const MAX_QUERY_SIZE: usize = 1_048_576;

/// GraphQL request payload
///
/// Represents a standard GraphQL HTTP request body as defined by the GraphQL
/// specification for application/json requests.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct GraphQLRequestPayload {
    /// The GraphQL query string
    pub query: String,

    /// Optional query variables as a JSON object
    #[serde(default)]
    pub variables: Option<Value>,

    /// Optional operation name for selecting which operation to execute
    /// when the query contains multiple operations
    #[serde(rename = "operationName")]
    pub operation_name: Option<String>,
}

/// GraphQL response payload
///
/// Represents a standard GraphQL HTTP response body containing data
/// and optional errors.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GraphQLResponsePayload {
    /// Execution result data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,

    /// Execution errors (null if successful)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errors: Option<Vec<GraphQLErrorResponse>>,

    /// Extensions (optional, for tracing, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Value>,
}

/// GraphQL error response format
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GraphQLErrorResponse {
    /// Error message
    pub message: String,

    /// Optional locations in the query where the error occurred
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locations: Option<Vec<Value>>,

    /// Optional path to the field that caused the error
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<Vec<Value>>,

    /// Optional additional error details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Value>,
}

/// Parse GraphQL request from HTTP request body
///
/// # Arguments
///
/// * `raw_body` - Raw request body bytes
///
/// # Returns
///
/// Parsed GraphQL request payload or error
fn parse_graphql_request(raw_body: &[u8]) -> Result<GraphQLRequestPayload, GraphQLError> {
    if raw_body.len() > MAX_QUERY_SIZE {
        return Err(GraphQLError::RequestHandlingError(format!(
            "Request body exceeds maximum size of {MAX_QUERY_SIZE} bytes"
        )));
    }
    serde_json::from_slice(raw_body)
        .map_err(|e| GraphQLError::RequestHandlingError(format!("Failed to parse GraphQL request: {e}")))
}

/// GraphQL HTTP handler
///
/// Integrates GraphQL execution with Spikard's HTTP server and tower-http
/// middleware stack. Handles parsing GraphQL requests, executing them via
/// the GraphQL executor, and returning properly formatted responses.
///
/// # Type Parameters
///
/// * `Query` - The root GraphQL Query type
/// * `Mutation` - The root GraphQL Mutation type
/// * `Subscription` - The root GraphQL Subscription type
///
/// # Example
///
/// ```ignore
/// use spikard_graphql::{GraphQLHandler, GraphQLExecutor};
///
/// // With concrete types:
/// // let executor = GraphQLExecutor::<Query, Mutation, Subscription>::new(schema);
/// // let handler = GraphQLHandler::new(Arc::new(executor));
/// ```
#[derive(Debug)]
pub struct GraphQLHandler<Query, Mutation, Subscription> {
    executor: Arc<GraphQLExecutor<Query, Mutation, Subscription>>,
}

impl<Query, Mutation, Subscription> GraphQLHandler<Query, Mutation, Subscription>
where
    Query: async_graphql::ObjectType + Send + Sync + 'static,
    Mutation: async_graphql::ObjectType + Send + Sync + 'static,
    Subscription: async_graphql::SubscriptionType + Send + Sync + 'static,
{
    /// Create a new GraphQL handler
    ///
    /// # Arguments
    ///
    /// * `executor` - Arc-wrapped GraphQL executor instance
    ///
    /// # Returns
    ///
    /// A new `GraphQLHandler` instance
    #[must_use]
    pub const fn new(executor: Arc<GraphQLExecutor<Query, Mutation, Subscription>>) -> Self {
        Self { executor }
    }

    /// Handle a GraphQL request
    ///
    /// # Arguments
    ///
    /// * `request_data` - The incoming request data
    ///
    /// # Returns
    ///
    /// Handler result with GraphQL response
    ///
    /// # Errors
    ///
    /// Returns `GraphQLError` if the request body cannot be parsed or execution fails.
    pub async fn handle_graphql(&self, request_data: &RequestData) -> Result<Value, GraphQLError> {
        // Extract raw body
        let body_bytes = request_data.raw_body.as_ref().map_or_else(
            || serde_json::to_vec(&request_data.body).unwrap_or_default(),
            |raw_body| raw_body.to_vec(),
        );

        // Parse the request payload
        let payload = parse_graphql_request(&body_bytes)?;

        // Execute the GraphQL query
        self.executor
            .execute(
                &payload.query,
                payload.variables.as_ref(),
                payload.operation_name.as_deref(),
            )
            .await
    }

    /// Create an HTTP response from a GraphQL result
    fn response_from_result(result: Result<Value, GraphQLError>) -> Response<Body> {
        match result {
            Ok(graphql_response) => {
                let body = serde_json::to_vec(&graphql_response).unwrap_or_else(|_| {
                    serde_json::to_vec(&json!({"errors": [{"message": "Failed to serialize GraphQL response"}]}))
                        .unwrap_or_else(|_| b"{\"errors\":[{\"message\":\"Internal server error\"}]}".to_vec())
                });
                Response::builder()
                    .status(StatusCode::OK)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap_or_else(|_| {
                        Response::builder()
                            .status(StatusCode::INTERNAL_SERVER_ERROR)
                            .body(Body::from("Internal server error"))
                            .unwrap()
                    })
            }
            Err(e) => {
                let status = StatusCode::from_u16(e.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                let error_response = e.to_graphql_response();
                let body = serde_json::to_vec(&error_response).unwrap_or_else(|_| {
                    serde_json::to_vec(&json!({"errors": [{"message": "Internal server error"}]}))
                        .unwrap_or_else(|_| b"{\"errors\":[{\"message\":\"Internal server error\"}]}".to_vec())
                });

                Response::builder()
                    .status(status)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap_or_else(|_| {
                        Response::builder()
                            .status(StatusCode::INTERNAL_SERVER_ERROR)
                            .body(Body::from("Internal server error"))
                            .unwrap()
                    })
            }
        }
    }
}

impl<Query, Mutation, Subscription> Clone for GraphQLHandler<Query, Mutation, Subscription> {
    fn clone(&self) -> Self {
        Self {
            executor: Arc::clone(&self.executor),
        }
    }
}

impl<Query, Mutation, Subscription> Handler for GraphQLHandler<Query, Mutation, Subscription>
where
    Query: async_graphql::ObjectType + Send + Sync + 'static,
    Mutation: async_graphql::ObjectType + Send + Sync + 'static,
    Subscription: async_graphql::SubscriptionType + Send + Sync + 'static,
{
    fn call(
        &self,
        _request: Request<Body>,
        request_data: RequestData,
    ) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>> {
        Box::pin(async move {
            let result = self.handle_graphql(&request_data).await;
            Ok(Self::response_from_result(result))
        })
    }

    fn prefers_raw_json_body(&self) -> bool {
        true
    }

    fn wants_headers(&self) -> bool {
        false
    }

    fn wants_cookies(&self) -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};

    #[derive(Default)]
    struct TestQuery;

    #[Object]
    impl TestQuery {
        async fn hello(&self) -> &'static str {
            "world"
        }
    }

    fn make_test_handler() -> GraphQLHandler<TestQuery, EmptyMutation, EmptySubscription> {
        let schema = Schema::build(TestQuery, EmptyMutation, EmptySubscription).finish();
        let executor = Arc::new(GraphQLExecutor::new(schema));
        GraphQLHandler::new(executor)
    }

    #[test]
    fn test_graphql_request_payload_parsing_minimal() {
        let json = r#"{"query":"{ hello }"}"#;
        let payload: GraphQLRequestPayload = serde_json::from_str(json).unwrap();

        assert_eq!(payload.query, "{ hello }");
        assert!(payload.variables.is_none());
        assert!(payload.operation_name.is_none());
    }

    #[test]
    fn test_graphql_request_payload_parsing_with_variables() {
        let json = r#"{"query":"query GetUser($id: ID!) { user(id: $id) { name } }","variables":{"id":"123"}}"#;
        let payload: GraphQLRequestPayload = serde_json::from_str(json).unwrap();

        assert_eq!(payload.query, "query GetUser($id: ID!) { user(id: $id) { name } }");
        assert!(payload.variables.is_some());
        assert_eq!(payload.variables.as_ref().unwrap()["id"], "123");
    }

    #[test]
    fn test_graphql_request_payload_parsing_with_operation_name() {
        let json =
            r#"{"query":"query GetUser { user { name } } query ListUsers { users { id } }","operationName":"GetUser"}"#;
        let payload: GraphQLRequestPayload = serde_json::from_str(json).unwrap();

        assert_eq!(payload.operation_name, Some("GetUser".to_string()));
    }

    #[test]
    fn test_graphql_request_payload_serialization() {
        let payload = GraphQLRequestPayload {
            query: "{ hello }".to_string(),
            variables: Some(json!({"test": "value"})),
            operation_name: Some("TestOp".to_string()),
        };

        let json = serde_json::to_string(&payload).unwrap();
        let parsed: GraphQLRequestPayload = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.query, payload.query);
        assert_eq!(parsed.variables, payload.variables);
        assert_eq!(parsed.operation_name, payload.operation_name);
    }

    #[test]
    fn test_graphql_response_payload_success() {
        let payload = GraphQLResponsePayload {
            data: Some(json!({"hello": "world"})),
            errors: None,
            extensions: None,
        };

        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"data\""));
        assert!(!json.contains("\"errors\""));
    }

    #[test]
    fn test_graphql_response_payload_with_errors() {
        let error = GraphQLErrorResponse {
            message: "Test error".to_string(),
            locations: None,
            path: None,
            extensions: None,
        };

        let payload = GraphQLResponsePayload {
            data: None,
            errors: Some(vec![error]),
            extensions: None,
        };

        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"errors\""));
        assert!(json.contains("Test error"));
    }

    #[test]
    fn test_parse_request_invalid_json() {
        let result = parse_graphql_request(b"invalid json");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_request_missing_query() {
        let result = parse_graphql_request(b"{}");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_request_exceeds_size_limit() {
        let huge_request = vec![b'x'; MAX_QUERY_SIZE + 1];
        let result = parse_graphql_request(&huge_request);
        assert!(result.is_err());
        match result.unwrap_err() {
            GraphQLError::RequestHandlingError(msg) => {
                assert!(msg.contains("exceeds maximum size"));
                assert!(msg.contains("1048576"));
            }
            _ => panic!("Expected RequestHandlingError"),
        }
    }

    #[test]
    fn test_parse_request_at_size_limit() {
        let request_at_limit = vec![b'x'; MAX_QUERY_SIZE];
        let result = parse_graphql_request(&request_at_limit);
        assert!(result.is_err());
        match result.unwrap_err() {
            GraphQLError::RequestHandlingError(msg) => {
                assert!(!msg.contains("exceeds maximum size"));
                assert!(msg.contains("Failed to parse GraphQL request"));
            }
            _ => panic!("Expected RequestHandlingError"),
        }
    }

    #[test]
    fn test_parse_request_normal_size_succeeds() {
        let json = r#"{"query":"{ hello }"}"#;
        let result = parse_graphql_request(json.as_bytes());
        assert!(result.is_ok());
        let payload = result.unwrap();
        assert_eq!(payload.query, "{ hello }");
    }

    #[test]
    fn test_handler_prefers_raw_json_body() {
        let handler = make_test_handler();
        assert!(handler.prefers_raw_json_body());
    }

    #[test]
    fn test_handler_does_not_want_headers() {
        let handler = make_test_handler();
        assert!(!handler.wants_headers());
    }

    #[test]
    fn test_handler_does_not_want_cookies() {
        let handler = make_test_handler();
        assert!(!handler.wants_cookies());
    }

    #[test]
    fn test_handler_clone() {
        let handler1 = make_test_handler();
        let handler2 = handler1.clone();

        // Verify Arc is shared
        assert!(Arc::ptr_eq(&handler1.executor, &handler2.executor));
    }
}