faucet-source-xml 1.2.3

XML 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
//! Integration tests for `XmlStream`'s HTTP fetch path against a wiremock
//! server: auth header application, pagination (page-number / offset),
//! `max_pages` capping, the identical-page loop guard, SOAP POST bodies,
//! and error paths (non-2xx status, malformed XML).

use faucet_core::FaucetError;
use faucet_source_xml::{XmlAuth, XmlPagination, XmlStream, XmlStreamConfig};
use reqwest::Method;
use std::collections::HashMap;
use wiremock::matchers::{body_string_contains, header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// `<root><item><id>i</id></item>...</root>` with `n` items.
fn items_doc(start: usize, n: usize) -> String {
    let mut s = String::from("<root>");
    for i in start..start + n {
        s.push_str(&format!("<item><id>{i}</id></item>"));
    }
    s.push_str("</root>");
    s
}

#[tokio::test]
async fn basic_auth_header_is_sent() {
    let server = MockServer::start().await;
    // Basic dXNlcjpwYXNz == base64("user:pass").
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(header("authorization", "Basic dXNlcjpwYXNz"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(0, 2)),
        )
        .expect(1)
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .auth(XmlAuth::Basic {
            username: "user".into(),
            password: "pass".into(),
        });
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 2);
    assert_eq!(records[0]["id"], "0");
}

#[tokio::test]
async fn custom_auth_headers_are_sent() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/soap"))
        .and(header("soapaction", "urn:GetUsers"))
        .and(header("x-api-key", "secret-key"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "text/xml")
                .set_body_string(items_doc(0, 1)),
        )
        .expect(1)
        .mount(&server)
        .await;

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

    let config = XmlStreamConfig::new(server.uri(), "/soap")
        .method(Method::POST)
        .records_element_path("root.item")
        .auth(XmlAuth::Custom { headers });
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 1);
}

#[tokio::test]
async fn custom_auth_invalid_header_name_errors() {
    // An illegal HTTP header name must surface as FaucetError::Auth before
    // any request is sent.
    let server = MockServer::start().await;
    let mut headers = HashMap::new();
    headers.insert("Invalid Header Name".to_string(), "v".to_string());
    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .auth(XmlAuth::Custom { headers });
    let err = XmlStream::new(config).fetch_all().await.unwrap_err();
    assert!(matches!(err, FaucetError::Auth(_)), "got {err:?}");
}

#[tokio::test]
async fn soap_post_body_is_sent_and_response_extracted() {
    let server = MockServer::start().await;
    let soap_response = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
            <GetUsersResponse>
                <User><Name>Alice</Name></User>
                <User><Name>Bob</Name></User>
            </GetUsersResponse>
        </soap:Body>
    </soap:Envelope>"#;
    Mock::given(method("POST"))
        .and(path("/soap"))
        .and(body_string_contains("GetUsers"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "text/xml")
                .set_body_string(soap_response),
        )
        .expect(1)
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/soap")
        .method(Method::POST)
        .body("<soap:Envelope><soap:Body><GetUsers/></soap:Body></soap:Envelope>")
        .records_element_path("soap:Envelope.soap:Body.GetUsersResponse.User");
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 2);
    assert_eq!(records[0]["Name"], "Alice");
    assert_eq!(records[1]["Name"], "Bob");
}

#[tokio::test]
async fn query_params_are_sent() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("format", "xml"))
        .and(query_param("v", "2"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(0, 1)),
        )
        .expect(1)
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .query_param("format", "xml")
        .query_param("v", "2");
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 1);
}

#[tokio::test]
async fn page_number_pagination_walks_pages_until_empty() {
    let server = MockServer::start().await;
    // page=1 -> 2 items, page=2 -> 2 items, page=3 -> empty (stops).
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("page", "1"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(0, 2)),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("page", "2"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(2, 2)),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("page", "3"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string("<root></root>"),
        )
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .pagination(XmlPagination::PageNumber {
            param_name: "page".into(),
            start_page: 1,
            page_size: None,
            page_size_param: None,
        });
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 4);
    assert_eq!(records[0]["id"], "0");
    assert_eq!(records[3]["id"], "3");
}

#[tokio::test]
async fn page_number_pagination_stops_on_short_page() {
    let server = MockServer::start().await;
    // page_size=3: first page full (3), second page short (1) -> stop.
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("page", "1"))
        .and(query_param("size", "3"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(0, 3)),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("page", "2"))
        .and(query_param("size", "3"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(3, 1)),
        )
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .pagination(XmlPagination::PageNumber {
            param_name: "page".into(),
            start_page: 1,
            page_size: Some(3),
            page_size_param: Some("size".into()),
        });
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 4, "3 full + 1 short page, then stop");
}

#[tokio::test]
async fn offset_pagination_walks_until_short_page() {
    let server = MockServer::start().await;
    // limit=2: offset 0 -> 2, offset 2 -> 2, offset 4 -> 1 (short) -> stop.
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("offset", "0"))
        .and(query_param("limit", "2"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(0, 2)),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("offset", "2"))
        .and(query_param("limit", "2"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(2, 2)),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("offset", "4"))
        .and(query_param("limit", "2"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(4, 1)),
        )
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .pagination(XmlPagination::Offset {
            offset_param: "offset".into(),
            limit_param: "limit".into(),
            limit: 2,
        });
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 5);
    assert_eq!(records[4]["id"], "4");
}

#[tokio::test]
async fn max_pages_caps_fetch() {
    let server = MockServer::start().await;
    // Every page is full (2 items), but max_pages=2 caps it at 4 records.
    // Use distinct page bodies so the loop guard does not trip first.
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("page", "1"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(0, 2)),
        )
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .and(query_param("page", "2"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(2, 2)),
        )
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .max_pages(2)
        .pagination(XmlPagination::PageNumber {
            param_name: "page".into(),
            start_page: 1,
            page_size: None,
            page_size_param: None,
        });
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 4, "max_pages=2 -> at most 4 records");
}

#[tokio::test]
async fn identical_page_loop_guard_stops_fetch() {
    // A server that ignores the page param and returns the same non-empty
    // body forever must stop after two identical pages (audit #146 H4/H5).
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string(items_doc(0, 2)),
        )
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml")
        .records_element_path("root.item")
        .pagination(XmlPagination::PageNumber {
            param_name: "page".into(),
            start_page: 1,
            page_size: None,
            page_size_param: None,
        });
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    // #321 M4: only page 1 is emitted (2 records). The identical page 2 trips
    // the stagnation guard and is DROPPED rather than emitted a second time
    // (previously it leaked 4 records = the duplicate page appended).
    assert_eq!(records.len(), 2);
}

#[tokio::test]
async fn non_2xx_status_returns_error() {
    // A persistent 404 is non-retriable and must surface as an error.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .respond_with(ResponseTemplate::new(404).set_body_string("not found"))
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml").records_element_path("root.item");
    let err = XmlStream::new(config).fetch_all().await.unwrap_err();
    assert!(
        matches!(err, FaucetError::HttpStatus { status, .. } if status == 404),
        "got {err:?}"
    );
}

#[tokio::test]
async fn malformed_xml_response_returns_transform_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string("<root><a></b></root>"),
        )
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml").records_element_path("root.a");
    let err = XmlStream::new(config).fetch_all().await.unwrap_err();
    assert!(
        matches!(&err, FaucetError::Transform(m) if m.contains("XML parse error")),
        "got {err:?}"
    );
}

#[tokio::test]
async fn no_records_path_returns_whole_document() {
    // With records_element_path = None, fetch_all returns the full doc as a
    // single record.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/feed.xml"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/xml")
                .set_body_string("<root><name>Z</name></root>"),
        )
        .mount(&server)
        .await;

    let config = XmlStreamConfig::new(server.uri(), "/feed.xml");
    let records = XmlStream::new(config).fetch_all().await.unwrap();
    assert_eq!(records.len(), 1);
    assert_eq!(records[0]["root"]["name"], "Z");
}