about summary refs log tree commit diff
path: root/src/routes/genotypes.rs
blob: 65d6a95db41c536a25a8fc9f2cbf2b6de5d89e5e (plain)
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
//! `GET /groups/{group}/genotypes` -- the genotype files a group can be
//! mapped with, newest first.
//!
//! This is the listing that makes `/compute/rqtl` and `/compute/gemma`
//! usable without knowing the deployment's filesystem: it names each
//! version, says which one a mapping gets by default, and reports the
//! panel and marker counts so a caller can size the request. It does
//! **not** serve the files, or their paths -- `src/genotypes.rs` resolves
//! those server-side from the group and version.

use axum::Json;
use axum::extract::{Path, Query};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

use gnauth_macros::gnauth;

use crate::auth::AuthToken;
use crate::config::Config;
use crate::error::{ApiError, Unauthorized};
use crate::genotypes::{self, GenotypeError, OrderSource};
use crate::response::{Ctx, Envelope, path_segment};
use crate::suggest;

/// One genotype file, as the listing reports it.
#[derive(Serialize, ToSchema)]
pub struct GenotypeVersion {
    /// What a mapping request names in `genotype_version`, e.g. "BXD.8".
    /// `null` in `current` means "whatever `genotype_version` is now".
    pub version: String,
    /// The genotype file's name, e.g. "BXD.8.geno".
    pub file: String,
    /// The panel's own title for it, e.g. "WGS-based (Mar2022)".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Individuals in the file (its header's sample columns).
    pub individuals: usize,
    /// Marker rows in the file.
    pub markers: usize,
    /// Whether GEMMA can run on it: a `bimbam/<version>_geno.txt` +
    /// `_snps.txt` pair exists.
    pub gemma: bool,
    /// Whether R/qtl can run on it: the `.geno` exists.
    pub rqtl: bool,
    /// This is what a mapping request gets when it names no version.
    pub current: bool,
}

/// The listing for one group.
#[derive(Serialize, ToSchema)]
pub struct GroupGenotypes {
    pub group: String,
    pub versions: Vec<GenotypeVersion>,
}

/// One marker's position.
#[derive(Serialize, ToSchema)]
pub struct MarkerInfo {
    pub name: String,
    pub chr: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cm: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mb: Option<f64>,
}

/// Everything about one genotype version except the genotypes.
#[derive(Serialize, ToSchema)]
pub struct GenotypeDetail {
    pub group: String,
    pub version: String,
    /// The genotype file's name, e.g. "BXD.8.geno".
    pub file: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// The panel's own `@`-labels (`type`, `mat`, `pat`, `het`, `unk`,
    /// `scale`, ...), as key/value pairs in file order.
    pub labels: Vec<Label>,
    /// Individuals in the file, in column order (parents and F1s included).
    pub individuals: Vec<String>,
    /// `individuals.len()`.
    pub num_individuals: usize,
    /// The individuals a mapping uses: `individuals` minus the parents and
    /// F1s that the default rule drops.
    pub strains: Vec<String>,
    /// `strains.len()`.
    pub num_strains: usize,
    /// Markers per chromosome, in the file's order.
    pub chromosomes: Vec<Chromosome>,
    pub markers: usize,
    pub gemma: bool,
    pub rqtl: bool,
    pub current: bool,
}

/// One `@key: value` line from the file's header.
#[derive(Serialize, ToSchema)]
pub struct Label {
    pub key: String,
    pub value: String,
}

/// A chromosome and how many markers it has.
#[derive(Serialize, ToSchema)]
pub struct Chromosome {
    pub name: String,
    pub markers: usize,
}

/// Paging for the marker list.
#[derive(Deserialize, utoipa::IntoParams)]
pub struct MarkerParams {
    /// One-based page of `limit` markers. Default 1.
    pub page: Option<u32>,
    /// Markers per page. Default 100, at most 10000.
    pub limit: Option<u32>,
    /// Only this chromosome, e.g. "1" or "X".
    pub chr: Option<String>,
}

#[utoipa::path(get, path = "/groups/{group}/genotypes",
    summary = "Genotype files available for a group, newest first",
    description = "Names each genotype version a group can be mapped with, the panel and \
marker counts, which engines can run on it, and which one is current (what a mapping \
request gets by default). Files and paths stay server-side: pass `group` and optionally \
`genotype_version` to POST /compute/rqtl or /compute/gemma.",
    params(("group" = String, Path, description = "InbredSet name, e.g. BXD")),
    responses(
        (status = 200, description = "The group's genotype versions", body = Envelope<GroupGenotypes>),
        Unauthorized,
        (status = 404, description = "No such group, or it has no genotype files", body = ApiError),
        (status = 500, description = "The genotype-files directory could not be read", body = ApiError)
    )
)]
#[gnauth(token_only)]
pub async fn group_genotypes(
    ctx: Ctx,
    Path(group): Path<String>,
    _token: AuthToken,
) -> Result<Json<Envelope<GroupGenotypes>>, ApiError> {
    let rid = ctx.request_info();
    let directory = Config::load().genotype_files_dir;
    let wanted = group.clone();
    let files = tokio::task::spawn_blocking(move || {
        genotypes::list(std::path::Path::new(&directory), &wanted)
    })
    .await
    .map_err(|e| {
        ApiError::new(
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            e.to_string(),
            "group_genotypes",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|e| match e {
        GenotypeError::Invalid(_) => ApiError::new(
            axum::http::StatusCode::UNPROCESSABLE_ENTITY,
            "invalid_individuals",
            "Unusable individual selection",
            e.to_string(),
            "group_genotypes",
        )
        .with_request_id(rid.clone()),
        GenotypeError::NotFound(message) => ApiError::new(
            axum::http::StatusCode::NOT_FOUND,
            "genotypes_not_found",
            "Genotype files not found",
            message,
            "group_genotypes",
        )
        .with_request_id(rid.clone()),
        GenotypeError::Io(message) => ApiError::new(
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            "genotypes_unreadable",
            "Genotype files could not be read",
            message,
            "group_genotypes",
        )
        .with_request_id(rid.clone()),
    })?;

    let order = match files.first().map(|file| file.order_source) {
        Some(OrderSource::Json) => {
            "Versions are in the order the deployment's genotype/<group>.json records, newest \
             first; `current` is its first entry, which is what GeneNetwork2's mapping UI \
             defaults to."
        }
        Some(OrderSource::FileNames) => {
            "No genotype/<group>.json records this group's versions, so the order is inferred \
             from the file names, highest version number first. Treat `current` as the likely \
             default rather than a recorded one."
        }
        None => "",
    };

    let current_version = files
        .iter()
        .find(|file| file.current)
        .map(|file| file.version.clone());
    Ok(Json(
        ctx.envelope(GroupGenotypes {
            group: group.clone(),
            versions: files
                .into_iter()
                .map(|file| GenotypeVersion {
                    file: file.file,
                    version: file.version,
                    title: file.title,
                    individuals: file.individuals,
                    markers: file.markers,
                    gemma: file.gemma,
                    rqtl: file.rqtl,
                    current: file.current,
                })
                .collect(),
        })
        .with_note(order)
        .with_note(
            "Mappings exclude parents and F1s by default, as in GeneNetwork2/3; pass \
             include_parents_f1 to include them. The individuals here are the whole file.",
        )
        .with_action(crate::response::SuggestedCall {
            method: "POST".to_string(),
            href: "/compute/rqtl".to_string(),
            description: "Map a trait over this group's current genotype file: pass `group`, the \
                          trait's values as named `samples`, and leave out `genotype_file`."
                .to_string(),
            body: None,
        })
        .with_action(crate::response::SuggestedCall {
            method: "POST".to_string(),
            href: "/compute/gemma".to_string(),
            description: "The same mapping with GEMMA (needs a version whose `gemma` is true): \
                          pass `group` and the trait's values as named `samples`."
                .to_string(),
            body: None,
        })
        .with_next(
            &format!("/groups/{}", path_segment(&group)),
            "The group's record",
        )
        .with_links(match current_version {
            Some(version) => suggest::genotype_version_links(&group, &version),
            None => suggest::root_links(),
        }),
    ))
}

#[utoipa::path(get, path = "/groups/{group}/genotypes/{version}",
    summary = "Metadata of one genotype version: labels, panel, markers",
    description = "The header labels, the panel's individuals (and the strains a mapping \
actually uses), the chromosomes and their marker counts -- without a single genotype call. \
Equivalently: everything //groups/{group}/traits/{id}/values leaves you needing to build a \
mapping request.",
    params(
        ("group" = String, Path, description = "InbredSet name, e.g. BXD"),
        ("version" = String, Path, description = "Version from /groups/{group}/genotypes, e.g. BXD.8")
    ),
    responses(
        (status = 200, description = "The version's metadata", body = Envelope<GenotypeDetail>),
        Unauthorized,
        (status = 404, description = "No such group or version", body = ApiError),
        (status = 500, description = "The genotype file could not be read", body = ApiError)
    )
)]
#[gnauth(token_only)]
pub async fn group_genotype_version(
    ctx: Ctx,
    Path((group, version)): Path<(String, String)>,
    _token: AuthToken,
) -> Result<Json<Envelope<GenotypeDetail>>, ApiError> {
    let rid = ctx.request_info();
    let detail = resolve_detail(&group, &version, rid.clone()).await?;
    let link_group = group.clone();
    let link_version = version.clone();
    Ok(Json(
        ctx.envelope(detail)
            .with_note(
                "`individuals` is the whole file; `strains` is what a mapping uses, after the \
                 default parents/F1s exclusion. Marker positions come from the file itself.",
            )
            .with_next(
                &format!(
                    "/groups/{}/genotypes/{}/markers",
                    path_segment(&link_group),
                    path_segment(&link_version)
                ),
                "The markers this version carries, paged (name, chr, cM, Mb)",
            )
            .with_next(
                &format!("/groups/{}", path_segment(&link_group)),
                "The group's record",
            )
            .with_links(suggest::genotype_version_links(&link_group, &link_version)),
    ))
}

#[utoipa::path(get, path = "/groups/{group}/genotypes/{version}/markers",
    summary = "The marker names one genotype version carries, paged",
    description = "The names only -- the list a caller iterates. Positions are a separate call, \
`/groups/{group}/genotypes/{version}/markers/{marker}/location`, so a page of names stays small \
and a position lookup is one marker rather than a table. Filter with ?chr=1 and page with \
?page/?limit.",
    params(
        ("group" = String, Path, description = "InbredSet name, e.g. BXD"),
        ("version" = String, Path, description = "Version from /groups/{group}/genotypes"),
        MarkerParams
    ),
    responses(
        (status = 200, description = "A page of marker names, positional rows (meta.columns names them)", body = Envelope<serde_json::Value>),
        Unauthorized,
        (status = 404, description = "No such group or version", body = ApiError),
        (status = 413, description = "The genotype file is too large to read whole", body = ApiError),
        (status = 422, description = "limit out of range", body = ApiError),
        (status = 500, description = "The genotype file could not be read", body = ApiError)
    )
)]
#[gnauth(token_only)]
pub async fn group_genotype_markers(
    ctx: Ctx,
    Path((group, version)): Path<(String, String)>,
    Query(params): Query<MarkerParams>,
    _token: AuthToken,
) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
    let rid = ctx.request_info();
    let directory = Config::load().genotype_files_dir;
    let wanted_group = group.clone();
    let wanted_version = version.clone();
    let geno = tokio::task::spawn_blocking(move || {
        genotypes::resolve(
            std::path::Path::new(&directory),
            &wanted_group,
            Some(&wanted_version),
        )
        .map(|resolved| resolved.geno)
    })
    .await
    .map_err(|error| internal_error(error.to_string(), "group_genotype_markers", rid.clone()))?
    .map_err(|error| genotype_error_to_api_error(error, "group_genotype_markers", rid.clone()))?;
    let prefix = format!(
        "/groups/{}/genotypes/{}/markers",
        path_segment(&group),
        path_segment(&version)
    );
    let links = suggest::genotype_version_links(&group, &version);
    Ok(Json(
        marker_names(ctx, geno, &params, &prefix, &links, rid).await?,
    ))
}

#[utoipa::path(get, path = "/groups/{group}/genotypes/{version}/markers/{marker}/location",
    summary = "One marker's position, as named fields",
    description = "`name`, `chr`, `cM` and `Mb` for one marker of this version, as an object \
rather than a row: the companion to the marker-name list, and the same shape as the \
frequencies endpoints' answers.",
    params(
        ("group" = String, Path, description = "InbredSet name, e.g. BXD"),
        ("version" = String, Path, description = "Version from /groups/{group}/genotypes"),
        ("marker" = String, Path, description = "Marker name as the genotype file spells it")
    ),
    responses(
        (status = 200, description = "The marker's position", body = Envelope<serde_json::Value>),
        Unauthorized,
        (status = 404, description = "No such group, version or marker", body = ApiError),
        (status = 413, description = "The genotype file is too large to read whole", body = ApiError)
    )
)]
#[gnauth(token_only)]
pub async fn group_marker_location(
    ctx: Ctx,
    Path((group, version, marker)): Path<(String, String, String)>,
    _token: AuthToken,
) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
    let rid = ctx.request_info();
    let directory = Config::load().genotype_files_dir;
    let wanted_group = group.clone();
    let wanted_version = version.clone();
    let geno = tokio::task::spawn_blocking(move || {
        genotypes::resolve(
            std::path::Path::new(&directory),
            &wanted_group,
            Some(&wanted_version),
        )
        .map(|resolved| resolved.geno)
    })
    .await
    .map_err(|error| internal_error(error.to_string(), "group_marker_location", rid.clone()))?
    .map_err(|error| genotype_error_to_api_error(error, "group_marker_location", rid.clone()))?;
    let prefix = format!(
        "/groups/{}/genotypes/{}/markers",
        path_segment(&group),
        path_segment(&version)
    );
    let links = suggest::marker_links(&group, &version, &marker);
    Ok(Json(
        marker_location(ctx, geno, &marker, &prefix, &links, rid).await?,
    ))
}

#[utoipa::path(get, path = "/groups/unlisted/genotypes/{name}/markers",
    summary = "The marker names in a genotype file no group lists, paged",
    description = "The names only, for a file outside the group listing (a panel in \
preparation, a fixture, the DO's `do/` cross). `{name}` is the version, `.geno` name, or a path \
relative to the genotype files directory.",
    params(
        ("name" = String, Path, description = "Version, .geno name, or path relative to the genotype files directory"),
        MarkerParams
    ),
    responses(
        (status = 200, description = "A page of marker names, positional rows (meta.columns names them)", body = Envelope<serde_json::Value>),
        Unauthorized,
        (status = 404, description = "No such genotype file", body = ApiError),
        (status = 413, description = "The genotype file is too large to read whole", body = ApiError)
    )
)]
#[gnauth(token_only)]
pub async fn unlisted_genotype_markers(
    ctx: Ctx,
    Path(name): Path<String>,
    Query(params): Query<MarkerParams>,
    _token: AuthToken,
) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
    let rid = ctx.request_info();
    let root = Config::load().genotype_files_dir;
    let geno = tokio::task::spawn_blocking({
        let name = name.clone();
        move || genotypes::resolve_named(std::path::Path::new(&root), &name)
    })
    .await
    .map_err(|error| internal_error(error.to_string(), "unlisted_genotype_markers", rid.clone()))?
    .map_err(|error| {
        genotype_error_to_api_error(error, "unlisted_genotype_markers", rid.clone())
    })?;
    let prefix = format!("/groups/unlisted/genotypes/{}/markers", path_segment(&name));
    let links = suggest::unlisted_genotype_links(&name);
    Ok(Json(
        marker_names(ctx, geno, &params, &prefix, &links, rid).await?,
    ))
}

#[utoipa::path(get, path = "/groups/unlisted/genotypes/{name}/markers/{marker}/location",
    summary = "One marker's position in a genotype file no group lists",
    description = "`name`, `chr`, `cM` and `Mb` for one marker of a file outside the group \
listing.",
    params(
        ("name" = String, Path, description = "Version, .geno name, or path relative to the genotype files directory"),
        ("marker" = String, Path, description = "Marker name as the genotype file spells it")
    ),
    responses(
        (status = 200, description = "The marker's position", body = Envelope<serde_json::Value>),
        Unauthorized,
        (status = 404, description = "No such genotype file or marker", body = ApiError),
        (status = 413, description = "The genotype file is too large to read whole", body = ApiError)
    )
)]
#[gnauth(token_only)]
pub async fn unlisted_marker_location(
    ctx: Ctx,
    Path((name, marker)): Path<(String, String)>,
    _token: AuthToken,
) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
    let rid = ctx.request_info();
    let root = Config::load().genotype_files_dir;
    let geno = tokio::task::spawn_blocking({
        let name = name.clone();
        move || genotypes::resolve_named(std::path::Path::new(&root), &name)
    })
    .await
    .map_err(|error| internal_error(error.to_string(), "unlisted_marker_location", rid.clone()))?
    .map_err(|error| genotype_error_to_api_error(error, "unlisted_marker_location", rid.clone()))?;
    let prefix = format!("/groups/unlisted/genotypes/{}/markers", path_segment(&name));
    let links = suggest::unlisted_marker_links(&name, &marker);
    Ok(Json(
        marker_location(ctx, geno, &marker, &prefix, &links, rid).await?,
    ))
}

/// Read a `.geno`'s markers and answer with one page of names.
async fn marker_names(
    ctx: Ctx,
    geno: std::path::PathBuf,
    params: &MarkerParams,
    prefix: &str,
    links: &[suggest::Link],
    rid: crate::response::RequestInfo,
) -> Result<Envelope<serde_json::Value>, ApiError> {
    let limit = params.limit.unwrap_or(100).clamp(1, 10_000) as usize;
    let page = params.page.unwrap_or(1).max(1) as usize;
    let chr = params.chr.clone();
    guard_size(&geno, "markers", rid.clone())?;
    let markers = read_markers(geno, "markers", rid.clone()).await?;
    let filtered: Vec<genotypes::Marker> = markers
        .into_iter()
        .filter(|marker| chr.as_deref().is_none_or(|wanted| marker.chr == wanted))
        .collect();
    let total = filtered.len();
    let rows: Vec<serde_json::Value> = filtered
        .into_iter()
        .skip((page - 1) * limit)
        .take(limit)
        .map(|marker| serde_json::json!([marker.name]))
        .collect();
    let num_rows = rows.len();
    let mut envelope = ctx
        .envelope(serde_json::Value::Array(rows))
        .with_columns(vec!["name".to_string()], num_rows)
        .with_note(
            "Marker names as the genotype file spells them. A position is one call per marker:              append /{marker}/location. The genotypes themselves are never served.",
        );
    if let Some(chr) = &chr {
        envelope = envelope.with_note(&format!(
            "Filtered to chromosome {chr}: {total} markers."
        ));
    }
    let pages = total.div_ceil(limit).max(1);
    if page < pages {
        envelope = envelope.with_next(
            &format!(
                "{prefix}?page={}&limit={}{}",
                page + 1,
                limit,
                chr.as_deref()
                    .map(|c| format!("&chr={}", path_segment(c)))
                    .unwrap_or_default()
            ),
            "The next page of marker names",
        );
    }
    Ok(envelope)
}

/// One marker's position, as named fields.
async fn marker_location(
    ctx: Ctx,
    geno: std::path::PathBuf,
    marker: &str,
    prefix: &str,
    links: &[suggest::Link],
    rid: crate::response::RequestInfo,
) -> Result<Envelope<serde_json::Value>, ApiError> {
    guard_size(&geno, "location", rid.clone())?;
    let markers = read_markers(geno, "location", rid.clone()).await?;
    let found = markers
        .into_iter()
        .find(|candidate| candidate.name == marker)
        .ok_or_else(|| {
            ApiError::new(
                axum::http::StatusCode::NOT_FOUND,
                "marker_not_found",
                "Marker not found",
                format!("no marker '{marker}' in this genotype file"),
                "marker_location",
            )
            .with_request_id(rid.clone())
        })?;
    Ok(ctx
        .envelope(serde_json::json!({
            "name": found.name,
            "chr": found.chr,
            "cM": found.cm,
            "Mb": found.mb,
        }))
        .with_note(
            "Positions come from the genotype file itself: cM from its genetic map, Mb from its              physical one, either of which may be absent.",
        )
        .with_next(prefix, "The marker names this file carries")
        .with_links_except(
            links.to_vec(),
            &format!("{prefix}/{}/location", path_segment(marker)),
        ))
}

/// A whole-file read needs a size guard, or a 3.7 GB panel turns a listing into
/// a ten-minute request.
fn guard_size(
    geno: &std::path::Path,
    operation: &'static str,
    rid: crate::response::RequestInfo,
) -> Result<(), ApiError> {
    let size = std::fs::metadata(geno)
        .map_err(|error| internal_error(format!("{}: {error}", geno.display()), operation, rid.clone()))?
        .len();
    if size > genotypes::MAX_SCAN_BYTES {
        return Err(ApiError::new(
            axum::http::StatusCode::PAYLOAD_TOO_LARGE,
            "genotype_too_large",
            "Panel too large to read whole",
            format!(
                "{} is {} MB, past the {} MB a listing reads; ask for one marker's location, or                  pick a smaller version",
                geno.display(),
                size / (1024 * 1024),
                genotypes::MAX_SCAN_BYTES / (1024 * 1024)
            ),
            operation,
        )
        .with_request_id(rid));
    }
    Ok(())
}

async fn read_markers(
    geno: std::path::PathBuf,
    operation: &'static str,
    rid: crate::response::RequestInfo,
) -> Result<Vec<genotypes::Marker>, ApiError> {
    tokio::task::spawn_blocking(move || genotypes::file_meta(&geno).map(|meta| meta.markers))
        .await
        .map_err(|error| internal_error(error.to_string(), operation, rid.clone()))?
        .map_err(|error| genotype_error_to_api_error(error, operation, rid))
}

fn internal_error(
    message: String,
    operation: &'static str,
    rid: crate::response::RequestInfo,
) -> ApiError {
    ApiError::new(
        axum::http::StatusCode::INTERNAL_SERVER_ERROR,
        "internal_error",
        "Internal error",
        message,
        operation,
    )
    .with_request_id(rid)
}

/// Resolve a version and read its metadata; shared by the detail handler.
async fn resolve_detail(
    group: &str,
    version: &str,
    rid: crate::response::RequestInfo,
) -> Result<GenotypeDetail, ApiError> {
    let directory = Config::load().genotype_files_dir;
    let group_owned = group.to_string();
    let version_owned = version.to_string();
    let wanted_group = group_owned.clone();
    let wanted_version = version_owned.clone();
    tokio::task::spawn_blocking(move || {
        let dir = std::path::Path::new(&directory);
        let resolved = genotypes::resolve(dir, &wanted_group, Some(&wanted_version))?;
        let files = genotypes::list(dir, &wanted_group)?;
        let listed = files
            .iter()
            .find(|file| file.version == resolved.version)
            .map(|file| (file.title.clone(), file.gemma, file.rqtl, file.current))
            .unwrap_or((resolved.title.clone(), false, false, false));
        let meta = genotypes::file_meta(&resolved.geno)?;
        let excluded = genotypes::non_strains(dir, &wanted_group, &meta.individuals);
        let strains: Vec<String> = meta
            .individuals
            .iter()
            .filter(|name| !excluded.contains(*name))
            .cloned()
            .collect();
        let mut order: Vec<(String, usize)> = Vec::new();
        for marker in &meta.markers {
            match order.iter_mut().find(|(name, _)| *name == marker.chr) {
                Some((_, count)) => *count += 1,
                None => order.push((marker.chr.clone(), 1)),
            }
        }
        let num_individuals = meta.individuals.len();
        let num_strains = strains.len();
        Ok::<_, genotypes::GenotypeError>(GenotypeDetail {
            group: wanted_group,
            version: resolved.version.clone(),
            file: format!("{}.geno", resolved.version),
            title: listed.0,
            labels: meta
                .labels
                .into_iter()
                .map(|(key, value)| Label { key, value })
                .collect(),
            individuals: meta.individuals,
            num_individuals,
            strains,
            num_strains,
            chromosomes: order
                .into_iter()
                .map(|(name, markers)| Chromosome { name, markers })
                .collect(),
            markers: meta.markers.len(),
            gemma: listed.1,
            rqtl: listed.2,
            current: listed.3,
        })
    })
    .await
    .map_err(|e| {
        ApiError::new(
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            e.to_string(),
            "group_genotype_version",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|e| genotype_error_to_api_error(e, "group_genotype_version", rid))
}

/// A genotype resolution failure, as a caller-facing error.
fn genotype_error_to_api_error(
    error: GenotypeError,
    operation: &str,
    rid: crate::response::RequestInfo,
) -> ApiError {
    let (status, code, title) = match error {
        GenotypeError::Invalid(_) => (
            axum::http::StatusCode::UNPROCESSABLE_ENTITY,
            "invalid_individuals",
            "Unusable individual selection",
        ),
        GenotypeError::NotFound(_) => (
            axum::http::StatusCode::NOT_FOUND,
            "genotypes_not_found",
            "Genotype file not found",
        ),
        GenotypeError::Io(_) => (
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            "genotypes_unreadable",
            "Genotype files could not be read",
        ),
    };
    ApiError::new(status, code, title, error.to_string(), operation).with_request_id(rid)
}

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

    fn version(name: &str, current: bool) -> GenotypeVersion {
        GenotypeVersion {
            file: format!("{name}.geno"),
            version: name.to_string(),
            title: None,
            individuals: 198,
            markers: 20_000,
            gemma: true,
            rqtl: true,
            current,
        }
    }

    #[test]
    fn the_listing_does_not_serialise_a_path() {
        let json = serde_json::to_value(GroupGenotypes {
            group: "BXD".to_string(),
            versions: vec![version("BXD.8", true), version("BXD", false)],
        })
        .unwrap();
        let text = json.to_string();
        assert!(!text.contains('/'), "no path-shaped value: {text}");
        assert_eq!(json["versions"][0]["file"], "BXD.8.geno", "the file name is fine: {text}");
        assert_eq!(json["versions"][0]["version"], "BXD.8");
        assert_eq!(json["versions"][0]["current"], true);
        assert_eq!(json["versions"][1]["current"], false);
    }
}