hyperlane_plugin_graphql/impl.rs
1use super::*;
2
3/// Accessors for [`FieldSelection`].
4impl FieldSelection {
5 /// Returns the output key for this field (its alias if specified, otherwise its field name).
6 ///
7 /// # Returns
8 ///
9 /// - `&str` - Response JSON key name.
10 #[inline]
11 pub fn response_key(&self) -> &str {
12 let Self { alias, name, .. } = self;
13 match alias {
14 Some(a) => a.as_str(),
15 None => name.as_str(),
16 }
17 }
18}
19
20/// Argument lookup helpers for [`GraphqlFieldArgs`].
21impl GraphqlFieldArgs {
22 /// Returns the argument value for `name`, if provided.
23 ///
24 /// # Arguments
25 ///
26 /// - `&str` - Argument name.
27 ///
28 /// # Returns
29 ///
30 /// - `Option<&Value>` - Argument JSON value.
31 #[inline]
32 pub fn arg(&self, name: &str) -> Option<&Value> {
33 self.get_arguments().get(name)
34 }
35
36 /// Returns a string argument by `name`.
37 ///
38 /// # Arguments
39 ///
40 /// - `&str` - Argument name.
41 ///
42 /// # Returns
43 ///
44 /// - `Option<&str>` - String value, if present and typed as string.
45 #[inline]
46 pub fn arg_str(&self, name: &str) -> Option<&str> {
47 self.arg(name).and_then(Value::as_str)
48 }
49
50 /// Returns an `i64` argument by `name`.
51 ///
52 /// # Arguments
53 ///
54 /// - `&str` - Argument name.
55 ///
56 /// # Returns
57 ///
58 /// - `Option<i64>` - Integer value, if present and typed as integer.
59 #[inline]
60 pub fn arg_i64(&self, name: &str) -> Option<i64> {
61 self.arg(name).and_then(Value::as_i64)
62 }
63}
64
65/// Implements [`GraphqlResolver`] for [`FnGraphqlResolver`].
66impl<F> GraphqlResolver for FnGraphqlResolver<F>
67where
68 F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
69{
70 /// Delegates resolution to the wrapped closure.
71 ///
72 /// # Arguments
73 ///
74 /// - `&GraphqlFieldArgs` - Field arguments and variables.
75 ///
76 /// # Returns
77 ///
78 /// - `Result<Value, String>` - Resolved JSON value or error.
79 fn resolve(&self, args: &GraphqlFieldArgs) -> Result<Value, String> {
80 let Self { func } = self;
81 func(args)
82 }
83}
84
85/// Constructors for [`GraphqlResponse`].
86impl GraphqlResponse {
87 /// Creates an error-only [`GraphqlResponse`].
88 ///
89 /// # Arguments
90 ///
91 /// - `S` - Error message string.
92 ///
93 /// # Returns
94 ///
95 /// - `Self` - GraphQL response containing a single error.
96 pub fn from_error<S>(message: S) -> Self
97 where
98 S: Into<String>,
99 {
100 Self {
101 data: None,
102 errors: vec![GraphqlError {
103 message: message.into(),
104 }],
105 }
106 }
107}
108
109/// Default construction for [`GraphqlConfig`].
110impl Default for GraphqlConfig {
111 /// Builds a default [`GraphqlConfig`] serving `/graphql` with DoS depth and complexity limits.
112 ///
113 /// # Returns
114 ///
115 /// - `Self` - Default configuration.
116 fn default() -> Self {
117 Self {
118 endpoint: DEFAULT_GRAPHQL_ENDPOINT.to_owned(),
119 max_depth: DEFAULT_MAX_DEPTH,
120 max_fields: DEFAULT_MAX_FIELDS,
121 max_query_bytes: DEFAULT_MAX_QUERY_BYTES,
122 allow_get: true,
123 }
124 }
125}
126
127/// Fluent builder helpers for [`GraphqlConfig`].
128impl GraphqlConfig {
129 /// Sets the exact endpoint path handled by [`GraphqlHook`].
130 ///
131 /// # Arguments
132 ///
133 /// - `S` - Endpoint path (for example `"/graphql"`).
134 ///
135 /// # Returns
136 ///
137 /// - `Self` - Updated configuration.
138 pub fn with_endpoint<S>(mut self, endpoint: S) -> Self
139 where
140 S: Into<String>,
141 {
142 self.set_endpoint(endpoint.into());
143 self
144 }
145
146 /// Sets the maximum query nesting depth.
147 ///
148 /// # Arguments
149 ///
150 /// - `usize` - Maximum depth (`>= 1`).
151 ///
152 /// # Returns
153 ///
154 /// - `Self` - Updated configuration.
155 pub fn with_max_depth(mut self, max_depth: usize) -> Self {
156 self.set_max_depth(max_depth.max(1));
157 self
158 }
159
160 /// Sets the maximum total field selections per operation.
161 ///
162 /// # Arguments
163 ///
164 /// - `usize` - Maximum selected fields (`>= 1`).
165 ///
166 /// # Returns
167 ///
168 /// - `Self` - Updated configuration.
169 pub fn with_max_fields(mut self, max_fields: usize) -> Self {
170 self.set_max_fields(max_fields.max(1));
171 self
172 }
173}
174
175/// Schema registration and GraphQL execution engine for [`GraphqlPlugin`].
176impl GraphqlPlugin {
177 /// Creates a new [`GraphqlPlugin`] with empty query and mutation registries.
178 ///
179 /// # Arguments
180 ///
181 /// - `GraphqlConfig` - GraphQL configuration.
182 ///
183 /// # Returns
184 ///
185 /// - `Self` - New GraphQL engine ready for resolver registration.
186 pub fn new(config: GraphqlConfig) -> Self {
187 Self {
188 config,
189 queries: hash_map_xx_hash3_64(),
190 mutations: hash_map_xx_hash3_64(),
191 }
192 }
193
194 /// Registers a closure resolver for a root `Query` field.
195 ///
196 /// # Arguments
197 ///
198 /// - `N` - Field name.
199 /// - `F` - Resolver closure.
200 ///
201 /// # Returns
202 ///
203 /// - `Self` - Updated GraphQL plugin.
204 pub fn with_query<N, F>(mut self, field_name: N, resolver: F) -> Self
205 where
206 N: Into<String>,
207 F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
208 {
209 let Self { queries, .. } = &mut self;
210 let _: Option<Arc<dyn GraphqlResolver>> = queries.insert(
211 field_name.into(),
212 Arc::new(FnGraphqlResolver { func: resolver }),
213 );
214 self
215 }
216
217 /// Registers a closure resolver for a root `Mutation` field.
218 ///
219 /// # Arguments
220 ///
221 /// - `N` - Field name.
222 /// - `F` - Resolver closure.
223 ///
224 /// # Returns
225 ///
226 /// - `Self` - Updated GraphQL plugin.
227 pub fn with_mutation<N, F>(mut self, field_name: N, resolver: F) -> Self
228 where
229 N: Into<String>,
230 F: Fn(&GraphqlFieldArgs) -> Result<Value, String> + Send + Sync + 'static,
231 {
232 let Self { mutations, .. } = &mut self;
233 let _: Option<Arc<dyn GraphqlResolver>> = mutations.insert(
234 field_name.into(),
235 Arc::new(FnGraphqlResolver { func: resolver }),
236 );
237 self
238 }
239
240 /// Installs `plugin` as the global [`GraphqlPlugin`] singleton once.
241 ///
242 /// # Arguments
243 ///
244 /// - `Self` - Configured GraphQL engine.
245 ///
246 /// # Returns
247 ///
248 /// - `&'static Self` - Reference to the global plugin.
249 pub fn init(plugin: Self) -> &'static Self {
250 GRAPHQL_PLUGIN.get_or_init(|| plugin)
251 }
252
253 /// Returns the initialized global [`GraphqlPlugin`], if configured.
254 ///
255 /// # Returns
256 ///
257 /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
258 #[inline(always)]
259 pub fn get() -> Option<&'static Self> {
260 GRAPHQL_PLUGIN.get()
261 }
262
263 /// Returns the configured endpoint path.
264 ///
265 /// # Returns
266 ///
267 /// - `&str` - Endpoint path.
268 #[inline(always)]
269 pub fn endpoint(&self) -> &str {
270 let Self { config, .. } = self;
271 config.get_endpoint().as_str()
272 }
273
274 /// Executes a [`GraphqlRequest`] against registered query or mutation resolvers.
275 ///
276 /// # Arguments
277 ///
278 /// - `&GraphqlRequest` - Parsed request envelope.
279 /// - `bool` - Whether mutations are permitted (`true` for `POST`, `false` for `GET`).
280 ///
281 /// # Returns
282 ///
283 /// - `GraphqlResponse` - Spec-compliant data/errors response.
284 pub fn execute(&self, req: &GraphqlRequest, allow_mutation: bool) -> GraphqlResponse {
285 let Self {
286 config,
287 queries,
288 mutations,
289 ..
290 } = self;
291 if req.get_query().len() > config.get_max_query_bytes() {
292 return GraphqlResponse::from_error(ERR_QUERY_TOO_LARGE);
293 }
294 let op: ParsedOperation = match parse_graphql_document(
295 req.get_query(),
296 req.get_variables(),
297 config.get_max_depth(),
298 config.get_max_fields(),
299 ) {
300 Ok(parsed) => parsed,
301 Err(err) => return GraphqlResponse::from_error(err),
302 };
303 if op.get_kind() == OperationKind::Mutation && !allow_mutation {
304 return GraphqlResponse::from_error(ERR_GET_MUTATION);
305 }
306 let registry: &HashMapXxHash3_64<String, Arc<dyn GraphqlResolver>> = match op.get_kind() {
307 OperationKind::Query => queries,
308 OperationKind::Mutation => mutations,
309 };
310 let mut data_map: Map<String, Value> = Map::with_capacity(op.get_selections().len());
311 let mut errors: Vec<GraphqlError> = Vec::new();
312 for sel in op.get_selections() {
313 let out_key: String = sel.response_key().to_owned();
314 if let Some(resolver) = registry.get(sel.get_name()) {
315 let args: GraphqlFieldArgs = GraphqlFieldArgs {
316 arguments: sel.get_arguments().clone(),
317 variables: req.get_variables().clone(),
318 };
319 match resolver.resolve(&args) {
320 Ok(val) => {
321 let projected: Value = project_selection(val, sel.get_sub_fields());
322 let _: Option<Value> = data_map.insert(out_key, projected);
323 }
324 Err(msg) => {
325 let _: Option<Value> = data_map.insert(out_key, Value::Null);
326 errors.push(GraphqlError { message: msg });
327 }
328 }
329 } else {
330 let _: Option<Value> = data_map.insert(out_key, Value::Null);
331 errors.push(GraphqlError {
332 message: format!("unknown GraphQL field: {}", sel.get_name()),
333 });
334 }
335 }
336 GraphqlResponse {
337 data: Some(Value::Object(data_map)),
338 errors,
339 }
340 }
341
342 /// Handles an incoming HTTP [`Request`] targeted at the GraphQL endpoint.
343 ///
344 /// # Arguments
345 ///
346 /// - `&Request` - Incoming HTTP request.
347 ///
348 /// # Returns
349 ///
350 /// - `(HttpStatus, Vec<u8>)` - HTTP status code and serialized JSON response bytes.
351 pub fn handle_http_request(&self, request: &Request) -> (HttpStatus, Vec<u8>) {
352 let Self { config, .. } = self;
353 let method: &Method = request.get_method();
354 if method.is_post() {
355 let gql_req: GraphqlRequest = match from_slice(request.get_body()) {
356 Ok(parsed) => parsed,
357 Err(_) => {
358 let err: GraphqlResponse = GraphqlResponse::from_error(ERR_INVALID_JSON);
359 return (HttpStatus::BadRequest, to_vec(&err).unwrap_or_default());
360 }
361 };
362 let resp: GraphqlResponse = self.execute(&gql_req, true);
363 (HttpStatus::Ok, to_vec(&resp).unwrap_or_default())
364 } else if method.is_get() && config.get_allow_get() {
365 let Some(query_val) = request
366 .try_get_query(QUERY_PARAM_KEY)
367 .and_then(|vals: VecDeque<String>| vals.into_iter().next())
368 else {
369 let err: GraphqlResponse = GraphqlResponse::from_error(ERR_MISSING_QUERY);
370 return (HttpStatus::BadRequest, to_vec(&err).unwrap_or_default());
371 };
372 let gql_req: GraphqlRequest = GraphqlRequest {
373 query: query_val,
374 operation_name: None,
375 variables: Map::new(),
376 };
377 let resp: GraphqlResponse = self.execute(&gql_req, false);
378 (HttpStatus::Ok, to_vec(&resp).unwrap_or_default())
379 } else {
380 let err: GraphqlResponse = GraphqlResponse::from_error(ERR_METHOD_NOT_ALLOWED);
381 (
382 HttpStatus::MethodNotAllowed,
383 to_vec(&err).unwrap_or_default(),
384 )
385 }
386 }
387}
388
389/// Implements [`ServerHook`] for [`GraphqlHook`].
390impl ServerHook for GraphqlHook {
391 /// Constructs a per-request [`GraphqlHook`].
392 ///
393 /// # Arguments
394 ///
395 /// - `&mut Stream` - Connection stream.
396 /// - `&mut Context` - Request context.
397 ///
398 /// # Returns
399 ///
400 /// - `Self` - Hook instance.
401 #[inline(always)]
402 async fn new(_: &mut Stream, _: &mut Context) -> Self {
403 Self
404 }
405
406 /// Dispatches requests matching the configured GraphQL endpoint and bypasses all other routes.
407 ///
408 /// # Arguments
409 ///
410 /// - `Self` - Hook instance.
411 /// - `&mut Stream` - Connection stream.
412 /// - `&mut Context` - Request context.
413 ///
414 /// # Returns
415 ///
416 /// - `Status` - `Status::Continue` for other routes; `Status::Reject` after sending the GraphQL response.
417 #[inline(always)]
418 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
419 let Some(plugin) = GraphqlPlugin::get() else {
420 return Status::Continue;
421 };
422 if ctx.get_request().get_path() != plugin.endpoint() {
423 return Status::Continue;
424 }
425 let (status, body): (HttpStatus, Vec<u8>) = plugin.handle_http_request(ctx.get_request());
426 ctx.get_mut_response()
427 .set_status_code(status.code())
428 .set_header(CONTENT_TYPE, GRAPHQL_JSON_CONTENT_TYPE)
429 .set_body(body);
430 let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
431 Status::Reject
432 }
433}