suku 0.1.1

GraphQL over HTTP for Rust
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
//! Axum integration (enabled by the default `axum` feature).
//!
//! [`GraphQL`] is a small builder around [`Server`]. It produces an [`axum::Router`] with one
//! route; authentication is a plain `async` closure that receives a [`ContextRequest`]. The same
//! route serves `GET`/`POST`/GraphiQL and, with the default `ws` feature, accepts
//! `graphql-transport-ws` upgrades. Disable upgrades for one mount with
//! [`GraphQL::websocket`].
//!
//! ```no_run
//! use suku::{Context, axum::GraphQL, http::{ContextRequest, HttpError}};
//!
//! # fn run(schema: gql::Schema) {
//! let app = GraphQL::new(suku::Server::new(schema))
//!     .path("/graphql")
//!     .with_context(|request: ContextRequest| async move {
//!         let Some(value) = request.header("authorization") else {
//!             return Err(HttpError::message(
//!                 ::http::StatusCode::UNAUTHORIZED,
//!                 "Missing bearer token",
//!             ));
//!         };
//!         let value = value.to_str().unwrap_or_default();
//!         Ok(Context::new(value.to_owned()))
//!     })
//!     .into_router();
//! # let _ = app;
//! # }
//! ```
//!
//! The builder does not install CORS or tracing; compose those layers yourself so they match the
//! rest of your application.

use core::future::Future;
use std::sync::Arc;

#[cfg(feature = "ws")]
use ::axum::extract::FromRequestParts as _;
use ::axum::{
    Router,
    body::{Body, to_bytes},
    extract::{Request, State},
    response::Response as AxumResponse,
    routing::any,
};
#[cfg(feature = "ws")]
use ::http::{HeaderMap, HeaderName};
use ::http::{HeaderValue, StatusCode, header};
use futures::future::BoxFuture;

use crate::{
    Context, Server,
    http::{
        ContextRequest, ExtractContext, HttpConfig, HttpError, HttpResponse, HttpResult,
        SseResponse,
    },
    response::ResponseExt as _,
};

#[cfg(feature = "ws")]
use crate::ws::WsConfig;

/// An Axum integration builder for a GraphQL server.
pub struct GraphQL {
    server: Server,
    config: HttpConfig,
    extractor: Arc<dyn ExtractContext>,
    #[cfg(feature = "ws")]
    websocket: bool,
    #[cfg(feature = "ws")]
    ws_config: WsConfig,
}

impl core::fmt::Debug for GraphQL {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut debug = f.debug_struct("GraphQL");
        debug
            .field("server", &self.server)
            .field("config", &self.config);
        #[cfg(feature = "ws")]
        debug
            .field("websocket", &self.websocket)
            .field("ws_config", &self.ws_config);
        debug.finish_non_exhaustive()
    }
}

impl GraphQL {
    /// Start building an endpoint for `server`.
    #[must_use]
    pub fn new(server: Server) -> Self {
        Self {
            server,
            config: HttpConfig::default(),
            extractor: Arc::new(empty_extractor),
            #[cfg(feature = "ws")]
            websocket: true,
            #[cfg(feature = "ws")]
            ws_config: WsConfig::default(),
        }
    }

    /// Mount at a different path. Defaults to `/graphql`.
    #[must_use]
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.config = self.config.path(path);
        self
    }

    /// Enable or disable the GraphiQL page. Defaults to enabled.
    #[must_use]
    pub const fn graphiql(mut self, enabled: bool) -> Self {
        self.config.graphiql = enabled;
        self
    }

    /// Override the request body limit for this mount.
    #[must_use]
    pub const fn max_body_bytes(mut self, bytes: usize) -> Self {
        self.config.max_body_bytes = Some(bytes);
        self
    }

    /// Override the batch size limit for this mount.
    #[must_use]
    pub const fn max_batch_size(mut self, size: usize) -> Self {
        self.config.max_batch_size = Some(size);
        self
    }

    /// Override the multipart part limit for this mount.
    #[must_use]
    pub const fn max_multipart_parts(mut self, parts: usize) -> Self {
        self.config.max_multipart_parts = Some(parts);
        self
    }

    /// Enable or disable WebSocket subscriptions on this mount. Defaults to enabled.
    ///
    /// This is a runtime switch on top of the compile-time `ws` feature. When disabled (or when
    /// the feature is off), an upgrade request falls through to the normal GET handling.
    #[cfg(feature = "ws")]
    #[must_use]
    pub const fn websocket(mut self, enabled: bool) -> Self {
        self.websocket = enabled;
        self
    }

    /// Override the WebSocket protocol limits for this mount.
    #[cfg(feature = "ws")]
    #[must_use]
    pub fn ws_config(mut self, config: WsConfig) -> Self {
        self.ws_config = config;
        self
    }

    /// Authenticate requests and build their context.
    ///
    /// The closure receives a cloneable snapshot of the request parts, so it can read
    /// `Authorization`, cookies and middleware request extensions. Returning `Err` stops the
    /// request before the body is parsed or any resolver runs.
    #[must_use]
    pub fn with_context<F, Fut>(mut self, extractor: F) -> Self
    where
        F: Fn(ContextRequest) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Context, HttpError>> + Send + 'static,
    {
        self.extractor = Arc::new(extractor);
        self
    }

    /// Use a pre-built extractor, useful when the extractor is shared with other endpoints.
    #[must_use]
    pub fn with_extractor(mut self, extractor: Arc<dyn ExtractContext>) -> Self {
        self.extractor = extractor;
        self
    }

    /// The server this builder will mount.
    #[must_use]
    pub fn server(&self) -> &Server {
        &self.server
    }

    /// The HTTP configuration for this mount.
    #[must_use]
    pub fn config(&self) -> &HttpConfig {
        &self.config
    }

    /// Build an Axum router with the GraphQL endpoint mounted.
    pub fn into_router(self) -> Router {
        let path = self.config.path.clone();
        let state = Arc::new(HandlerState {
            server: self.server,
            config: self.config,
            extractor: self.extractor,
            #[cfg(feature = "ws")]
            websocket: self.websocket,
            #[cfg(feature = "ws")]
            ws_config: self.ws_config,
        });

        Router::new().route(&path, any(handler)).with_state(state)
    }

    /// Build an Axum router. Alias for [`GraphQL::into_router`].
    pub fn router(self) -> Router {
        self.into_router()
    }
}

impl From<Server> for GraphQL {
    fn from(value: Server) -> Self {
        Self::new(value)
    }
}

/// Build an Axum endpoint for a server.
#[must_use]
pub fn graphql(server: Server) -> GraphQL {
    GraphQL::new(server)
}

/// Build an Axum router for a server using the default configuration.
///
/// Equivalent to `GraphQL::new(server).into_router()`.
#[must_use]
pub fn router(server: Server) -> Router {
    GraphQL::new(server).into_router()
}

struct HandlerState {
    server: Server,
    config: HttpConfig,
    extractor: Arc<dyn ExtractContext>,
    #[cfg(feature = "ws")]
    websocket: bool,
    #[cfg(feature = "ws")]
    ws_config: WsConfig,
}

async fn handler(State(state): State<Arc<HandlerState>>, request: Request) -> AxumResponse {
    #[cfg(feature = "ws")]
    if state.websocket && is_websocket_upgrade(request.headers()) {
        return websocket_response(state, request).await;
    }

    let (parts, body) = request.into_parts();
    let configured_limit = state
        .config
        .max_body_bytes
        .unwrap_or_else(|| state.server.max_body_bytes_limit());
    let limit = if configured_limit == 0 {
        usize::MAX
    } else {
        configured_limit
    };

    let body = match to_bytes(body, limit).await {
        Ok(body) => body,
        Err(_) => {
            return error_response(
                &state.server,
                StatusCode::PAYLOAD_TOO_LARGE,
                "Request body could not be read or exceeded the size limit.",
            );
        }
    };

    let extractor = state.extractor.clone();
    let result =
        crate::http::handle_bytes(&state.server, &state.config, &parts, body, move |request| {
            extractor.extract(request)
        })
        .await;

    match result {
        HttpResult::Response(response) => buffered_response(response),
        HttpResult::Stream(response) => stream_response(response),
    }
}

fn buffered_response(response: HttpResponse) -> AxumResponse {
    let mut out = AxumResponse::new(Body::from(response.body));
    *out.status_mut() = response.status;
    *out.headers_mut() = response.headers;
    out
}

#[cfg(feature = "ws")]
async fn websocket_response(state: Arc<HandlerState>, request: Request) -> AxumResponse {
    if !offers_graphql_transport_ws(request.headers()) {
        return error_response(
            &state.server,
            StatusCode::BAD_REQUEST,
            &format!(
                "WebSocket connections must offer the `{}` subprotocol.",
                crate::ws::GRAPHQL_TRANSPORT_WS
            ),
        );
    }

    let (mut parts, _body) = request.into_parts();

    // Authenticate the upgrade exactly like an HTTP request. The resulting context is reused by
    // every operation on this connection; nothing a client sends after the upgrade can replace it.
    let context = match state
        .extractor
        .extract(ContextRequest::from_parts(&parts))
        .await
    {
        Ok(context) => context,
        Err(error) => return http_error_response(&state.server, error),
    };

    let upgrade =
        match ::axum::extract::WebSocketUpgrade::from_request_parts(&mut parts, &state).await {
            Ok(upgrade) => upgrade,
            Err(_) => {
                return error_response(
                    &state.server,
                    StatusCode::BAD_REQUEST,
                    "Invalid WebSocket upgrade request.",
                );
            }
        };

    let server = state.server.clone();
    let mut config = state.ws_config.clone();
    if config.max_message_bytes.is_none() {
        config.max_message_bytes = state.config.max_body_bytes;
    }
    upgrade
        .protocols([crate::ws::GRAPHQL_TRANSPORT_WS])
        .on_upgrade(move |socket| async move {
            crate::ws::serve_axum(server, config, context, socket).await;
        })
}

#[cfg(feature = "ws")]
fn is_websocket_upgrade(headers: &HeaderMap) -> bool {
    header_has_token(headers, header::UPGRADE, "websocket")
        && header_has_token(headers, header::CONNECTION, "upgrade")
}

#[cfg(feature = "ws")]
fn offers_graphql_transport_ws(headers: &HeaderMap) -> bool {
    headers
        .get(header::SEC_WEBSOCKET_PROTOCOL)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| {
            value
                .split(',')
                .any(|protocol| protocol.trim() == crate::ws::GRAPHQL_TRANSPORT_WS)
        })
}

#[cfg(feature = "ws")]
fn header_has_token(headers: &HeaderMap, name: HeaderName, token: &str) -> bool {
    headers
        .get(name)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| {
            value
                .split(',')
                .any(|candidate| candidate.trim().eq_ignore_ascii_case(token))
        })
}

#[cfg(feature = "ws")]
fn http_error_response(server: &Server, mut error: HttpError) -> AxumResponse {
    server.format_response(
        &mut error.response,
        crate::error::ResponseMeta::none(),
        crate::error::ErrorKind::Request,
    );
    let mut response = AxumResponse::new(Body::from(error.response.to_json_bytes()));
    *response.status_mut() = error.status;
    response.headers_mut().insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static("application/json; charset=utf-8"),
    );
    response.headers_mut().extend(error.headers);
    response
}

fn stream_response(response: SseResponse) -> AxumResponse {
    let mut out = AxumResponse::new(Body::from_stream(response.stream));
    *out.status_mut() = response.status;
    *out.headers_mut() = response.headers;
    out
}

fn error_response(server: &Server, status: StatusCode, message: &str) -> AxumResponse {
    let mut error = crate::response::error_response(message);
    server.format_response(
        &mut error,
        crate::error::ResponseMeta::none(),
        crate::error::ErrorKind::Request,
    );
    let mut response = AxumResponse::new(Body::from(error.to_json_bytes()));
    *response.status_mut() = status;
    response.headers_mut().insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static("application/json; charset=utf-8"),
    );
    response
}

fn empty_extractor(_: ContextRequest) -> BoxFuture<'static, Result<Context, HttpError>> {
    Box::pin(async { Ok(Context::empty()) })
}