faucet-source-graphql 1.2.3

GraphQL API source connector for the faucet-stream ecosystem
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
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
//! Additional coverage tests for `GraphqlStream` driven against a wiremock
//! GraphQL endpoint (no live services).
//!
//! These exercise paths the existing `streaming.rs` / `shared_auth_test.rs`
//! suites leave uncovered:
//!   * the buffered `fetch_all` / `fetch_with_context` pagination loop
//!     (multi-page walk via `pageInfo.hasNextPage` / `endCursor`, the
//!     `!has_next` and missing-cursor terminators, and the `max_pages` cap);
//!   * parent-context variable injection into the GraphQL request body;
//!   * the JSONPath records-extraction path;
//!   * `Custom` header auth application;
//!   * the `credential_to_auth` mapping for every shared-provider `Credential`
//!     variant (Token / Header / Basic);
//!   * GraphQL `errors` arrays in a 200 body surfaced as
//!     `FaucetError::HttpStatus`;
//!   * non-2xx HTTP surfaced as the expected `FaucetError`.

use std::collections::HashMap;
use std::sync::Arc;

use faucet_core::{AuthProvider, Credential, FaucetError, Source};
use faucet_source_graphql::config::{GraphqlAuth, GraphqlPagination};
use faucet_source_graphql::{GraphqlStream, GraphqlStreamConfig};
use serde_json::{Value, json};
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};

/// Parse a wiremock request body as JSON and return the `variables` object.
fn request_variables(req: &Request) -> Value {
    let body: Value = serde_json::from_slice(&req.body).expect("request body is JSON");
    body.get("variables").cloned().unwrap_or(Value::Null)
}

/// Read the `after` cursor variable from a GraphQL request body.
fn request_cursor(req: &Request) -> Option<String> {
    request_variables(req)
        .get("after")
        .and_then(|v| v.as_str().map(|s| s.to_string()))
}

/// Relay-style page payload with records `start..start+n` under
/// `data.users.edges[*].node`, advertising `next_cursor` when present.
fn make_page(start: u64, n: u64, next_cursor: Option<&str>) -> Value {
    let edges: Vec<Value> = (start..start + n)
        .map(|i| json!({ "node": { "id": i } }))
        .collect();
    json!({
        "data": {
            "users": {
                "edges": edges,
                "pageInfo": {
                    "hasNextPage": next_cursor.is_some(),
                    "endCursor": next_cursor,
                }
            }
        }
    })
}

/// Mount a two-page Relay endpoint: cursor `None` → page 0 (next `"c1"`),
/// cursor `"c1"` → page 1 (final, `hasNextPage: false`).
async fn mount_two_pages(server: &MockServer) {
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .respond_with(move |req: &Request| match request_cursor(req).as_deref() {
            None => ResponseTemplate::new(200).set_body_json(make_page(0, 2, Some("c1"))),
            Some("c1") => ResponseTemplate::new(200).set_body_json(make_page(2, 2, None)),
            other => panic!("unexpected cursor {other:?}"),
        })
        .mount(server)
        .await;
}

fn relay_config(server: &MockServer) -> GraphqlStreamConfig {
    GraphqlStreamConfig::new(
        format!("{}/graphql", server.uri()),
        "query($first: Int, $after: String) { users(first: $first, after: $after) { \
         edges { node { id } } pageInfo { hasNextPage endCursor } } }",
    )
    .records_path("$.data.users.edges[*].node")
    .pagination(GraphqlPagination {
        has_next_page_path: "$.data.users.pageInfo.hasNextPage".into(),
        cursor_path: "$.data.users.pageInfo.endCursor".into(),
        cursor_variable: "after".into(),
        page_size_variable: "first".into(),
    })
    .with_batch_size(2)
}

/// `fetch_all` must walk every page until `hasNextPage: false`, advancing the
/// `after` cursor with `endCursor`, and concatenate the extracted records.
#[tokio::test(flavor = "multi_thread")]
async fn fetch_all_walks_cursor_pages_until_has_next_page_false() {
    let server = MockServer::start().await;
    mount_two_pages(&server).await;

    let source = GraphqlStream::new(relay_config(&server));
    let records = source.fetch_all().await.expect("fetch_all ok");

    let ids: Vec<u64> = records
        .iter()
        .map(|r| r["id"].as_u64().expect("id is a number"))
        .collect();
    assert_eq!(
        ids,
        vec![0, 1, 2, 3],
        "both pages must be walked and concatenated in order"
    );

    // Exactly two requests: page 0 (after=None) then page 1 (after=c1).
    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 2, "exactly two upstream pages fetched");
    assert_eq!(request_cursor(&requests[0]), None);
    assert_eq!(request_cursor(&requests[1]), Some("c1".to_string()));
    // The page-size variable carries `batch_size`.
    assert_eq!(request_variables(&requests[0])["first"].as_u64(), Some(2));
}

/// `max_pages` caps the buffered `fetch_all` walk at the configured number of
/// upstream pages even when more pages are available.
#[tokio::test(flavor = "multi_thread")]
async fn fetch_all_respects_max_pages_cap() {
    let server = MockServer::start().await;
    mount_two_pages(&server).await;

    let source = GraphqlStream::new(relay_config(&server).max_pages(1));
    let records = source.fetch_all().await.expect("fetch_all ok");

    let ids: Vec<u64> = records.iter().map(|r| r["id"].as_u64().unwrap()).collect();
    assert_eq!(ids, vec![0, 1], "max_pages=1 stops after the first page");

    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1, "max_pages=1 issues exactly one request");
}

/// `fetch_all` stops when the server reports `hasNextPage: false` even on the
/// very first page (single-page result set).
#[tokio::test(flavor = "multi_thread")]
async fn fetch_all_single_page_stops_immediately() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .respond_with(ResponseTemplate::new(200).set_body_json(make_page(0, 3, None)))
        .mount(&server)
        .await;

    let source = GraphqlStream::new(relay_config(&server));
    let records = source.fetch_all().await.expect("fetch_all ok");
    assert_eq!(records.len(), 3);

    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1, "a single non-next page ends pagination");
}

/// `fetch_all` stops when the server claims `hasNextPage: true` but provides no
/// `endCursor` — advancing is impossible, so the walk terminates without
/// re-fetching (the missing-cursor terminator).
#[tokio::test(flavor = "multi_thread")]
async fn fetch_all_stops_when_next_cursor_is_absent() {
    let server = MockServer::start().await;
    // hasNextPage=true but endCursor=null.
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "users": {
                    "edges": [{ "node": { "id": 0 } }],
                    "pageInfo": { "hasNextPage": true, "endCursor": null }
                }
            }
        })))
        .mount(&server)
        .await;

    let source = GraphqlStream::new(relay_config(&server));
    let records = source.fetch_all().await.expect("fetch_all ok");
    assert_eq!(records.len(), 1);

    let requests = server.received_requests().await.unwrap();
    assert_eq!(
        requests.len(),
        1,
        "a null endCursor must stop the walk after one request"
    );
}

/// Parent context values are merged into the GraphQL request `variables` via
/// `fetch_with_context`, alongside the injected cursor / page-size variables.
#[tokio::test(flavor = "multi_thread")]
async fn fetch_with_context_injects_parent_variables() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .respond_with(move |req: &Request| {
            let vars = request_variables(req);
            // Parent context value merged into variables verbatim.
            assert_eq!(vars["org"], json!("acme"), "parent context var injected");
            assert_eq!(vars["region"], json!("us-east-1"));
            ResponseTemplate::new(200).set_body_json(make_page(0, 1, None))
        })
        .mount(&server)
        .await;

    let source = GraphqlStream::new(relay_config(&server));
    let mut ctx: HashMap<String, Value> = HashMap::new();
    ctx.insert("org".to_string(), json!("acme"));
    ctx.insert("region".to_string(), json!("us-east-1"));

    let records = source.fetch_with_context(&ctx).await.expect("fetch ok");
    assert_eq!(records.len(), 1);

    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1);
}

/// `Custom` header auth applies each configured header to the request.
#[tokio::test(flavor = "multi_thread")]
async fn custom_header_auth_is_applied() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .and(header("x-api-key", "secret-key"))
        .and(header("x-tenant", "acme"))
        .respond_with(ResponseTemplate::new(200).set_body_json(make_page(0, 1, None)))
        .mount(&server)
        .await;

    let mut headers = HashMap::new();
    headers.insert("X-API-Key".to_string(), "secret-key".to_string());
    headers.insert("X-Tenant".to_string(), "acme".to_string());

    let config = GraphqlStreamConfig::new(
        format!("{}/graphql", server.uri()),
        "query { users { edges { node { id } } } }",
    )
    .records_path("$.data.users.edges[*].node")
    .auth(GraphqlAuth::Custom { headers });

    let source = GraphqlStream::new(config);
    let records = source.fetch_all().await.expect("custom-auth fetch ok");
    assert_eq!(
        records.len(),
        1,
        "request matched only with both custom headers"
    );
}

/// A `Custom` header with an invalid header *name* surfaces as
/// `FaucetError::Auth` rather than silently sending an unauthenticated request.
#[tokio::test(flavor = "multi_thread")]
async fn custom_header_auth_invalid_name_errors() {
    let server = MockServer::start().await;
    // No mock mounted — request must never be sent.

    let mut headers = HashMap::new();
    // A space is not a legal HTTP header-name character.
    headers.insert("Bad Header".to_string(), "value".to_string());

    let config = GraphqlStreamConfig::new(
        format!("{}/graphql", server.uri()),
        "query { users { edges { node { id } } } }",
    )
    .records_path("$.data.users.edges[*].node")
    .auth(GraphqlAuth::Custom { headers });

    let source = GraphqlStream::new(config);
    let err = source
        .fetch_all()
        .await
        .expect_err("invalid header name must error");
    assert!(matches!(err, FaucetError::Auth(_)), "got {err:?}");

    let requests = server.received_requests().await.unwrap();
    assert!(
        requests.is_empty(),
        "no request leaks on invalid header name"
    );
}

// ─── credential_to_auth mapping for every shared-provider variant ────────────

/// A provider returning an arbitrary [`Credential`] for `credential_to_auth`.
#[derive(Debug)]
struct FixedCredential(Credential);

#[async_trait::async_trait]
impl AuthProvider for FixedCredential {
    async fn credential(&self) -> Result<Credential, FaucetError> {
        Ok(self.0.clone())
    }
    fn provider_name(&self) -> &'static str {
        "fixed-credential"
    }
}

async fn run_with_provider_expecting_header(
    cred: Credential,
    header_name: &str,
    header_value: &str,
) {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .and(header(header_name, header_value))
        .respond_with(ResponseTemplate::new(200).set_body_json(make_page(0, 1, None)))
        .mount(&server)
        .await;

    let provider = Arc::new(FixedCredential(cred));
    let source = GraphqlStream::new(
        GraphqlStreamConfig::new(
            format!("{}/graphql", server.uri()),
            "query { users { edges { node { id } } } }",
        )
        .records_path("$.data.users.edges[*].node"),
    )
    .with_auth_provider(provider);

    let records = source.fetch_all().await.expect("provider-auth fetch ok");
    assert_eq!(
        records.len(),
        1,
        "request matched only with the expected auth header"
    );
}

/// `Credential::Token` maps to a raw `Authorization` header value.
#[tokio::test(flavor = "multi_thread")]
async fn provider_token_credential_sets_authorization_header() {
    run_with_provider_expecting_header(
        Credential::Token("raw-token-123".to_string()),
        "authorization",
        "raw-token-123",
    )
    .await;
}

/// `Credential::Header` maps to a custom header with the given name/value.
#[tokio::test(flavor = "multi_thread")]
async fn provider_header_credential_sets_named_header() {
    run_with_provider_expecting_header(
        Credential::Header {
            name: "X-Api-Token".to_string(),
            value: "hv-456".to_string(),
        },
        "x-api-token",
        "hv-456",
    )
    .await;
}

/// `Credential::Basic` maps to a base64-encoded `Authorization: Basic` header.
#[tokio::test(flavor = "multi_thread")]
async fn provider_basic_credential_sets_basic_authorization_header() {
    // base64("alice:s3cr3t") == "YWxpY2U6czNjcjN0"
    run_with_provider_expecting_header(
        Credential::Basic {
            username: "alice".to_string(),
            password: "s3cr3t".to_string(),
        },
        "authorization",
        "Basic YWxpY2U6czNjcjN0",
    )
    .await;
}

// ─── error surfacing ─────────────────────────────────────────────────────────

/// A GraphQL `errors` array in a 200 body is surfaced as
/// `FaucetError::HttpStatus { status: 200, .. }` with the joined messages.
#[tokio::test(flavor = "multi_thread")]
async fn graphql_errors_array_surfaces_as_http_status_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": null,
            "errors": [
                { "message": "Field 'bogus' doesn't exist" },
                { "message": "Cannot query nonsense" }
            ]
        })))
        .mount(&server)
        .await;

    let config = GraphqlStreamConfig::new(
        format!("{}/graphql", server.uri()),
        "query { users { edges { node { id } } } }",
    )
    .records_path("$.data.users.edges[*].node");
    let source = GraphqlStream::new(config);

    let err = source
        .fetch_all()
        .await
        .expect_err("errors array must fail the fetch");
    match err {
        FaucetError::HttpStatus { status, body, .. } => {
            assert_eq!(status, 200, "GraphQL errors arrive in a 200 response");
            assert!(
                body.contains("Field 'bogus' doesn't exist")
                    && body.contains("Cannot query nonsense"),
                "all error messages must be joined into the body; got {body:?}"
            );
        }
        other => panic!("expected HttpStatus, got {other:?}"),
    }
}

/// A non-2xx HTTP status (non-retriable 4xx) surfaces as
/// `FaucetError::HttpStatus` carrying that status code.
#[tokio::test(flavor = "multi_thread")]
async fn non_2xx_http_status_surfaces_as_http_status_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/graphql"))
        .respond_with(ResponseTemplate::new(404).set_body_string("not found"))
        .mount(&server)
        .await;

    let config = GraphqlStreamConfig::new(
        format!("{}/graphql", server.uri()),
        "query { users { edges { node { id } } } }",
    )
    .records_path("$.data.users.edges[*].node");
    let source = GraphqlStream::new(config);

    let err = source
        .fetch_all()
        .await
        .expect_err("404 must fail the fetch");
    match err {
        FaucetError::HttpStatus { status, .. } => {
            assert_eq!(status, 404, "the upstream 404 status must be surfaced");
        }
        other => panic!("expected HttpStatus(404), got {other:?}"),
    }
}

// ─── config schema introspection ─────────────────────────────────────────────

/// `config_schema()` returns a JSON object describing `GraphqlStreamConfig`.
#[tokio::test(flavor = "multi_thread")]
async fn config_schema_describes_the_config_struct() {
    let source = GraphqlStream::new(GraphqlStreamConfig::new(
        "https://api.example.com/graphql",
        "query { id }",
    ));
    let schema = source.config_schema();
    let props = schema
        .get("properties")
        .and_then(|p| p.as_object())
        .expect("schema has a properties object");
    assert!(
        props.contains_key("endpoint"),
        "schema documents `endpoint`"
    );
    assert!(props.contains_key("query"), "schema documents `query`");
    assert!(
        props.contains_key("pagination"),
        "schema documents `pagination`"
    );
}