quelch 0.4.0

Ingest data from Jira, Confluence, and more directly into Azure AI Search
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
pub mod data;

use axum::{
    Router,
    extract::{Path as AxumPath, Query, State},
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Json},
    routing::{delete, get, post, put},
};
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};

const MOCK_TOKEN: &str = "mock-pat-token";

// -----------------------------------------------------------------------
// Shared server state (for Azure mock)
// -----------------------------------------------------------------------

/// Per-index storage: map of doc id → full doc object.
#[derive(Default)]
struct IndexStore {
    docs: HashMap<String, Value>,
}

#[derive(Default)]
struct AzureMockState {
    indexes: HashMap<String, IndexStore>,
    /// Remaining forced faults: each fault applies to the next single request.
    pending_faults: Vec<u16>,
}

type SharedState = Arc<Mutex<AzureMockState>>;

/// Returns Some(status) if a fault was consumed; None otherwise.
fn consume_fault(state: &SharedState) -> Option<u16> {
    let mut s = state.lock().unwrap();
    if s.pending_faults.is_empty() {
        None
    } else {
        Some(s.pending_faults.remove(0))
    }
}

// -----------------------------------------------------------------------
// Auth helper
// -----------------------------------------------------------------------

fn check_auth(headers: &HeaderMap) -> Result<(), (StatusCode, Json<Value>)> {
    let expected = format!("Bearer {MOCK_TOKEN}");
    match headers.get("authorization").and_then(|v| v.to_str().ok()) {
        Some(val) if val == expected => Ok(()),
        _ => Err((
            StatusCode::UNAUTHORIZED,
            Json(json!({
                "errorMessages": ["Authentication required. Use 'Authorization: Bearer mock-pat-token'"],
                "errors": {}
            })),
        )),
    }
}

// -----------------------------------------------------------------------
// Jira endpoint
// -----------------------------------------------------------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct JiraSearchParams {
    jql: Option<String>,
    start_at: Option<u64>,
    max_results: Option<u64>,
    #[serde(default)]
    #[allow(dead_code)]
    fields: Option<String>,
}

async fn jira_search(
    headers: HeaderMap,
    Query(params): Query<JiraSearchParams>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    check_auth(&headers)?;

    let all_issues = data::jira_issues();
    let jql = params.jql.unwrap_or_default();

    // Filter by project if JQL contains "project = X"
    let filtered: Vec<&Value> = all_issues
        .iter()
        .filter(|issue| {
            if jql.is_empty() {
                return true;
            }
            // Parse project filter
            if let Some(project) = extract_jql_project(&jql) {
                let issue_project = issue["fields"]["project"]["key"].as_str().unwrap_or("");
                if !project.eq_ignore_ascii_case(issue_project) {
                    return false;
                }
            }
            // Parse updated >= filter
            if let Some(updated_since) = extract_jql_updated(&jql) {
                let issue_updated = issue["fields"]["updated"].as_str().unwrap_or("");
                if issue_updated < updated_since.as_str() {
                    return false;
                }
            }
            true
        })
        .collect();

    let start_at = params.start_at.unwrap_or(0);
    let max_results = params.max_results.unwrap_or(50);
    let total = filtered.len() as u64;

    let page: Vec<Value> = filtered
        .into_iter()
        .skip(start_at as usize)
        .take(max_results as usize)
        .cloned()
        .collect();

    Ok(Json(json!({
        "expand": "schema,names",
        "startAt": start_at,
        "maxResults": max_results,
        "total": total,
        "issues": page
    })))
}

// -----------------------------------------------------------------------
// Confluence endpoint
// -----------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct ConfluenceSearchParams {
    cql: Option<String>,
    start: Option<u64>,
    limit: Option<u64>,
    #[serde(default)]
    #[allow(dead_code)]
    expand: Option<String>,
}

async fn confluence_search(
    headers: HeaderMap,
    Query(params): Query<ConfluenceSearchParams>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    check_auth(&headers)?;

    let all_pages = data::confluence_pages();
    let cql = params.cql.unwrap_or_default();

    let filtered: Vec<&Value> = all_pages
        .iter()
        .filter(|page| {
            if cql.is_empty() {
                return true;
            }
            // Parse space filter
            if let Some(space) = extract_cql_space(&cql) {
                let page_space = page["space"]["key"].as_str().unwrap_or("");
                if !space.eq_ignore_ascii_case(page_space) {
                    return false;
                }
            }
            // Parse lastmodified filter
            if let Some(since) = extract_cql_lastmodified(&cql) {
                let page_updated = page["version"]["when"].as_str().unwrap_or("");
                if page_updated < since.as_str() {
                    return false;
                }
            }
            true
        })
        .collect();

    let start = params.start.unwrap_or(0);
    let limit = params.limit.unwrap_or(25);
    let total = filtered.len() as u64;

    let page_slice: Vec<Value> = filtered
        .into_iter()
        .skip(start as usize)
        .take(limit as usize)
        .cloned()
        .collect();

    let has_more = (start + page_slice.len() as u64) < total;
    let mut links = json!({
        "base": format!("http://localhost:9999/confluence"),
        "context": "/confluence"
    });
    if has_more {
        links["next"] = json!(format!(
            "/rest/api/content/search?cql={}&start={}&limit={}",
            cql,
            start + limit,
            limit
        ));
    }

    Ok(Json(json!({
        "results": page_slice,
        "start": start,
        "limit": limit,
        "size": page_slice.len(),
        "_links": links
    })))
}

// -----------------------------------------------------------------------
// Azure AI Search mock handlers
// -----------------------------------------------------------------------

async fn azure_index_get(
    State(state): State<SharedState>,
    AxumPath(name): AxumPath<String>,
) -> impl IntoResponse {
    if let Some(status) = consume_fault(&state) {
        return (StatusCode::from_u16(status).unwrap(), Json(json!({}))).into_response();
    }
    let s = state.lock().unwrap();
    if s.indexes.contains_key(&name) {
        (StatusCode::OK, Json(json!({ "name": name }))).into_response()
    } else {
        (StatusCode::NOT_FOUND, Json(json!({ "error": "not found" }))).into_response()
    }
}

async fn azure_index_put(
    State(state): State<SharedState>,
    AxumPath(name): AxumPath<String>,
    Json(_body): Json<Value>,
) -> impl IntoResponse {
    if let Some(status) = consume_fault(&state) {
        return (StatusCode::from_u16(status).unwrap(), Json(json!({}))).into_response();
    }
    state
        .lock()
        .unwrap()
        .indexes
        .entry(name.clone())
        .or_default();
    (StatusCode::CREATED, Json(json!({ "name": name }))).into_response()
}

/// Azure's real `create_index` posts the schema (with `name` inside) to
/// `/indexes?api-version=...`. Honor that alongside the `PUT /{name}` we
/// already have.
async fn azure_indexes_collection_post(
    State(state): State<SharedState>,
    Json(body): Json<Value>,
) -> impl IntoResponse {
    if let Some(status) = consume_fault(&state) {
        return (StatusCode::from_u16(status).unwrap(), Json(json!({}))).into_response();
    }
    let name = match body.get("name").and_then(|v| v.as_str()) {
        Some(n) => n.to_string(),
        None => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": "missing 'name' field" })),
            )
                .into_response();
        }
    };
    state
        .lock()
        .unwrap()
        .indexes
        .entry(name.clone())
        .or_default();
    (StatusCode::CREATED, Json(json!({ "name": name }))).into_response()
}

async fn azure_index_delete(
    State(state): State<SharedState>,
    AxumPath(name): AxumPath<String>,
) -> impl IntoResponse {
    if let Some(status) = consume_fault(&state) {
        return (StatusCode::from_u16(status).unwrap(), Json(json!({}))).into_response();
    }
    state.lock().unwrap().indexes.remove(&name);
    StatusCode::NO_CONTENT.into_response()
}

#[derive(Debug, Deserialize)]
struct AzureBatch {
    value: Vec<Value>,
}

async fn azure_index_docs_post(
    State(state): State<SharedState>,
    AxumPath(name): AxumPath<String>,
    Json(batch): Json<AzureBatch>,
) -> impl IntoResponse {
    if let Some(status) = consume_fault(&state) {
        return (StatusCode::from_u16(status).unwrap(), Json(json!({}))).into_response();
    }
    let mut s = state.lock().unwrap();
    let store = s.indexes.entry(name).or_default();
    let mut results = Vec::new();
    for mut doc in batch.value {
        let action = doc
            .get("@search.action")
            .and_then(|v| v.as_str())
            .unwrap_or("mergeOrUpload")
            .to_string();
        let id = doc
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string();
        if let Some(obj) = doc.as_object_mut() {
            obj.remove("@search.action");
        }
        match action.as_str() {
            "delete" => {
                store.docs.remove(&id);
            }
            _ => {
                store.docs.insert(id.clone(), doc);
            }
        }
        results.push(json!({ "key": id, "status": true, "statusCode": 200 }));
    }
    (StatusCode::OK, Json(json!({ "value": results }))).into_response()
}

#[derive(Debug, Deserialize)]
struct AzureSearchBody {
    search: Option<String>,
}

async fn azure_index_search_post(
    State(state): State<SharedState>,
    AxumPath(name): AxumPath<String>,
    Json(body): Json<AzureSearchBody>,
) -> impl IntoResponse {
    if let Some(status) = consume_fault(&state) {
        return (StatusCode::from_u16(status).unwrap(), Json(json!({}))).into_response();
    }
    let s = state.lock().unwrap();
    let store = match s.indexes.get(&name) {
        Some(v) => v,
        None => {
            return (StatusCode::NOT_FOUND, Json(json!({ "error": "no index" }))).into_response();
        }
    };
    let q = body.search.unwrap_or_default().to_lowercase();
    let results: Vec<Value> = store
        .docs
        .values()
        .filter(|doc| {
            if q.is_empty() || q == "*" {
                return true;
            }
            doc.as_object()
                .map(|o| {
                    o.values().any(|v| {
                        v.as_str()
                            .map(|s| s.to_lowercase().contains(&q))
                            .unwrap_or(false)
                    })
                })
                .unwrap_or(false)
        })
        .cloned()
        .collect();
    (StatusCode::OK, Json(json!({ "value": results }))).into_response()
}

/// GET /azure/indexes/{name}/docs — ID-listing (used by SearchClient::fetch_all_ids).
async fn azure_index_docs_list(
    State(state): State<SharedState>,
    AxumPath(name): AxumPath<String>,
) -> impl IntoResponse {
    if let Some(status) = consume_fault(&state) {
        return (StatusCode::from_u16(status).unwrap(), Json(json!({}))).into_response();
    }
    let s = state.lock().unwrap();
    let store = match s.indexes.get(&name) {
        Some(v) => v,
        None => {
            return (StatusCode::NOT_FOUND, Json(json!({ "error": "no index" }))).into_response();
        }
    };
    let values: Vec<Value> = store.docs.keys().map(|id| json!({ "id": id })).collect();
    (StatusCode::OK, Json(json!({ "value": values }))).into_response()
}

#[derive(Debug, Deserialize)]
struct FaultSpec {
    count: usize,
    status: u16,
}

async fn azure_fault_post(
    State(state): State<SharedState>,
    Json(spec): Json<FaultSpec>,
) -> impl IntoResponse {
    let mut s = state.lock().unwrap();
    for _ in 0..spec.count {
        s.pending_faults.push(spec.status);
    }
    StatusCode::OK
}

// -----------------------------------------------------------------------
// Query parsing helpers
// -----------------------------------------------------------------------

/// Extract project name from JQL like "project = QUELCH ..."
fn extract_jql_project(jql: &str) -> Option<String> {
    let lower = jql.to_lowercase();
    let idx = lower.find("project")?;
    let rest = &jql[idx..];
    // Find the = sign
    let eq_idx = rest.find('=')?;
    let after_eq = rest[eq_idx + 1..].trim_start();
    // Take the first word (project key)
    let key: String = after_eq
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
        .collect();
    if key.is_empty() { None } else { Some(key) }
}

/// Extract updated >= timestamp from JQL like `updated >= "2026-03-15 14:30"`
fn extract_jql_updated(jql: &str) -> Option<String> {
    let lower = jql.to_lowercase();
    let idx = lower.find("updated")?;
    let rest = &jql[idx..];
    // Find >=
    let ge_idx = rest.find(">=")?;
    let after_ge = rest[ge_idx + 2..].trim_start();
    // Extract quoted value
    if let Some(stripped) = after_ge.strip_prefix('"') {
        let end = stripped.find('"')?;
        let ts = &stripped[..end];
        // Convert "2026-03-15 14:30" to comparable format "2026-03-15T14:30"
        Some(ts.replace(' ', "T"))
    } else {
        None
    }
}

/// Extract space name from CQL like `space = "QUELCH" ...`
fn extract_cql_space(cql: &str) -> Option<String> {
    let lower = cql.to_lowercase();
    let idx = lower.find("space")?;
    let rest = &cql[idx..];
    let eq_idx = rest.find('=')?;
    let after_eq = rest[eq_idx + 1..].trim_start();
    if let Some(stripped) = after_eq.strip_prefix('"') {
        let end = stripped.find('"')?;
        Some(stripped[..end].to_string())
    } else {
        let key: String = after_eq
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
            .collect();
        if key.is_empty() { None } else { Some(key) }
    }
}

/// Extract lastmodified >= timestamp from CQL
fn extract_cql_lastmodified(cql: &str) -> Option<String> {
    let lower = cql.to_lowercase();
    let idx = lower.find("lastmodified")?;
    let rest = &cql[idx..];
    let ge_idx = rest.find(">=")?;
    let after_ge = rest[ge_idx + 2..].trim_start();
    if let Some(stripped) = after_ge.strip_prefix('"') {
        let end = stripped.find('"')?;
        let ts = &stripped[..end];
        Some(ts.replace(' ', "T"))
    } else {
        None
    }
}

// -----------------------------------------------------------------------
// Router builder (testable, used by integration tests)
// -----------------------------------------------------------------------

/// Build the axum Router used by the mock server. `pub` so integration
/// tests outside this module can spin up an in-process instance.
pub fn build_router() -> Router {
    let state: SharedState = Arc::new(Mutex::new(AzureMockState::default()));

    Router::new()
        // Jira + Confluence routes:
        .route("/jira/rest/api/2/search", get(jira_search))
        .route(
            "/confluence/rest/api/content/search",
            get(confluence_search),
        )
        // Azure routes (all share the same state):
        .route("/azure/indexes", post(azure_indexes_collection_post))
        .route("/azure/indexes/{name}", get(azure_index_get))
        .route("/azure/indexes/{name}", put(azure_index_put))
        .route("/azure/indexes/{name}", delete(azure_index_delete))
        .route(
            "/azure/indexes/{name}/docs/index",
            post(azure_index_docs_post),
        )
        .route(
            "/azure/indexes/{name}/docs/search",
            post(azure_index_search_post),
        )
        .route("/azure/indexes/{name}/docs", get(azure_index_docs_list))
        .route("/azure/_fault", post(azure_fault_post))
        .with_state(state)
}

// -----------------------------------------------------------------------
// Server entry point
// -----------------------------------------------------------------------

/// Start the mock Jira DC + Confluence DC server.
pub async fn run_mock_server(port: u16) -> anyhow::Result<()> {
    let app = build_router();
    let addr = SocketAddr::from(([127, 0, 0, 1], port));

    println!("Mock Jira DC server running at http://localhost:{port}/jira");
    println!("Mock Confluence DC server running at http://localhost:{port}/confluence");
    println!();
    println!("Auth token: {MOCK_TOKEN}");
    println!("Jira projects: QUELCH (17 issues), DEMO (2 issues)");
    println!("Confluence spaces: QUELCH (8 pages), INFRA (2 pages)");
    println!();
    println!("Example quelch.yaml config:");
    println!();
    println!("  azure:");
    println!("    endpoint: \"https://your-search.search.windows.net\"");
    println!("    api_key: \"${{AZURE_SEARCH_API_KEY}}\"");
    println!();
    println!("  sources:");
    println!("    - type: jira");
    println!("      name: \"mock-jira\"");
    println!("      url: \"http://localhost:{port}/jira\"");
    println!("      auth:");
    println!("        pat: \"{MOCK_TOKEN}\"");
    println!("      projects:");
    println!("        - \"QUELCH\"");
    println!("        - \"DEMO\"");
    println!("      index: \"jira-issues\"");
    println!();
    println!("    - type: confluence");
    println!("      name: \"mock-confluence\"");
    println!("      url: \"http://localhost:{port}/confluence\"");
    println!("      auth:");
    println!("        pat: \"{MOCK_TOKEN}\"");
    println!("      spaces:");
    println!("        - \"QUELCH\"");
    println!("        - \"INFRA\"");
    println!("      index: \"confluence-pages\"");
    println!();
    println!("Press Ctrl+C to stop.");

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::SocketAddr;

    async fn spawn_test_server() -> String {
        let listener = tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
            .await
            .unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, build_router()).await.unwrap();
        });
        format!("http://{}", addr)
    }

    #[tokio::test]
    async fn azure_index_create_get_delete_roundtrip() {
        let base = spawn_test_server().await;
        let client = reqwest::Client::new();

        let put = client
            .put(format!(
                "{}/azure/indexes/test-idx?api-version=2024-07-01",
                base
            ))
            .header("api-key", "ignored-by-mock")
            .json(&serde_json::json!({ "name": "test-idx", "fields": [] }))
            .send()
            .await
            .unwrap();
        assert!(put.status().is_success(), "PUT failed: {}", put.status());

        let get = client
            .get(format!(
                "{}/azure/indexes/test-idx?api-version=2024-07-01",
                base
            ))
            .send()
            .await
            .unwrap();
        assert!(get.status().is_success());

        let del = client
            .delete(format!(
                "{}/azure/indexes/test-idx?api-version=2024-07-01",
                base
            ))
            .send()
            .await
            .unwrap();
        assert!(del.status().is_success());

        let after = client
            .get(format!(
                "{}/azure/indexes/test-idx?api-version=2024-07-01",
                base
            ))
            .send()
            .await
            .unwrap();
        assert_eq!(after.status().as_u16(), 404);
    }

    #[tokio::test]
    async fn azure_push_and_search_documents() {
        let base = spawn_test_server().await;
        let client = reqwest::Client::new();

        client
            .put(format!(
                "{}/azure/indexes/docs?api-version=2024-07-01",
                base
            ))
            .json(&serde_json::json!({ "name": "docs", "fields": [] }))
            .send()
            .await
            .unwrap();

        let body = serde_json::json!({
            "value": [
                { "@search.action": "mergeOrUpload", "id": "a", "content": "hello world" },
                { "@search.action": "mergeOrUpload", "id": "b", "content": "quelch rocks" },
            ]
        });
        let push = client
            .post(format!(
                "{}/azure/indexes/docs/docs/index?api-version=2024-07-01",
                base
            ))
            .json(&body)
            .send()
            .await
            .unwrap();
        assert!(push.status().is_success());

        let search = client
            .post(format!(
                "{}/azure/indexes/docs/docs/search?api-version=2024-07-01",
                base
            ))
            .json(&serde_json::json!({ "search": "hello" }))
            .send()
            .await
            .unwrap();
        let body: serde_json::Value = search.json().await.unwrap();
        let values = body.get("value").and_then(|v| v.as_array()).unwrap();
        assert_eq!(values.len(), 1);
        assert_eq!(values[0].get("id").unwrap(), "a");
    }

    #[tokio::test]
    async fn azure_fault_injection_next_n_calls() {
        let base = spawn_test_server().await;
        let client = reqwest::Client::new();

        client
            .post(format!("{}/azure/_fault", base))
            .json(&serde_json::json!({ "count": 2, "status": 429 }))
            .send()
            .await
            .unwrap();

        let r1 = client
            .get(format!("{}/azure/indexes/x?api-version=2024-07-01", base))
            .send()
            .await
            .unwrap();
        assert_eq!(r1.status().as_u16(), 429);

        let r2 = client
            .get(format!("{}/azure/indexes/x?api-version=2024-07-01", base))
            .send()
            .await
            .unwrap();
        assert_eq!(r2.status().as_u16(), 429);

        let r3 = client
            .get(format!("{}/azure/indexes/x?api-version=2024-07-01", base))
            .send()
            .await
            .unwrap();
        assert_eq!(r3.status().as_u16(), 404);
    }

    #[tokio::test]
    async fn azure_post_indexes_collection_creates_from_body() {
        let base = spawn_test_server().await;
        let client = reqwest::Client::new();

        let resp = client
            .post(format!("{}/azure/indexes?api-version=2024-07-01", base))
            .json(&serde_json::json!({ "name": "coll-idx", "fields": [] }))
            .send()
            .await
            .unwrap();
        assert!(resp.status().is_success());

        let get = client
            .get(format!(
                "{}/azure/indexes/coll-idx?api-version=2024-07-01",
                base
            ))
            .send()
            .await
            .unwrap();
        assert!(get.status().is_success());
    }

    #[tokio::test]
    async fn jira_data_has_two_projects() {
        let base = spawn_test_server().await;
        let client = reqwest::Client::new();

        let quelch_resp = client
            .get(format!("{}/jira/rest/api/2/search", base))
            .header("authorization", format!("Bearer {}", MOCK_TOKEN))
            .query(&[("jql", "project = QUELCH"), ("maxResults", "100")])
            .send()
            .await
            .unwrap();
        let q: serde_json::Value = quelch_resp.json().await.unwrap();
        assert!(q.get("total").unwrap().as_u64().unwrap() > 0);

        let demo_resp = client
            .get(format!("{}/jira/rest/api/2/search", base))
            .header("authorization", format!("Bearer {}", MOCK_TOKEN))
            .query(&[("jql", "project = DEMO"), ("maxResults", "100")])
            .send()
            .await
            .unwrap();
        let d: serde_json::Value = demo_resp.json().await.unwrap();
        assert!(
            d.get("total").unwrap().as_u64().unwrap() > 0,
            "DEMO project should exist"
        );
    }

    #[tokio::test]
    async fn confluence_data_has_two_spaces() {
        let base = spawn_test_server().await;
        let client = reqwest::Client::new();

        let quelch = client
            .get(format!("{}/confluence/rest/api/content/search", base))
            .header("authorization", format!("Bearer {}", MOCK_TOKEN))
            .query(&[("cql", "space = QUELCH")])
            .send()
            .await
            .unwrap();
        let q: serde_json::Value = quelch.json().await.unwrap();
        assert!(q.get("size").unwrap().as_u64().unwrap() > 0);

        let infra = client
            .get(format!("{}/confluence/rest/api/content/search", base))
            .header("authorization", format!("Bearer {}", MOCK_TOKEN))
            .query(&[("cql", "space = INFRA")])
            .send()
            .await
            .unwrap();
        let i: serde_json::Value = infra.json().await.unwrap();
        assert!(
            i.get("size").unwrap().as_u64().unwrap() > 0,
            "INFRA space should exist"
        );
    }
}