hive-router 0.2.0

GraphQL router for Federation, part of the Hive platform
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use schemars::JsonSchema;
use serde::{de::Error as _, Deserialize, Serialize};
use std::collections::HashSet;
use std::time::Duration;

use crate::config::primitives::file_path::FilePath;
use crate::config::primitives::retry_policy::RetryPolicyConfig;
use crate::config::primitives::single_or_multiple::SingleOrMultiple;
use crate::config::primitives::toggle::ToggleWith;
use crate::config::primitives::value_or_expression::ValueOrExpression;

#[derive(Debug, Serialize, JsonSchema, Clone, Default)]
pub struct PersistedDocumentsConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub require_id: ValueOrExpression<bool>,
    #[serde(default)]
    pub log_missing_id: bool,
    #[serde(default)]
    pub storage: Option<PersistedDocumentsStorageConfig>,
    #[serde(default)]
    pub selectors: Option<Vec<PersistedDocumentExtractorConfig>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPersistedDocumentsConfig {
    #[serde(default)]
    enabled: bool,
    #[serde(default)]
    require_id: ValueOrExpression<bool>,
    #[serde(default)]
    log_missing_id: bool,
    #[serde(default)]
    storage: Option<PersistedDocumentsStorageConfig>,
    #[serde(default)]
    selectors: Option<Vec<PersistedDocumentExtractorConfig>>,
}

impl<'de> Deserialize<'de> for PersistedDocumentsConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = RawPersistedDocumentsConfig::deserialize(deserializer)?;

        if raw.enabled && matches!(raw.selectors.as_ref(), Some(selectors) if selectors.is_empty())
        {
            return Err(D::Error::custom(
                "persisted_documents.selectors must not be an explicit empty list when persisted_documents.enabled=true",
            ));
        }

        if raw.enabled && raw.storage.is_none() {
            return Err(D::Error::custom(
                "persisted_documents.storage is required when persisted_documents.enabled=true",
            ));
        }

        if let Some(selectors) = raw.selectors.as_ref() {
            let mut seen = HashSet::new();
            for selector in selectors {
                if !seen.insert(selector.clone()) {
                    return Err(D::Error::custom(format!(
                        "persisted_documents.selectors contains a duplicate entry: {selector:?}"
                    )));
                }
            }
        }

        Ok(Self {
            enabled: raw.enabled,
            require_id: raw.require_id,
            log_missing_id: raw.log_missing_id,
            storage: raw.storage,
            selectors: raw.selectors,
        })
    }
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
#[serde(deny_unknown_fields, tag = "type", rename_all = "snake_case")]
pub enum PersistedDocumentsStorageConfig {
    File {
        #[serde(flatten)]
        config: PersistedDocumentsFileStorageConfig,
    },
    Hive {
        #[serde(flatten)]
        config: PersistedDocumentsHiveStorageConfig,
    },
    Storage {
        #[serde(flatten)]
        config: PersistedDocumentsStorageRefConfig,
    },
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
#[serde(deny_unknown_fields)]
pub struct PersistedDocumentsFileStorageConfig {
    pub path: FilePath,
    #[serde(default = "default_watch")]
    pub watch: bool,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
#[serde(deny_unknown_fields)]
pub struct PersistedDocumentsStorageRefConfig {
    pub storage_id: String,
    pub location: String,
    #[serde(
        default = "default_storage_poll_interval",
        deserialize_with = "humantime_serde::deserialize",
        serialize_with = "humantime_serde::serialize"
    )]
    #[schemars(with = "String")]
    pub poll_interval: Option<Duration>,
}

fn default_storage_poll_interval() -> Option<Duration> {
    None
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
#[serde(deny_unknown_fields)]
pub struct PersistedDocumentsHiveStorageConfig {
    /// The CDN endpoint from Hive Console target.
    /// Can also be set using the `HIVE_CDN_ENDPOINT` environment variable.
    pub endpoint: Option<SingleOrMultiple<String>>,
    /// The CDN Access Token with from the Hive Console target.
    /// Can also be set using the `HIVE_CDN_KEY` environment variable.
    pub key: Option<String>,
    #[serde(default = "default_hive_accept_invalid_certs")]
    pub accept_invalid_certs: bool,
    #[serde(
        default = "default_hive_connect_timeout",
        deserialize_with = "humantime_serde::deserialize",
        serialize_with = "humantime_serde::serialize"
    )]
    #[schemars(with = "String")]
    pub connect_timeout: Duration,
    #[serde(
        default = "default_hive_request_timeout",
        deserialize_with = "humantime_serde::deserialize",
        serialize_with = "humantime_serde::serialize"
    )]
    #[schemars(with = "String")]
    pub request_timeout: Duration,
    #[serde(default = "default_hive_retry_policy")]
    pub retry_policy: RetryPolicyConfig,
    #[serde(default = "default_hive_cache_size")]
    pub cache_size: u64,
    #[serde(default)]
    pub circuit_breaker: PersistedDocumentsHiveCircuitBreakerConfig,
    #[serde(default = "default_hive_negative_cache")]
    pub negative_cache: ToggleWith<PersistedDocumentsHiveNegativeCacheConfig>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct PersistedDocumentsHiveNegativeCacheConfig {
    #[serde(
        deserialize_with = "humantime_serde::deserialize",
        serialize_with = "humantime_serde::serialize"
    )]
    #[schemars(with = "String")]
    pub ttl: Duration,
}

impl Default for PersistedDocumentsHiveNegativeCacheConfig {
    fn default() -> Self {
        Self {
            ttl: Duration::from_secs(5),
        }
    }
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
#[serde(deny_unknown_fields)]
pub struct PersistedDocumentsHiveCircuitBreakerConfig {
    #[serde(default = "default_circuit_breaker_error_threshold")]
    pub error_threshold: f32,
    #[serde(default = "default_circuit_breaker_volume_threshold")]
    pub volume_threshold: usize,
    #[serde(
        default = "default_circuit_breaker_reset_timeout",
        deserialize_with = "humantime_serde::deserialize",
        serialize_with = "humantime_serde::serialize"
    )]
    #[schemars(with = "String")]
    pub reset_timeout: Duration,
}

impl Default for PersistedDocumentsHiveCircuitBreakerConfig {
    fn default() -> Self {
        Self {
            error_threshold: default_circuit_breaker_error_threshold(),
            volume_threshold: default_circuit_breaker_volume_threshold(),
            reset_timeout: default_circuit_breaker_reset_timeout(),
        }
    }
}

fn default_hive_accept_invalid_certs() -> bool {
    false
}

fn default_hive_connect_timeout() -> Duration {
    Duration::from_secs(5)
}

fn default_hive_request_timeout() -> Duration {
    Duration::from_secs(15)
}

fn default_hive_retry_policy() -> RetryPolicyConfig {
    RetryPolicyConfig { max_retries: 3 }
}

fn default_hive_cache_size() -> u64 {
    10_000
}

fn default_hive_negative_cache() -> ToggleWith<PersistedDocumentsHiveNegativeCacheConfig> {
    ToggleWith::Enabled(PersistedDocumentsHiveNegativeCacheConfig::default())
}

fn default_circuit_breaker_error_threshold() -> f32 {
    0.5
}

fn default_circuit_breaker_volume_threshold() -> usize {
    5
}

fn default_circuit_breaker_reset_timeout() -> Duration {
    Duration::from_secs(10)
}

const fn default_watch() -> bool {
    true
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, PartialEq, Eq, Hash)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PersistedDocumentExtractorConfig {
    JsonPath {
        path: PersistedDocumentJsonPath,
    },
    UrlPathParam {
        template: PersistedDocumentUrlTemplate,
    },
    UrlQueryParam {
        name: PersistedDocumentQueryParamName,
    },
}

#[derive(Debug, Serialize, JsonSchema, Clone, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct PersistedDocumentJsonPath(String);

impl PersistedDocumentJsonPath {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl<'de> Deserialize<'de> for PersistedDocumentJsonPath {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // TODO: add more validations (like " char etc)
        let path = String::deserialize(deserializer)?;
        if path.is_empty() {
            return Err(D::Error::custom("json_path cannot be empty"));
        }
        if path.chars().any(char::is_whitespace) {
            return Err(D::Error::custom("json_path cannot include whitespace"));
        }
        if path.contains('[') || path.contains(']') {
            return Err(D::Error::custom("json_path cannot include array syntax"));
        }
        if path.contains('*') {
            return Err(D::Error::custom("json_path cannot include wildcard syntax"));
        }
        if path.split('.').any(str::is_empty) {
            return Err(D::Error::custom(
                "json_path cannot include empty segments (e.g. '..')",
            ));
        }

        if matches!(
            path.split('.').next(),
            Some("query" | "operationName" | "variables")
        ) {
            return Err(D::Error::custom(
                "json_path cannot access root GraphQL fields: query, operationName, variables",
            ));
        }

        Ok(Self(path))
    }
}

#[derive(Debug, Serialize, JsonSchema, Clone, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct PersistedDocumentUrlTemplate(String);

impl PersistedDocumentUrlTemplate {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl<'de> Deserialize<'de> for PersistedDocumentUrlTemplate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let template = String::deserialize(deserializer)?;

        validate_url_path_template(&template).map_err(D::Error::custom)?;

        Ok(Self(template))
    }
}

fn validate_url_path_template(template: &str) -> Result<(), String> {
    if template.is_empty() {
        return Err("url_path_param.template cannot be empty".to_string());
    }
    if !template.starts_with('/') {
        return Err("url_path_param.template must start with '/'".to_string());
    }
    if template.contains('?') || template.contains('#') {
        return Err("url_path_param.template cannot include query string or fragment".to_string());
    }

    let raw_segments: Vec<&str> = template.split('/').skip(1).collect();
    if raw_segments.iter().any(|segment| segment.is_empty()) {
        return Err("url_path_param.template cannot include empty segments".to_string());
    }

    let mut id_count = 0;
    for (index, segment) in raw_segments.iter().enumerate() {
        match *segment {
            ":id" => id_count += 1,
            "*" => {}
            "**" => {
                return Err("url_path_param.template does not support '**' segments".to_string());
            }
            literal if literal.starts_with(':') => {
                return Err(format!(
                    "url_path_param.template has unsupported parameter segment '{literal}' at index {index}; only ':id' is allowed"
                ));
            }
            _ => {}
        }
    }

    if id_count != 1 {
        return Err("url_path_param.template must include exactly one ':id' segment".to_string());
    }

    Ok(())
}

#[derive(Debug, Serialize, JsonSchema, Clone, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct PersistedDocumentQueryParamName(String);

impl PersistedDocumentQueryParamName {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl<'de> Deserialize<'de> for PersistedDocumentQueryParamName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let name = String::deserialize(deserializer)?;
        // TODO: improve it
        if name.trim().is_empty() {
            return Err(D::Error::custom("url_query_param.name cannot be empty"));
        }
        Ok(Self(name))
    }
}

impl PersistedDocumentsConfig {
    pub fn default_selectors() -> Vec<PersistedDocumentExtractorConfig> {
        vec![
            PersistedDocumentExtractorConfig::JsonPath {
                path: PersistedDocumentJsonPath("documentId".to_string()),
            },
            PersistedDocumentExtractorConfig::JsonPath {
                path: PersistedDocumentJsonPath("extensions.persistedQuery.sha256Hash".to_string()),
            },
        ]
    }
}

#[cfg(test)]
mod tests {
    use super::{
        PersistedDocumentJsonPath, PersistedDocumentUrlTemplate, PersistedDocumentsConfig,
    };

    #[test]
    fn rejects_root_graphql_fields_for_json_path() {
        for path in ["query", "operationName", "variables", "query.foo"] {
            let raw = format!("\"{path}\"");
            let parsed = serde_json::from_str::<PersistedDocumentJsonPath>(&raw);
            assert!(parsed.is_err(), "expected path '{path}' to be rejected");
        }
    }

    #[test]
    fn allows_non_root_graphql_fields_for_json_path() {
        for path in [
            "documentId",
            "extensions.persistedQuery.sha256Hash",
            "foo.query",
        ] {
            let raw = format!("\"{path}\"");
            let parsed = serde_json::from_str::<PersistedDocumentJsonPath>(&raw);
            assert!(parsed.is_ok(), "expected path '{path}' to be allowed");
        }
    }

    #[test]
    fn enabled_persisted_documents_require_storage() {
        let parsed = serde_json::from_str::<PersistedDocumentsConfig>(
            r#"{
              "enabled": true
            }"#,
        );

        assert!(
            parsed.is_err(),
            "expected storage to be required when enabled"
        );
    }

    #[test]
    fn url_template_rejects_unknown_parameter_segment() {
        let parsed = serde_json::from_str::<PersistedDocumentUrlTemplate>(r#""/p/:docId""#);
        assert!(parsed.is_err(), "expected unknown parameter to be rejected");
    }

    #[test]
    fn url_template_accepts_supported_segment_types() {
        for template in ["/v1/p/:id", "/v1/*/:id", "/v1/*/:id/details"] {
            let raw = format!("\"{template}\"");
            let parsed = serde_json::from_str::<PersistedDocumentUrlTemplate>(&raw);
            assert!(parsed.is_ok(), "expected template '{template}' to be valid");
        }
    }

    #[test]
    fn url_template_rejects_globstar_segment() {
        for template in ["/v1/**/:id", "/:id/**/v2"] {
            let raw = format!("\"{template}\"");
            let parsed = serde_json::from_str::<PersistedDocumentUrlTemplate>(&raw);
            assert!(
                parsed.is_err(),
                "expected template '{template}' to be rejected"
            );
        }
    }
}