hyperlane-plugin-graphql 23.3.1

A zero-external-parser GraphQL over HTTP plugin for the Hyperlane framework featuring a recursive-descent GraphQL query parser, depth and complexity DoS limits, XxHash3_64 query/mutation resolver registries, variable binding, and GraphQL-over-HTTP POST/GET dispatch.
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
433
use super::*;

/// Accessors for [`FieldSelection`].
impl FieldSelection {
    /// Returns the output key for this field (its alias if specified, otherwise its field name).
    ///
    /// # Returns
    ///
    /// - `&str` - Response JSON key name.
    #[inline]
    pub fn response_key(&self) -> &str {
        let Self { alias, name, .. } = self;
        match alias {
            Some(a) => a.as_str(),
            None => name.as_str(),
        }
    }
}

/// Argument lookup helpers for [`GraphqlFieldArgs`].
impl GraphqlFieldArgs {
    /// Returns the argument value for `name`, if provided.
    ///
    /// # Arguments
    ///
    /// - `&str` - Argument name.
    ///
    /// # Returns
    ///
    /// - `Option<&Value>` - Argument JSON value.
    #[inline]
    pub fn arg(&self, name: &str) -> Option<&Value> {
        self.get_arguments().get(name)
    }

    /// Returns a string argument by `name`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Argument name.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - String value, if present and typed as string.
    #[inline]
    pub fn arg_str(&self, name: &str) -> Option<&str> {
        self.arg(name).and_then(Value::as_str)
    }

    /// Returns an `i64` argument by `name`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Argument name.
    ///
    /// # Returns
    ///
    /// - `Option<i64>` - Integer value, if present and typed as integer.
    #[inline]
    pub fn arg_i64(&self, name: &str) -> Option<i64> {
        self.arg(name).and_then(Value::as_i64)
    }
}

/// Implements [`GraphqlResolver`] for [`FnGraphqlResolver`].
impl<F> GraphqlResolver for FnGraphqlResolver<F>
where
    F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
{
    /// Delegates resolution to the wrapped closure.
    ///
    /// # Arguments
    ///
    /// - `&GraphqlFieldArgs` - Field arguments and variables.
    ///
    /// # Returns
    ///
    /// - `Result<Value, String>` - Resolved JSON value or error.
    fn resolve(&self, args: &GraphqlFieldArgs) -> Result<Value, String> {
        let Self { func } = self;
        func(args)
    }
}

/// Constructors for [`GraphqlResponse`].
impl GraphqlResponse {
    /// Creates an error-only [`GraphqlResponse`].
    ///
    /// # Arguments
    ///
    /// - `S` - Error message string.
    ///
    /// # Returns
    ///
    /// - `Self` - GraphQL response containing a single error.
    pub fn from_error<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            data: None,
            errors: vec![GraphqlError {
                message: message.into(),
            }],
        }
    }
}

/// Default construction for [`GraphqlConfig`].
impl Default for GraphqlConfig {
    /// Builds a default [`GraphqlConfig`] serving `/graphql` with DoS depth and complexity limits.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            endpoint: DEFAULT_GRAPHQL_ENDPOINT.to_owned(),
            max_depth: DEFAULT_MAX_DEPTH,
            max_fields: DEFAULT_MAX_FIELDS,
            max_query_bytes: DEFAULT_MAX_QUERY_BYTES,
            allow_get: true,
        }
    }
}

/// Fluent builder helpers for [`GraphqlConfig`].
impl GraphqlConfig {
    /// Sets the exact endpoint path handled by [`GraphqlHook`].
    ///
    /// # Arguments
    ///
    /// - `S` - Endpoint path (for example `"/graphql"`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_endpoint<S>(mut self, endpoint: S) -> Self
    where
        S: Into<String>,
    {
        self.set_endpoint(endpoint.into());
        self
    }

    /// Sets the maximum query nesting depth.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum depth (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
        self.set_max_depth(max_depth.max(1));
        self
    }

    /// Sets the maximum total field selections per operation.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum selected fields (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_max_fields(mut self, max_fields: usize) -> Self {
        self.set_max_fields(max_fields.max(1));
        self
    }
}

/// Schema registration and GraphQL execution engine for [`GraphqlPlugin`].
impl GraphqlPlugin {
    /// Creates a new [`GraphqlPlugin`] with empty query and mutation registries.
    ///
    /// # Arguments
    ///
    /// - `GraphqlConfig` - GraphQL configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - New GraphQL engine ready for resolver registration.
    pub fn new(config: GraphqlConfig) -> Self {
        Self {
            config,
            queries: hash_map_xx_hash3_64(),
            mutations: hash_map_xx_hash3_64(),
        }
    }

    /// Registers a closure resolver for a root `Query` field.
    ///
    /// # Arguments
    ///
    /// - `N` - Field name.
    /// - `F` - Resolver closure.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated GraphQL plugin.
    pub fn with_query<N, F>(mut self, field_name: N, resolver: F) -> Self
    where
        N: Into<String>,
        F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
    {
        let Self { queries, .. } = &mut self;
        let _: Option<Arc<dyn GraphqlResolver>> = queries.insert(
            field_name.into(),
            Arc::new(FnGraphqlResolver { func: resolver }),
        );
        self
    }

    /// Registers a closure resolver for a root `Mutation` field.
    ///
    /// # Arguments
    ///
    /// - `N` - Field name.
    /// - `F` - Resolver closure.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated GraphQL plugin.
    pub fn with_mutation<N, F>(mut self, field_name: N, resolver: F) -> Self
    where
        N: Into<String>,
        F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
    {
        let Self { mutations, .. } = &mut self;
        let _: Option<Arc<dyn GraphqlResolver>> = mutations.insert(
            field_name.into(),
            Arc::new(FnGraphqlResolver { func: resolver }),
        );
        self
    }

    /// Installs `plugin` as the global [`GraphqlPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `Self` - Configured GraphQL engine.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(plugin: Self) -> &'static Self {
        GRAPHQL_PLUGIN.get_or_init(|| plugin)
    }

    /// Returns the initialized global [`GraphqlPlugin`], if configured.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        GRAPHQL_PLUGIN.get()
    }

    /// Returns the configured endpoint path.
    ///
    /// # Returns
    ///
    /// - `&str` - Endpoint path.
    #[inline(always)]
    pub fn endpoint(&self) -> &str {
        let Self { config, .. } = self;
        config.get_endpoint().as_str()
    }

    /// Executes a [`GraphqlRequest`] against registered query or mutation resolvers.
    ///
    /// # Arguments
    ///
    /// - `&GraphqlRequest` - Parsed request envelope.
    /// - `bool` - Whether mutations are permitted (`true` for `POST`, `false` for `GET`).
    ///
    /// # Returns
    ///
    /// - `GraphqlResponse` - Spec-compliant data/errors response.
    pub fn execute(&self, req: &GraphqlRequest, allow_mutation: bool) -> GraphqlResponse {
        let Self {
            config,
            queries,
            mutations,
            ..
        } = self;
        if req.get_query().len() > config.get_max_query_bytes() {
            return GraphqlResponse::from_error(ERR_QUERY_TOO_LARGE);
        }
        let op: ParsedOperation = match parse_graphql_document(
            req.get_query(),
            req.get_variables(),
            config.get_max_depth(),
            config.get_max_fields(),
        ) {
            Ok(parsed) => parsed,
            Err(err) => return GraphqlResponse::from_error(err),
        };
        if op.get_kind() == OperationKind::Mutation && !allow_mutation {
            return GraphqlResponse::from_error(ERR_GET_MUTATION);
        }
        let registry: &HashMapXxHash3_64<String, Arc<dyn GraphqlResolver>> = match op.get_kind() {
            OperationKind::Query => queries,
            OperationKind::Mutation => mutations,
        };
        let mut data_map: Map<String, Value> = Map::with_capacity(op.get_selections().len());
        let mut errors: Vec<GraphqlError> = Vec::new();
        for sel in op.get_selections() {
            let out_key: String = sel.response_key().to_owned();
            if let Some(resolver) = registry.get(sel.get_name()) {
                let args: GraphqlFieldArgs = GraphqlFieldArgs {
                    arguments: sel.get_arguments().clone(),
                    variables: req.get_variables().clone(),
                };
                match resolver.resolve(&args) {
                    Ok(val) => {
                        let projected: Value = project_selection(val, sel.get_sub_fields());
                        let _: Option<Value> = data_map.insert(out_key, projected);
                    }
                    Err(msg) => {
                        let _: Option<Value> = data_map.insert(out_key, Value::Null);
                        errors.push(GraphqlError { message: msg });
                    }
                }
            } else {
                let _: Option<Value> = data_map.insert(out_key, Value::Null);
                errors.push(GraphqlError {
                    message: format!("unknown GraphQL field: {}", sel.get_name()),
                });
            }
        }
        GraphqlResponse {
            data: Some(Value::Object(data_map)),
            errors,
        }
    }

    /// Handles an incoming HTTP [`Request`] targeted at the GraphQL endpoint.
    ///
    /// # Arguments
    ///
    /// - `&Request` - Incoming HTTP request.
    ///
    /// # Returns
    ///
    /// - `(HttpStatus, Vec<u8>)` - HTTP status code and serialized JSON response bytes.
    pub fn handle_http_request(&self, request: &Request) -> (HttpStatus, Vec<u8>) {
        let Self { config, .. } = self;
        let method: &Method = request.get_method();
        if method.is_post() {
            let gql_req: GraphqlRequest = match from_slice(request.get_body()) {
                Ok(parsed) => parsed,
                Err(_) => {
                    let err: GraphqlResponse = GraphqlResponse::from_error(ERR_INVALID_JSON);
                    return (HttpStatus::BadRequest, to_vec(&err).unwrap_or_default());
                }
            };
            let resp: GraphqlResponse = self.execute(&gql_req, true);
            (HttpStatus::Ok, to_vec(&resp).unwrap_or_default())
        } else if method.is_get() && config.get_allow_get() {
            let Some(query_val) = request
                .try_get_query(QUERY_PARAM_KEY)
                .and_then(|vals: VecDeque<String>| vals.into_iter().next())
            else {
                let err: GraphqlResponse = GraphqlResponse::from_error(ERR_MISSING_QUERY);
                return (HttpStatus::BadRequest, to_vec(&err).unwrap_or_default());
            };
            let gql_req: GraphqlRequest = GraphqlRequest {
                query: query_val,
                operation_name: None,
                variables: Map::new(),
            };
            let resp: GraphqlResponse = self.execute(&gql_req, false);
            (HttpStatus::Ok, to_vec(&resp).unwrap_or_default())
        } else {
            let err: GraphqlResponse = GraphqlResponse::from_error(ERR_METHOD_NOT_ALLOWED);
            (
                HttpStatus::MethodNotAllowed,
                to_vec(&err).unwrap_or_default(),
            )
        }
    }
}

/// Implements [`ServerHook`] for [`GraphqlHook`].
impl ServerHook for GraphqlHook {
    /// Constructs a per-request [`GraphqlHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Dispatches requests matching the configured GraphQL endpoint and bypasses all other routes.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Continue` for other routes; `Status::Reject` after sending the GraphQL response.
    #[inline(always)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = GraphqlPlugin::get() else {
            return Status::Continue;
        };
        if ctx.get_request().get_path() != plugin.endpoint() {
            return Status::Continue;
        }
        let (status, body): (HttpStatus, Vec<u8>) = plugin.handle_http_request(ctx.get_request());
        ctx.get_mut_response()
            .set_status_code(status.code())
            .set_header(CONTENT_TYPE, GRAPHQL_JSON_CONTENT_TYPE)
            .set_body(body);
        let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
        Status::Reject
    }
}