refget-server 0.1.0

Axum-based GA4GH refget Sequences v2.0.0 and Sequence Collections v1.0.0 server
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! Handlers for the refget Sequences v2.0.0 API.

use axum::Router;
use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Deserialize;

use super::json_error;
use crate::RefgetState;

/// GA4GH refget v2 content type for JSON responses.
const REFGET_JSON_CONTENT_TYPE: &str = "application/vnd.ga4gh.refget.v2.0.0+json";

/// GA4GH refget v2 content type for sequence (plain text) responses.
const REFGET_PLAIN_CONTENT_TYPE: &str = "text/vnd.ga4gh.refget.v2.0.0+plain";

/// Acceptable fallback media types for JSON endpoints (includes v1 for compliance suite compat).
const JSON_FALLBACKS: &[&str] = &["application/json", "application/vnd.ga4gh.refget.v1.0.0+json"];

/// Acceptable fallback media types for plain text endpoints (includes v1 for compliance suite compat).
const PLAIN_FALLBACKS: &[&str] = &["text/plain", "text/vnd.ga4gh.refget.v1.0.0+plain"];

pub fn router(state: RefgetState) -> Router {
    Router::new()
        .route("/sequence/service-info", get(service_info))
        .route("/sequence/{digest}", get(get_sequence))
        .route("/sequence/{digest}/metadata", get(get_metadata))
        .with_state(state)
}

/// Check the Accept header and return 406 if the client doesn't accept the
/// given content type or any of the provided fallbacks.
fn check_accept(headers: &HeaderMap, content_type: &str, fallbacks: &[&str]) -> Option<Response> {
    let accept = headers.get("accept")?;
    let accept_str = accept.to_str().ok()?;
    for media_type in accept_str.split(',') {
        let media_type = media_type.split(';').next().unwrap_or("").trim();
        if media_type == "*/*" || media_type == content_type || fallbacks.contains(&media_type) {
            return None;
        }
    }
    Some(json_error(StatusCode::NOT_ACCEPTABLE, "Not Acceptable"))
}

/// Normalize a digest identifier for store lookup.
///
/// Produces candidates in priority order:
/// 1. Raw identifier as-is
/// 2. Strip `SQ.` prefix (ga4gh without prefix)
/// 3. Strip `ga4gh:` namespace prefix
/// 4. Strip `md5:` namespace prefix
/// 5. Convert trunc512 (48-char hex) to sha512t24u (base64url)
/// 6. Case-fold to lowercase (for case-insensitive MD5 hex)
fn normalize_candidates(digest: &str) -> Vec<String> {
    let mut candidates = vec![digest.to_string()];

    // Strip SQ. prefix
    if let Some(stripped) = digest.strip_prefix("SQ.") {
        candidates.push(stripped.to_string());
    }

    // Strip ga4gh: namespace prefix → "ga4gh:SQ.xxx" → "SQ.xxx" and "xxx"
    if let Some(stripped) = digest.strip_prefix("ga4gh:") {
        candidates.push(stripped.to_string());
        if let Some(bare) = stripped.strip_prefix("SQ.") {
            candidates.push(bare.to_string());
        }
    }

    // Strip md5: namespace prefix
    if let Some(stripped) = digest.strip_prefix("md5:") {
        candidates.push(stripped.to_string());
    }

    // trunc512: 48-char hex → decode to 24 bytes → base64url = sha512t24u
    if digest.len() == 48
        && digest.chars().all(|c| c.is_ascii_hexdigit())
        && let Ok(bytes) = hex_decode(digest)
    {
        let b64 = URL_SAFE_NO_PAD.encode(&bytes);
        candidates.push(format!("SQ.{b64}"));
        candidates.push(b64);
    }

    // Case-fold: lowercase for case-insensitive MD5 hex matching
    let lower = digest.to_ascii_lowercase();
    if lower != digest {
        candidates.push(lower);
    }

    candidates
}

/// Decode a hex string to bytes.
fn hex_decode(hex: &str) -> Result<Vec<u8>, ()> {
    if !hex.len().is_multiple_of(2) {
        return Err(());
    }
    (0..hex.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).map_err(|_| ()))
        .collect()
}

/// Try a store lookup with digest normalization.
/// Returns `Ok(Some(value))` on hit, `Ok(None)` for not found, `Err(response)` on store error.
fn lookup_normalized<T>(
    digest: &str,
    mut f: impl FnMut(&str) -> refget_store::StoreResult<Option<T>>,
) -> Result<Option<T>, Box<Response>> {
    for candidate in normalize_candidates(digest) {
        match f(&candidate) {
            Ok(Some(val)) => return Ok(Some(val)),
            Ok(None) => continue,
            Err(e) => {
                tracing::error!("Store error looking up digest {candidate}: {e}");
                return Err(Box::new(json_error(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Internal server error",
                )));
            }
        }
    }
    Ok(None)
}

async fn service_info(State(state): State<RefgetState>, headers: HeaderMap) -> Response {
    if let Some(resp) = check_accept(&headers, REFGET_JSON_CONTENT_TYPE, JSON_FALLBACKS) {
        return resp;
    }

    let refget_info = serde_json::json!({
        "circular_supported": state.config.circular_supported,
        "algorithms": state.config.algorithms,
        "identifier_types": ["ga4gh", "md5"],
        "subsequence_limit": state.config.subsequence_limit,
        "supported_api_versions": ["2.0.0"],
    });

    let mut info = serde_json::json!({
        "id": "org.ga4gh.refget",
        "name": "refget-rs",
        "type": {
            "group": "org.ga4gh",
            "artifact": "refget",
            "version": "2.0.0"
        },
        "description": "GA4GH refget Sequences v2.0.0",
        "version": env!("CARGO_PKG_VERSION"),
        "refget": refget_info,
        // v1 compliance suite expects "service" key wrapping the refget config
        "service": refget_info,
    });

    // Add optional service-info fields when configured
    let si = &state.config.service_info;
    if let Some(org) = &si.organization {
        info["organization"] = serde_json::json!({"name": org.name, "url": org.url});
    }
    if let Some(url) = &si.contact_url {
        info["contactUrl"] = serde_json::Value::String(url.clone());
    }
    if let Some(url) = &si.documentation_url {
        info["documentationUrl"] = serde_json::Value::String(url.clone());
    }
    if let Some(env) = &si.environment {
        info["environment"] = serde_json::Value::String(env.clone());
    }

    (
        StatusCode::OK,
        [("content-type", REFGET_JSON_CONTENT_TYPE)],
        serde_json::to_string(&info).unwrap(),
    )
        .into_response()
}

#[derive(Deserialize)]
struct SubsequenceParams {
    start: Option<u64>,
    end: Option<u64>,
}

async fn get_sequence(
    State(state): State<RefgetState>,
    Path(digest): Path<String>,
    Query(params): Query<SubsequenceParams>,
    headers: HeaderMap,
) -> Response {
    if let Some(resp) = check_accept(&headers, REFGET_PLAIN_CONTENT_TYPE, PLAIN_FALLBACKS) {
        return resp;
    }

    let has_query_params = params.start.is_some() || params.end.is_some();
    let has_range_header = headers.get("range").is_some();

    // Reject combined Range header + query params
    if has_query_params && has_range_header {
        return json_error(
            StatusCode::BAD_REQUEST,
            "Cannot combine Range header with start/end query params",
        );
    }

    // Parse Range header if present and no query params
    let (start, end, used_range_header) = if !has_query_params && has_range_header {
        match parse_range_header(&headers) {
            Some((s, e)) => (s, e, true),
            None => {
                return json_error(StatusCode::BAD_REQUEST, "Malformed Range header");
            }
        }
    } else {
        (params.start, params.end, false)
    };

    // Look up sequence length for bounds checking (needed before start/end validation)
    let length = match lookup_normalized(&digest, |d| state.sequence_store.get_length(d)) {
        Ok(Some(len)) => len,
        Ok(None) => return json_error(StatusCode::NOT_FOUND, "Sequence not found"),
        Err(resp) => return *resp,
    };

    // Bounds validation: check start >= length first (416 takes precedence over 501)
    if let Some(s) = start
        && s >= length
    {
        return json_error(StatusCode::RANGE_NOT_SATISFIABLE, "start >= sequence length");
    }
    // end > length: query params → 416, Range header → clamp (per HTTP spec)
    if let Some(e) = end
        && e > length
        && !used_range_header
    {
        return json_error(StatusCode::RANGE_NOT_SATISFIABLE, "end > sequence length");
    }

    // start > end: check circularity
    let is_circular_request = matches!((start, end), (Some(s), Some(e)) if s > e);
    if is_circular_request {
        if used_range_header {
            return json_error(StatusCode::RANGE_NOT_SATISFIABLE, "Range start > end");
        }
        if !state.config.circular_supported {
            return json_error(StatusCode::NOT_IMPLEMENTED, "Circular sequences not supported");
        }
        // Check if the sequence is actually circular
        let is_circular = match lookup_normalized(&digest, |d| state.sequence_store.get_metadata(d))
        {
            Ok(Some(meta)) => meta.circular,
            Ok(None) => return json_error(StatusCode::NOT_FOUND, "Sequence not found"),
            Err(resp) => return *resp,
        };
        if !is_circular {
            return json_error(StatusCode::RANGE_NOT_SATISFIABLE, "Sequence is not circular");
        }
    }

    // Enforce subsequence_limit (0 = no limit)
    let limit = state.config.subsequence_limit;
    if limit > 0 {
        let req_start = start.unwrap_or(0);
        let req_end = end.unwrap_or(length);
        let req_len = if is_circular_request {
            // Circular: wraps around
            (length - req_start) + req_end
        } else {
            req_end - req_start
        };
        if req_len > limit {
            return json_error(StatusCode::RANGE_NOT_SATISFIABLE, "Subsequence exceeds limit");
        }
    }

    // Fetch sequence (with circular wrapping if needed)
    let seq = if is_circular_request {
        // Circular: fetch [start..length] + [0..end]
        let tail = lookup_normalized(&digest, |d| {
            state.sequence_store.get_sequence(d, start, Some(length))
        });
        let head =
            lookup_normalized(&digest, |d| state.sequence_store.get_sequence(d, Some(0), end));
        match (tail, head) {
            (Ok(Some(mut t)), Ok(Some(h))) => {
                t.extend_from_slice(&h);
                Some(t)
            }
            (Ok(None), _) | (_, Ok(None)) => None,
            (Err(resp), _) | (_, Err(resp)) => return *resp,
        }
    } else {
        match lookup_normalized(&digest, |d| state.sequence_store.get_sequence(d, start, end)) {
            Ok(seq) => seq,
            Err(resp) => return *resp,
        }
    };

    match seq {
        Some(seq) => {
            if used_range_header {
                (StatusCode::PARTIAL_CONTENT, [("content-type", REFGET_PLAIN_CONTENT_TYPE)], seq)
                    .into_response()
            } else if start.is_some() || end.is_some() {
                (
                    StatusCode::OK,
                    [("content-type", REFGET_PLAIN_CONTENT_TYPE), ("accept-ranges", "none")],
                    seq,
                )
                    .into_response()
            } else {
                (StatusCode::OK, [("content-type", REFGET_PLAIN_CONTENT_TYPE)], seq).into_response()
            }
        }
        None => json_error(StatusCode::NOT_FOUND, "Sequence not found"),
    }
}

async fn get_metadata(
    State(state): State<RefgetState>,
    Path(digest): Path<String>,
    headers: HeaderMap,
) -> Response {
    if let Some(resp) = check_accept(&headers, REFGET_JSON_CONTENT_TYPE, JSON_FALLBACKS) {
        return resp;
    }

    match lookup_normalized(&digest, |d| state.sequence_store.get_metadata(d)) {
        Ok(Some(meta)) => {
            // Derive trunc512 (hex) from sha512t24u (base64url)
            let trunc512 = meta
                .sha512t24u
                .strip_prefix("SQ.")
                .and_then(|b64| URL_SAFE_NO_PAD.decode(b64).ok())
                .map(|bytes| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>())
                .unwrap_or_default();

            let response = serde_json::json!({
                "metadata": {
                    "md5": meta.md5,
                    "trunc512": trunc512,
                    "ga4gh": meta.sha512t24u,
                    "length": meta.length,
                    "aliases": meta.aliases,
                }
            });
            (
                StatusCode::OK,
                [("content-type", REFGET_JSON_CONTENT_TYPE)],
                serde_json::to_string(&response).unwrap(),
            )
                .into_response()
        }
        Ok(None) => json_error(StatusCode::NOT_FOUND, "Sequence not found"),
        Err(resp) => *resp,
    }
}

/// Parse a Range header of the form `bytes=start-end`.
///
/// Returns `Some((start, end))` on success, `None` for malformed headers.
/// HTTP Range is inclusive on both ends; the returned end is converted to exclusive.
fn parse_range_header(headers: &HeaderMap) -> Option<(Option<u64>, Option<u64>)> {
    let range = headers.get("range")?;
    let range_str = range.to_str().ok()?;
    let bytes_range = range_str.strip_prefix("bytes=")?;
    let parts: Vec<&str> = bytes_range.splitn(2, '-').collect();
    if parts.len() != 2 {
        return None;
    }
    let start = if parts[0].is_empty() { None } else { Some(parts[0].parse::<u64>().ok()?) };
    let end = if parts[1].is_empty() {
        None
    } else {
        Some(parts[1].parse::<u64>().ok()?.checked_add(1)?) // inclusive → exclusive
    };
    Some((start, end))
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::Request;
    use http_body_util::BodyExt;
    use refget_model::SequenceMetadata;
    use refget_store::{InMemorySeqColStore, InMemorySequenceStore};
    use std::sync::Arc;
    use tower::ServiceExt;

    use crate::{RefgetConfig, RefgetState};

    fn test_metadata() -> SequenceMetadata {
        SequenceMetadata {
            md5: "abc123".to_string(),
            sha512t24u: "SQ.xyz789".to_string(),
            length: 10,
            aliases: vec![],
            circular: false,
        }
    }

    fn test_state() -> RefgetState {
        RefgetState {
            sequence_store: Arc::new(InMemorySequenceStore::new()),
            seqcol_store: Arc::new(InMemorySeqColStore::new()),
            config: RefgetConfig::default(),
        }
    }

    fn test_state_with_sequence() -> RefgetState {
        let mut seq_store = InMemorySequenceStore::new();
        seq_store.add(test_metadata(), b"ACGTACGTAC".to_vec());
        RefgetState {
            sequence_store: Arc::new(seq_store),
            seqcol_store: Arc::new(InMemorySeqColStore::new()),
            config: RefgetConfig::default(),
        }
    }

    #[tokio::test]
    async fn test_service_info() {
        let app = router(test_state());
        let req = Request::builder().uri("/sequence/service-info").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let content_type = resp.headers().get("content-type").unwrap().to_str().unwrap();
        assert_eq!(content_type, REFGET_JSON_CONTENT_TYPE);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let refget = json.get("refget").expect("response must contain 'refget' key");
        assert_eq!(refget["subsequence_limit"], 0);
    }

    #[tokio::test]
    async fn test_get_sequence() {
        let state = test_state_with_sequence();
        let app = router(state);
        let req = Request::builder().uri("/sequence/SQ.xyz789").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let content_type = resp.headers().get("content-type").unwrap().to_str().unwrap();
        assert_eq!(content_type, REFGET_PLAIN_CONTENT_TYPE);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"ACGTACGTAC");
    }

    #[tokio::test]
    async fn test_get_sequence_not_found() {
        let app = router(test_state());
        let req = Request::builder().uri("/sequence/nonexistent").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_get_sequence_with_query_params() {
        let state = test_state_with_sequence();
        let app = router(state);
        let req = Request::builder()
            .uri("/sequence/SQ.xyz789?start=2&end=6")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        // Query param subsequences return 200, not 206
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.headers().get("accept-ranges").unwrap().to_str().unwrap(), "none");

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"GTAC");
    }

    #[tokio::test]
    async fn test_get_sequence_with_range_header() {
        let state = test_state_with_sequence();
        let app = router(state);
        let req = Request::builder()
            .uri("/sequence/SQ.xyz789")
            .header("range", "bytes=2-5")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        // Range header → 206
        assert_eq!(resp.status(), StatusCode::PARTIAL_CONTENT);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"GTAC");
    }

    #[tokio::test]
    async fn test_get_sequence_invalid_range() {
        let state = test_state_with_sequence();
        let app = router(state);
        let req = Request::builder()
            .uri("/sequence/SQ.xyz789?start=5&end=3")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        // start > end on a non-circular sequence → 416
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
    }

    #[tokio::test]
    async fn test_get_metadata() {
        let state = test_state_with_sequence();
        let app = router(state);
        let req =
            Request::builder().uri("/sequence/SQ.xyz789/metadata").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let content_type = resp.headers().get("content-type").unwrap().to_str().unwrap();
        assert_eq!(content_type, REFGET_JSON_CONTENT_TYPE);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let metadata = json.get("metadata").expect("must have 'metadata' key");
        assert_eq!(metadata["md5"], "abc123");
        assert_eq!(metadata["ga4gh"], "SQ.xyz789");
        assert_eq!(metadata["length"], 10);
    }

    #[tokio::test]
    async fn test_get_metadata_not_found() {
        let app = router(test_state());
        let req =
            Request::builder().uri("/sequence/nonexistent/metadata").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_parse_range_header_valid() {
        let mut headers = HeaderMap::new();
        headers.insert("range", "bytes=10-19".parse().unwrap());
        let (start, end) = parse_range_header(&headers).unwrap();
        assert_eq!(start, Some(10));
        // HTTP Range is inclusive, so 19 becomes 20 (exclusive)
        assert_eq!(end, Some(20));
    }

    #[test]
    fn test_parse_range_header_invalid_format() {
        let mut headers = HeaderMap::new();
        headers.insert("range", "invalid".parse().unwrap());
        assert!(parse_range_header(&headers).is_none());
    }

    #[test]
    fn test_parse_range_header_missing() {
        let headers = HeaderMap::new();
        assert!(parse_range_header(&headers).is_none());
    }

    #[test]
    fn test_parse_range_header_bad_units() {
        let mut headers = HeaderMap::new();
        headers.insert("range", "units=20-30".parse().unwrap());
        assert!(parse_range_header(&headers).is_none());
    }

    #[test]
    fn test_parse_range_header_non_numeric() {
        let mut headers = HeaderMap::new();
        headers.insert("range", "bytes=ab-19".parse().unwrap());
        assert!(parse_range_header(&headers).is_none());
    }

    // --- GA4GH Compliance Integration Tests ---

    fn compliance_test_state() -> RefgetState {
        use md5::{Digest, Md5};
        use refget_digest::sha512t24u;
        use refget_model::Alias;

        let mut seq_store = InMemorySequenceStore::new();

        // Canonical test vector: ACGT
        let seq = b"ACGT";
        let md5_hex = format!("{:x}", Md5::digest(seq));
        let sha_digest = sha512t24u(seq);
        let ga4gh_digest = format!("SQ.{sha_digest}");

        seq_store.add(
            SequenceMetadata {
                md5: md5_hex.clone(),
                sha512t24u: ga4gh_digest.clone(),
                length: seq.len() as u64,
                aliases: vec![Alias {
                    naming_authority: "insdc".to_string(),
                    value: "test_seq".to_string(),
                }],
                circular: false,
            },
            seq.to_vec(),
        );

        RefgetState {
            sequence_store: Arc::new(seq_store),
            seqcol_store: Arc::new(InMemorySeqColStore::new()),
            config: RefgetConfig::default(),
        }
    }

    #[tokio::test]
    async fn test_compliance_service_info() {
        let app = router(compliance_test_state());
        let req = Request::builder().uri("/sequence/service-info").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let content_type = resp.headers().get("content-type").unwrap().to_str().unwrap();
        assert_eq!(content_type, REFGET_JSON_CONTENT_TYPE);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let refget = &json["refget"];
        assert_eq!(refget["circular_supported"], true);
        assert!(refget["algorithms"].as_array().unwrap().len() >= 2);
        assert_eq!(refget["subsequence_limit"], 0);
        assert!(refget["identifier_types"].as_array().is_some());
    }

    #[tokio::test]
    async fn test_compliance_service_info_with_optional_fields() {
        use crate::state::{OrganizationConfig, ServiceInfoConfig};

        let mut state = compliance_test_state();
        state.config.service_info = ServiceInfoConfig {
            organization: Some(OrganizationConfig {
                name: "Test Org".to_string(),
                url: "https://example.org".to_string(),
            }),
            contact_url: Some("mailto:admin@example.org".to_string()),
            documentation_url: Some("https://example.org/docs".to_string()),
            environment: Some("test".to_string()),
        };

        let app = router(state);
        let req = Request::builder().uri("/sequence/service-info").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["organization"]["name"], "Test Org");
        assert_eq!(json["organization"]["url"], "https://example.org");
        assert_eq!(json["contactUrl"], "mailto:admin@example.org");
        assert_eq!(json["documentationUrl"], "https://example.org/docs");
        assert_eq!(json["environment"], "test");
    }

    #[tokio::test]
    async fn test_compliance_get_sequence_by_ga4gh() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"ACGT");
    }

    #[tokio::test]
    async fn test_compliance_get_sequence_by_md5() {
        use md5::{Digest, Md5};

        let md5_hex = format!("{:x}", Md5::digest(b"ACGT"));
        let app = router(compliance_test_state());
        let req =
            Request::builder().uri(format!("/sequence/{md5_hex}")).body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"ACGT");
    }

    #[tokio::test]
    async fn test_compliance_get_sequence_by_md5_uppercase() {
        use md5::{Digest, Md5};

        let md5_hex = format!("{:X}", Md5::digest(b"ACGT"));
        let app = router(compliance_test_state());
        let req =
            Request::builder().uri(format!("/sequence/{md5_hex}")).body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"ACGT");
    }

    #[tokio::test]
    async fn test_compliance_get_sequence_by_namespaced_ga4gh() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/ga4gh:SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"ACGT");
    }

    #[tokio::test]
    async fn test_compliance_get_sequence_by_namespaced_md5() {
        use md5::{Digest, Md5};

        let md5_hex = format!("{:x}", Md5::digest(b"ACGT"));
        let app = router(compliance_test_state());
        let req =
            Request::builder().uri(format!("/sequence/md5:{md5_hex}")).body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"ACGT");
    }

    #[tokio::test]
    async fn test_compliance_get_sequence_by_trunc512() {
        use sha2::{Digest, Sha512};

        // Compute trunc512: first 24 bytes of SHA-512, hex-encoded (48 chars)
        let hash = Sha512::digest(b"ACGT");
        let trunc512: String = hash[..24].iter().map(|b| format!("{b:02x}")).collect();
        assert_eq!(trunc512.len(), 48);

        let app = router(compliance_test_state());
        let req =
            Request::builder().uri(format!("/sequence/{trunc512}")).body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"ACGT");
    }

    #[tokio::test]
    async fn test_compliance_subsequence_start_end() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?start=1&end=3")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        // Query params → 200, not 206
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.headers().get("accept-ranges").unwrap().to_str().unwrap(), "none");

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"CG");
    }

    #[tokio::test]
    async fn test_compliance_subsequence_range_header() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2")
            .header("range", "bytes=1-2")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        // Range header → 206
        assert_eq!(resp.status(), StatusCode::PARTIAL_CONTENT);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"CG");
    }

    #[tokio::test]
    async fn test_compliance_start_equals_end() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?start=2&end=2")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert!(body.is_empty());
    }

    #[tokio::test]
    async fn test_compliance_start_greater_end_non_circular_416() {
        // start > end on a non-circular sequence with circular_supported=true → 416
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?start=3&end=1")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
    }

    #[tokio::test]
    async fn test_compliance_start_beyond_length_416() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?start=100")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
    }

    #[tokio::test]
    async fn test_compliance_end_beyond_length_416() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?end=100")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
    }

    #[tokio::test]
    async fn test_compliance_range_plus_query_400() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?start=0&end=2")
            .header("range", "bytes=0-1")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_compliance_accept_not_acceptable() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2")
            .header("accept", "text/xml")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_ACCEPTABLE);
    }

    #[tokio::test]
    async fn test_compliance_accept_wildcard() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2")
            .header("accept", "*/*")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_compliance_accept_text_plain_fallback() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2")
            .header("accept", "text/plain")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_compliance_accept_json_fallback_for_metadata() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2/metadata")
            .header("accept", "application/json")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_compliance_accept_json_fallback_for_service_info() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/service-info")
            .header("accept", "application/json")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_compliance_metadata_content_type() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2/metadata")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let content_type = resp.headers().get("content-type").unwrap().to_str().unwrap();
        assert_eq!(content_type, REFGET_JSON_CONTENT_TYPE);
    }

    #[tokio::test]
    async fn test_compliance_metadata_shape() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2/metadata")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let metadata = json.get("metadata").expect("must have 'metadata' key");
        assert!(metadata["md5"].is_string());
        assert!(metadata["ga4gh"].as_str().unwrap().starts_with("SQ."));
        assert_eq!(metadata["length"], 4);
        assert!(metadata["aliases"].is_array());
    }

    #[tokio::test]
    async fn test_compliance_not_found_404() {
        let app = router(compliance_test_state());
        let req = Request::builder()
            .uri("/sequence/SQ.nonexistentdigest000000000000")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_compliance_subsequence_limit_enforced() {
        let mut state = compliance_test_state();
        state.config.subsequence_limit = 2;

        let app = router(state);
        // Request 3 bases with limit of 2 → 416
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?start=0&end=3")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
    }

    #[tokio::test]
    async fn test_compliance_subsequence_limit_within() {
        let mut state = compliance_test_state();
        state.config.subsequence_limit = 2;

        let app = router(state);
        // Request 2 bases with limit of 2 → OK
        let req = Request::builder()
            .uri("/sequence/SQ.aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2?start=0&end=2")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], b"AC");
    }

    #[test]
    fn test_hex_decode() {
        assert_eq!(hex_decode(""), Ok(vec![]));
        assert_eq!(hex_decode("00ff"), Ok(vec![0x00, 0xff]));
        assert_eq!(hex_decode("0F"), Ok(vec![0x0f]));
        assert!(hex_decode("0").is_err());
        assert!(hex_decode("zz").is_err());
    }

    #[test]
    fn test_normalize_candidates() {
        // Basic SQ. prefix
        let candidates = normalize_candidates("SQ.abc123");
        assert!(candidates.contains(&"SQ.abc123".to_string()));
        assert!(candidates.contains(&"abc123".to_string()));

        // ga4gh: namespace
        let candidates = normalize_candidates("ga4gh:SQ.abc123");
        assert!(candidates.contains(&"SQ.abc123".to_string()));
        assert!(candidates.contains(&"abc123".to_string()));

        // md5: namespace
        let candidates = normalize_candidates("md5:abc123");
        assert!(candidates.contains(&"abc123".to_string()));

        // Case folding
        let candidates = normalize_candidates("ABC123");
        assert!(candidates.contains(&"abc123".to_string()));
    }
}