about summary refs log tree commit diff
path: root/src/routes/traits.rs
blob: 91e7fc825b39eeac550dd46ee6ffde1e92905b8d (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
//! Trait domain endpoints spanning both ProbeSet (expression) and
//! Publish (phenotype) data: a trait is a trait is a trait, addressed
//! the same way as GeneNetwork2's own generic
//! `wqflask.api.router.trait_sample_data`/`get_trait_info` --
//! `(dataset, trait)` -- rather than category-specific paths. See
//! docs/gn-auth.md for why `dataset` is resolved across categories
//! before `trait` is ever looked up (avoids ever having to guess which
//! category a bare trait name/id belongs to).
//!
//! `/groups/{group}/traits...` and `/datasets/{dataset}/probesets...`
//! (src/routes/groups.rs, src/routes/datasets.rs) are untouched by
//! this -- this is an additional, category-spanning way to reach the
//! same underlying data, not a replacement.

use axum::Json;
use axum::extract::Path;
use axum::http::StatusCode;
use serde::Serialize;

use gnauth_macros::gnauth;

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

/// One trait's metadata, tagged by which category its dataset resolved
/// to (db::resolve_trait_dataset). ProbeSetInfo and TraitInfo share
/// little beyond mean/locus/lrs/additive -- gene annotation vs.
/// publication reference -- so this keeps both fully typed rather than
/// collapsing to a lossy common subset.
#[derive(Serialize, utoipa::ToSchema)]
#[serde(tag = "category", rename_all = "snake_case")]
pub enum TraitInfoResponse {
    Probeset(db::ProbeSetInfo),
    Publish(db::TraitInfo),
}

/// Either a database error, or a failure to reach/parse gn-auth's
/// answer while checking authorization for a non-public dataset. Same
/// shape as routes::datasets::DatasetAuthError; not shared with it,
/// matching this codebase's existing per-module lookup/error types
/// (see e.g. GroupTraitLookup vs DatasetProbesetLookup).
enum TraitAuthError {
    Db(db::DbError),
    Auth(String),
}

impl From<db::DbError> for TraitAuthError {
    fn from(e: db::DbError) -> Self {
        TraitAuthError::Db(e)
    }
}

enum TraitsLookup {
    DatasetNotFound,
    Forbidden,
    Found(Authorized, Vec<TraitInfoResponse>),
}

fn get_traits_result(
    dataset: &str,
    auth_server_url: &str,
    token: &AuthToken,
) -> Result<TraitsLookup, TraitAuthError> {
    let dataset = match db::resolve_trait_dataset(dataset)? {
        None => return Ok(TraitsLookup::DatasetNotFound),
        Some(dataset) => dataset,
    };
    match dataset {
        db::TraitDataset::ProbeSet(ds) => {
            let Some(auth) = auth::check(
                auth_server_url,
                token,
                &ds.name,
                None,
                ds.public,
                ds.confidentiality,
                &ds.create_time,
            )
            .map_err(TraitAuthError::Auth)?
            else {
                return Ok(TraitsLookup::Forbidden);
            };
            Ok(TraitsLookup::Found(
                auth,
                db::get_dataset_probesets(ds.id)?
                    .into_iter()
                    .map(TraitInfoResponse::Probeset)
                    .collect(),
            ))
        }
        db::TraitDataset::Publish(pf) => {
            let Some(auth) = auth::check(
                auth_server_url,
                token,
                &pf.name,
                None,
                pf.public,
                pf.confidentiality,
                &pf.create_time,
            )
            .map_err(TraitAuthError::Auth)?
            else {
                return Ok(TraitsLookup::Forbidden);
            };
            Ok(TraitsLookup::Found(
                auth,
                db::get_group_traits(pf.inbred_set_id)?
                    .into_iter()
                    .map(TraitInfoResponse::Publish)
                    .collect(),
            ))
        }
    }
}

#[utoipa::path(get, path = "/traits/{dataset}", summary = "List every trait in a dataset, across ProbeSet and Publish categories", params(
    ("dataset" = String, Path, description = "ProbeSetFreeze Name/Name2/FullName/ShortName/Id, or PublishFreeze Name/ShortName/Id, or (for Publish data) the owning group's Name/InbredSetName/FullName/Id")
), responses(
    (status = 200, description = "Every trait in the dataset, tagged by category", body = Envelope<Vec<TraitInfoResponse>>),
    Unauthorized,
    (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError),
    (status = 404, description = "No matching dataset", body = ApiError),
    (status = 500, description = "Database error", body = ApiError),
    (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError)
))]
pub async fn traits(
    ctx: Ctx,
    Path(dataset): Path<String>,
    token: AuthToken,
) -> Result<Json<Envelope<Vec<TraitInfoResponse>>>, ApiError> {
    let rid = ctx.request_info();
    let not_found_name = dataset.clone();
    let auth_server_url = Config::load().auth_server_url.clone();
    tokio::task::spawn_blocking(move || get_traits_result(&dataset, &auth_server_url, &token))
        .await
        .map_err(|e| {
            ApiError::new(
                StatusCode::INTERNAL_SERVER_ERROR,
                "internal_error",
                "Internal error",
                e.to_string(),
                "traits",
            )
            .with_request_id(rid.clone())
        })?
        .map_err(|e| match e {
            TraitAuthError::Db(e) => {
                ApiError::from_db(e, "traits").with_request_id(rid.clone())
            }
            TraitAuthError::Auth(e) => ApiError::new(
                StatusCode::BAD_GATEWAY,
                "auth_server_error",
                "Could not check authorization",
                e,
                "traits",
            )
            .with_request_id(rid.clone()),
        })
        .and_then(|lookup| match lookup {
            TraitsLookup::Found(_authorized, traits) => {
                Ok(Json(
                    ctx.envelope(traits)
                        .with_note(db::LOD_NOTE)
                        .with_links(crate::suggest::root_links()),
                ))
            }
            TraitsLookup::Forbidden => Err(ApiError::new(
                StatusCode::FORBIDDEN,
                "forbidden",
                "Not authorized",
                format!(
                    "Dataset '{not_found_name}' is not public, and you are not authorized to view it."
                ),
                "traits",
            )
            .with_request_id(rid.clone())),
            TraitsLookup::DatasetNotFound => Err(ApiError::new(
                StatusCode::NOT_FOUND,
                "dataset_not_found",
                "Dataset not found",
                format!("No dataset matching '{not_found_name}'."),
                "traits",
            )
            .with_request_id(rid)),
        })
}

enum TraitInfoLookup {
    DatasetNotFound,
    TraitNotFound,
    Forbidden,
    Found(Authorized, Box<TraitInfoResponse>),
}

fn get_trait_info_result(
    dataset: &str,
    trait_name: &str,
    auth_server_url: &str,
    token: &AuthToken,
) -> Result<TraitInfoLookup, TraitAuthError> {
    let dataset = match db::resolve_trait_dataset(dataset)? {
        None => return Ok(TraitInfoLookup::DatasetNotFound),
        Some(dataset) => dataset,
    };
    match dataset {
        db::TraitDataset::ProbeSet(ds) => {
            let info = match db::get_dataset_probeset_info(ds.id, trait_name)? {
                None => return Ok(TraitInfoLookup::TraitNotFound),
                Some(info) => info,
            };
            let Some(auth) = auth::check(
                auth_server_url,
                token,
                &ds.name,
                Some(trait_name),
                ds.public,
                ds.confidentiality,
                &ds.create_time,
            )
            .map_err(TraitAuthError::Auth)?
            else {
                return Ok(TraitInfoLookup::Forbidden);
            };
            Ok(TraitInfoLookup::Found(
                auth,
                Box::new(TraitInfoResponse::Probeset(info)),
            ))
        }
        db::TraitDataset::Publish(pf) => {
            let Ok(trait_id) = trait_name.parse::<u32>() else {
                return Ok(TraitInfoLookup::TraitNotFound);
            };
            let info = match db::get_group_trait_info(pf.inbred_set_id, trait_id)? {
                None => return Ok(TraitInfoLookup::TraitNotFound),
                Some(info) => info,
            };
            let Some(auth) = auth::check(
                auth_server_url,
                token,
                &pf.name,
                Some(trait_name),
                pf.public,
                pf.confidentiality,
                &pf.create_time,
            )
            .map_err(TraitAuthError::Auth)?
            else {
                return Ok(TraitInfoLookup::Forbidden);
            };
            Ok(TraitInfoLookup::Found(
                auth,
                Box::new(TraitInfoResponse::Publish(info)),
            ))
        }
    }
}

#[utoipa::path(get, path = "/traits/{dataset}/{trait}", summary = "Get one trait's metadata, across ProbeSet and Publish categories", params(
    ("dataset" = String, Path, description = "ProbeSetFreeze Name/Name2/FullName/ShortName/Id, or PublishFreeze Name/ShortName/Id, or (for Publish data) the owning group's Name/InbredSetName/FullName/Id"),
    ("trait" = String, Path, description = "ProbeSet.Name (ProbeSet category) or PublishXRef.Id (Publish category)")
), responses(
    (status = 200, description = "The trait's metadata, tagged by category", body = Envelope<TraitInfoResponse>),
    Unauthorized,
    (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError),
    (status = 404, description = "No matching dataset, or no matching trait in that dataset", body = ApiError),
    (status = 500, description = "Database error", body = ApiError),
    (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError)
))]
pub async fn trait_info(
    ctx: Ctx,
    Path((dataset, trait_name)): Path<(String, String)>,
    token: AuthToken,
) -> Result<Json<Envelope<TraitInfoResponse>>, ApiError> {
    let rid = ctx.request_info();
    let not_found_dataset = dataset.clone();
    let not_found_trait = trait_name.clone();
    let auth_server_url = Config::load().auth_server_url.clone();
    tokio::task::spawn_blocking(move || {
        get_trait_info_result(&dataset, &trait_name, &auth_server_url, &token)
    })
    .await
    .map_err(|e| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            e.to_string(),
            "trait_info",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|e| match e {
        TraitAuthError::Db(e) => ApiError::from_db(e, "trait_info").with_request_id(rid.clone()),
        TraitAuthError::Auth(e) => ApiError::new(
            StatusCode::BAD_GATEWAY,
            "auth_server_error",
            "Could not check authorization",
            e,
            "trait_info",
        )
        .with_request_id(rid.clone()),
    })
    .and_then(|lookup| match lookup {
        TraitInfoLookup::Found(_authorized, info) => {
            let base = format!(
                "/traits/{}/{}",
                path_segment(&not_found_dataset),
                path_segment(&not_found_trait)
            );
            let pubmed_id = match &*info {
                TraitInfoResponse::Publish(info) => info.pubmed_id,
                TraitInfoResponse::Probeset(_) => None,
            };
            let mut envelope = ctx.envelope(*info).with_note(db::LOD_NOTE).with_next(
                &format!("{base}/values"),
                "The trait's value in each strain",
            );
            if let Some(pubmed_id) = pubmed_id {
                envelope = envelope.with_next(
                    &format!("/publications/{pubmed_id}/traits"),
                    "Every trait reported by this trait's publication",
                );
            }
            Ok(Json(envelope.with_links(crate::suggest::root_links())))
        }
        TraitInfoLookup::Forbidden => Err(ApiError::new(
            StatusCode::FORBIDDEN,
            "forbidden",
            "Not authorized",
            format!(
                "'{not_found_trait}' in dataset '{not_found_dataset}' is not public, \
                     and you are not authorized to view it."
            ),
            "trait_info",
        )
        .with_request_id(rid.clone())),
        TraitInfoLookup::DatasetNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "dataset_not_found",
            "Dataset not found",
            format!("No dataset matching '{not_found_dataset}'."),
            "trait_info",
        )
        .with_request_id(rid.clone())),
        TraitInfoLookup::TraitNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "trait_not_found",
            "Trait not found",
            format!("No trait '{not_found_trait}' in dataset '{not_found_dataset}'."),
            "trait_info",
        )
        .with_request_id(rid)),
    })
}

enum TraitValuesLookup {
    DatasetNotFound,
    TraitNotFound,
    Forbidden,
    /// The values, plus the owning group's name when the dataset belongs to
    /// one -- the links offered are `/groups/...` paths, and a dataset name is
    /// not a group name (BXDPublish's traits live in BXD).
    Found(Authorized, Vec<db::TraitValue>, Option<String>),
}

fn get_trait_values_result(
    dataset: &str,
    trait_name: &str,
    auth_server_url: &str,
    token: &AuthToken,
) -> Result<TraitValuesLookup, TraitAuthError> {
    let dataset = match db::resolve_trait_dataset(dataset)? {
        None => return Ok(TraitValuesLookup::DatasetNotFound),
        Some(dataset) => dataset,
    };
    match dataset {
        db::TraitDataset::ProbeSet(ds) => {
            let values = db::get_dataset_probeset_values(ds.id, trait_name)?;
            if values.is_empty() {
                return Ok(TraitValuesLookup::TraitNotFound);
            }
            let Some(auth) = auth::check(
                auth_server_url,
                token,
                &ds.name,
                Some(trait_name),
                ds.public,
                ds.confidentiality,
                &ds.create_time,
            )
            .map_err(TraitAuthError::Auth)?
            else {
                return Ok(TraitValuesLookup::Forbidden);
            };
            Ok(TraitValuesLookup::Found(
                auth,
                values
                    .into_iter()
                    .map(|v| db::TraitValue {
                        name: v.name,
                        value: v.value,
                    })
                    .collect(),
                Some(ds.name.clone()),
            ))
        }
        db::TraitDataset::Publish(pf) => {
            let Ok(trait_id) = trait_name.parse::<u32>() else {
                return Ok(TraitValuesLookup::TraitNotFound);
            };
            let values = db::get_group_trait_values(pf.inbred_set_id, trait_id)?;
            if values.is_empty() {
                return Ok(TraitValuesLookup::TraitNotFound);
            }
            let Some(auth) = auth::check(
                auth_server_url,
                token,
                &pf.name,
                Some(trait_name),
                pf.public,
                pf.confidentiality,
                &pf.create_time,
            )
            .map_err(TraitAuthError::Auth)?
            else {
                return Ok(TraitValuesLookup::Forbidden);
            };
            let group = db::get_group_name(pf.inbred_set_id)?;
            Ok(TraitValuesLookup::Found(auth, values, group))
        }
    }
}

#[utoipa::path(get, path = "/traits/{dataset}/{trait}/values", summary = "Get one trait's value in each strain, across ProbeSet and Publish categories", params(
    ("dataset" = String, Path, description = "ProbeSetFreeze Name/Name2/FullName/ShortName/Id, or PublishFreeze Name/ShortName/Id, or (for Publish data) the owning group's Name/InbredSetName/FullName/Id"),
    ("trait" = String, Path, description = "ProbeSet.Name (ProbeSet category) or PublishXRef.Id (Publish category)")
), responses(
    (status = 200, description = "The trait's per-strain values", body = Envelope<Vec<db::TraitValue>>),
    Unauthorized,
    (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError),
    (status = 404, description = "No matching dataset, or no matching trait in that dataset", body = ApiError),
    (status = 500, description = "Database error", body = ApiError),
    (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError)
))]
#[gnauth(secured)]
pub async fn trait_values(
    ctx: Ctx,
    Path((dataset, trait_name)): Path<(String, String)>,
    token: AuthToken,
) -> Result<Json<Envelope<Vec<db::TraitValue>>>, ApiError> {
    let rid = ctx.request_info();
    let not_found_dataset = dataset.clone();
    let not_found_trait = trait_name.clone();
    let auth_server_url = Config::load().auth_server_url.clone();
    tokio::task::spawn_blocking(move || {
        get_trait_values_result(&dataset, &trait_name, &auth_server_url, &token)
    })
    .await
    .map_err(|e| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            e.to_string(),
            "trait_values",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|e| match e {
        TraitAuthError::Db(e) => ApiError::from_db(e, "trait_values").with_request_id(rid.clone()),
        TraitAuthError::Auth(e) => ApiError::new(
            StatusCode::BAD_GATEWAY,
            "auth_server_error",
            "Could not check authorization",
            e,
            "trait_values",
        )
        .with_request_id(rid.clone()),
    })
    .and_then(|lookup| match lookup {
        TraitValuesLookup::Found(authorized, values, group) => {
            let _: Authorized = authorized;
            let actions = suggest::mapping_actions_for(
                &values,
                &format!("{}::{}", not_found_dataset, not_found_trait),
            );
            // Group paths take the group's own name, not the dataset's: the
            // dataset here may be BXDPublish, whose group is BXD, and
            // `/groups/BXDPublish/phewas` is a 404 (no genotype files for it).
            // When the dataset has no group at all (a ProbeSet dataset whose
            // ProbeFreeze names none), the group links are simply absent.
            let group_links: Vec<suggest::Link> = group
                .as_deref()
                .map(|group| {
                    vec![
                        (
                            // A bare `/phewas` is a 422 (`give either locus,
                            // or chr and mb`), so the link is a shape with
                            // placeholders -- the same convention as
                            // `/markers/{marker}/classes?trait={trait_id}`:
                            // the description says what to fill in, and
                            // tests/envelope.rs skips hrefs with braces on
                            // that condition.
                            format!(
                                "/groups/{}/phewas?chr={{chr}}&mb={{mb}}",
                                path_segment(group)
                            ),
                            "PheWAS: this group's traits peaking near one locus; fill in chr \
                             and mb (e.g. chr=1&mb=50)",
                        ),
                        (
                            format!("/groups/{}/genotypes", path_segment(group)),
                            "The genotype versions these values can be mapped against",
                        ),
                        (
                            format!("/groups/{}/traits", path_segment(group)),
                            "The group's other published traits",
                        ),
                    ]
                })
                .unwrap_or_default();
            // No `next` link for correlation: it is a POST
            // (`/compute/correlation`) and this reply already carries it in
            // `actions`. A GET `next` here was a 404 -- `tests/envelope.rs`
            // follows every link offered.
            Ok(Json(
                ctx.envelope(values)
                    .with_actions(actions)
                    .with_next(
                        &format!(
                            "/traits/{}/{}",
                            path_segment(&not_found_dataset),
                            path_segment(&not_found_trait)
                        ),
                        "The trait's metadata",
                    )
                    .with_links(group_links)
                    .with_links(crate::suggest::root_links()),
            ))
        }
        TraitValuesLookup::Forbidden => Err(ApiError::new(
            StatusCode::FORBIDDEN,
            "forbidden",
            "Not authorized",
            format!(
                "'{not_found_trait}' in dataset '{not_found_dataset}' is not public, \
                     and you are not authorized to view it."
            ),
            "trait_values",
        )
        .with_request_id(rid.clone())),
        TraitValuesLookup::DatasetNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "dataset_not_found",
            "Dataset not found",
            format!("No dataset matching '{not_found_dataset}'."),
            "trait_values",
        )
        .with_request_id(rid.clone())),
        TraitValuesLookup::TraitNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "trait_not_found",
            "Trait not found",
            format!("No trait '{not_found_trait}' in dataset '{not_found_dataset}'."),
            "trait_values",
        )
        .with_request_id(rid)),
    })
}