about summary refs log tree commit diff
path: root/src/routes/datasets.rs
blob: 1835b4c3fe09a027522f5ed422a7d185c781a4ac (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
//! Expression (ProbeSet) dataset domain endpoints: read-only access to
//! the ProbeSetFreeze/ProbeSetXRef/ProbeSet tables.

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

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;

#[utoipa::path(get, path = "/datasets/{dataset}", summary = "Get one expression dataset's full record by name or numeric id", params(
    ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id")
), responses(
    (status = 200, description = "The matching row of the ProbeSetFreeze table", body = Envelope<db::Dataset>),
    Unauthorized,
    (status = 404, description = "No matching dataset", body = ApiError),
    (status = 500, description = "Database error", body = ApiError)
))]
#[gnauth(token_only)]
pub async fn dataset_by_name(
    ctx: Ctx,
    Path(dataset): Path<String>,
    _token: AuthToken,
) -> Result<Json<Envelope<db::Dataset>>, ApiError> {
    let rid = ctx.request_info();
    let not_found_name = dataset.clone();
    tokio::task::spawn_blocking(move || db::get_dataset_by_name(&dataset))
        .await
        .map_err(|e| {
            ApiError::new(
                StatusCode::INTERNAL_SERVER_ERROR,
                "internal_error",
                "Internal error",
                e.to_string(),
                "dataset_by_name",
            )
            .with_request_id(rid.clone())
        })?
        .map_err(|e| ApiError::from_db(e, "dataset_by_name").with_request_id(rid.clone()))?
        .map(|dataset| {
            Json(
                ctx.envelope(dataset)
                    .with_next(
                        &format!("/datasets/{}/probesets", path_segment(&not_found_name)),
                        "The expression traits (probesets) of this dataset (can be very \
                         large); append /<probeset> to one of them for its metadata",
                    )
                    .with_links(crate::suggest::root_links()),
            )
        })
        .ok_or_else(|| {
            ApiError::new(
                StatusCode::NOT_FOUND,
                "dataset_not_found",
                "Dataset not found",
                format!("No dataset matching '{not_found_name}'."),
                "dataset_by_name",
            )
            .with_request_id(rid)
        })
}

/// What looking up and authorizing a dataset's probeset listing found.
/// Unlike [`DatasetProbesetLookup`], there's no single probeset to miss
/// -- a dataset with zero probesets is just an empty `Found(vec![])` --
/// but there is still a dataset-level `Forbidden` outcome.
enum DatasetProbesetsLookup {
    DatasetNotFound,
    Forbidden,
    Found(Authorized, Vec<db::ProbeSetInfo>),
}

fn get_dataset_probesets_result(
    dataset: &str,
    auth_server_url: &str,
    token: &AuthToken,
) -> Result<DatasetProbesetsLookup, DatasetAuthError> {
    let dataset = match db::get_dataset_by_name(dataset)? {
        None => return Ok(DatasetProbesetsLookup::DatasetNotFound),
        Some(dataset) => dataset,
    };
    let Some(auth) = auth::check(
        auth_server_url,
        token,
        &dataset.name,
        None,
        dataset.public,
        dataset.confidentiality,
        &dataset.create_time,
    )
    .map_err(DatasetAuthError::Auth)?
    else {
        return Ok(DatasetProbesetsLookup::Forbidden);
    };
    Ok(DatasetProbesetsLookup::Found(
        auth,
        db::get_dataset_probesets(dataset.id)?,
    ))
}

#[utoipa::path(get, path = "/datasets/{dataset}/probesets", summary = "List the expression (ProbeSet) traits belonging to a dataset", params(
    ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id")
), responses(
    (status = 200, description = "The probesets' ProbeSetXRef/ProbeSet metadata", body = Envelope<Vec<db::ProbeSetInfo>>),
    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 dataset_probesets(
    ctx: Ctx,
    Path(dataset): Path<String>,
    token: AuthToken,
) -> Result<Json<Envelope<Vec<db::ProbeSetInfo>>>, 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_dataset_probesets_result(&dataset, &auth_server_url, &token)
    })
    .await
    .map_err(|e| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            e.to_string(),
            "dataset_probesets",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|e| match e {
        DatasetAuthError::Db(e) => {
            ApiError::from_db(e, "dataset_probesets").with_request_id(rid.clone())
        }
        DatasetAuthError::Auth(e) => ApiError::new(
            StatusCode::BAD_GATEWAY,
            "auth_server_error",
            "Could not check authorization",
            e,
            "dataset_probesets",
        )
        .with_request_id(rid.clone()),
    })
    .and_then(|lookup| match lookup {
        DatasetProbesetsLookup::Found(_authorized, probesets) => Ok(Json(
            ctx.envelope(probesets)
                .with_note(db::LOD_NOTE)
                .with_next(
                    &format!("/datasets/{}", path_segment(&not_found_name)),
                    "The dataset these probesets belong to",
                )
                .with_next(
                    &format!("/datasets/{}/probesets/{{probeset}}/values", path_segment(&not_found_name)),
                    "One probeset's value per strain, with the mapping suggestions",
                )
                .with_links(crate::suggest::root_links()),
        )),
        DatasetProbesetsLookup::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."
            ),
            "dataset_probesets",
        )
        .with_request_id(rid.clone())),
        DatasetProbesetsLookup::DatasetNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "dataset_not_found",
            "Dataset not found",
            format!("No dataset matching '{not_found_name}'."),
            "dataset_probesets",
        )
        .with_request_id(rid)),
    })
}

/// What looking up and authorizing a probeset trait within a dataset
/// found, the expression-dataset equivalent of GroupTraitLookup above.
/// `Forbidden` covers "the dataset isn't public and the caller isn't
/// authorized for it" -- both `dataset_probeset_info` and
/// `dataset_probeset_values` gate on gn-auth.
enum DatasetProbesetLookup<T> {
    DatasetNotFound,
    ProbesetNotFound,
    Forbidden,
    Found(Authorized, T),
}

/// Either a database error, or a failure to reach/parse gn-auth's
/// answer while checking authorization for a non-public dataset.
enum DatasetAuthError {
    Db(db::DbError),
    Auth(String),
}

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

fn get_dataset_probeset_info_result(
    dataset: &str,
    probeset: &str,
    auth_server_url: &str,
    token: &AuthToken,
) -> Result<DatasetProbesetLookup<db::ProbeSetInfo>, DatasetAuthError> {
    let dataset = match db::get_dataset_by_name(dataset)? {
        None => return Ok(DatasetProbesetLookup::DatasetNotFound),
        Some(dataset) => dataset,
    };
    let info = match db::get_dataset_probeset_info(dataset.id, probeset)? {
        None => return Ok(DatasetProbesetLookup::ProbesetNotFound),
        Some(info) => info,
    };
    let Some(auth) = auth::check(
        auth_server_url,
        token,
        &dataset.name,
        Some(&info.name),
        dataset.public,
        dataset.confidentiality,
        &dataset.create_time,
    )
    .map_err(DatasetAuthError::Auth)?
    else {
        return Ok(DatasetProbesetLookup::Forbidden);
    };
    Ok(DatasetProbesetLookup::Found(auth, info))
}

#[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}", summary = "Get one expression trait's ProbeSetXRef/ProbeSet metadata", params(
    ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id"),
    ("probeset" = String, Path, description = "ProbeSet.Name within the dataset")
), responses(
    (status = 200, description = "The probeset's ProbeSetXRef/ProbeSet metadata", body = Envelope<db::ProbeSetInfo>),
    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 probeset 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 dataset_probeset_info(
    ctx: Ctx,
    Path((dataset, probeset)): Path<(String, String)>,
    token: AuthToken,
) -> Result<Json<Envelope<db::ProbeSetInfo>>, ApiError> {
    let rid = ctx.request_info();
    let not_found_dataset = dataset.clone();
    let not_found_probeset = probeset.clone();
    let auth_server_url = Config::load().auth_server_url.clone();
    tokio::task::spawn_blocking(move || {
        get_dataset_probeset_info_result(&dataset, &probeset, &auth_server_url, &token)
    })
    .await
    .map_err(|e| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            e.to_string(),
            "dataset_probeset_info",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|e| match e {
        DatasetAuthError::Db(e) => {
            ApiError::from_db(e, "dataset_probeset_info").with_request_id(rid.clone())
        }
        DatasetAuthError::Auth(e) => ApiError::new(
            StatusCode::BAD_GATEWAY,
            "auth_server_error",
            "Could not check authorization",
            e,
            "dataset_probeset_info",
        )
        .with_request_id(rid.clone()),
    })
    .and_then(|lookup| match lookup {
        DatasetProbesetLookup::Found(_authorized, info) => {
            let dataset = path_segment(&not_found_dataset);
            let probeset = path_segment(&not_found_probeset);
            Ok(Json(
                ctx.envelope(info)
                    .with_note(db::LOD_NOTE)
                    .with_next(
                        &format!("/datasets/{dataset}/probesets/{probeset}/values"),
                        "The probeset's value in each strain",
                    )
                    .with_next(
                        &format!("/datasets/{dataset}"),
                        "The dataset this probeset belongs to",
                    )
                    .with_next(
                        &format!("/publications/{{pubmed_id}}/traits"),
                        "Every trait this probeset's publication reports",
                    )
                    .with_links(crate::suggest::root_links()),
            ))
        }
        DatasetProbesetLookup::Forbidden => Err(ApiError::new(
            StatusCode::FORBIDDEN,
            "forbidden",
            "Not authorized",
            format!(
                "'{not_found_probeset}' in dataset '{not_found_dataset}' is not public, \
                     and you are not authorized to view it."
            ),
            "dataset_probeset_info",
        )
        .with_request_id(rid.clone())),
        DatasetProbesetLookup::DatasetNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "dataset_not_found",
            "Dataset not found",
            format!("No dataset matching '{not_found_dataset}'."),
            "dataset_probeset_info",
        )
        .with_request_id(rid.clone())),
        DatasetProbesetLookup::ProbesetNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "probeset_not_found",
            "Probeset not found",
            format!("No probeset '{not_found_probeset}' in dataset '{not_found_dataset}'."),
            "dataset_probeset_info",
        )
        .with_request_id(rid)),
    })
}

fn get_dataset_probeset_values_result(
    dataset: &str,
    probeset: &str,
    auth_server_url: &str,
    token: &AuthToken,
) -> Result<DatasetProbesetLookup<Vec<db::ProbeSetValue>>, DatasetAuthError> {
    let dataset = match db::get_dataset_by_name(dataset)? {
        None => return Ok(DatasetProbesetLookup::DatasetNotFound),
        Some(dataset) => dataset,
    };
    let values = db::get_dataset_probeset_values(dataset.id, probeset)?;
    if values.is_empty() {
        return Ok(DatasetProbesetLookup::ProbesetNotFound);
    }
    let Some(auth) = auth::check(
        auth_server_url,
        token,
        &dataset.name,
        Some(probeset),
        dataset.public,
        dataset.confidentiality,
        &dataset.create_time,
    )
    .map_err(DatasetAuthError::Auth)?
    else {
        return Ok(DatasetProbesetLookup::Forbidden);
    };
    Ok(DatasetProbesetLookup::Found(auth, values))
}

#[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}/values", summary = "Get one expression trait's value in each strain in the dataset", params(
    ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id"),
    ("probeset" = String, Path, description = "ProbeSet.Name within the dataset")
), responses(
    (status = 200, description = "The dataset's per-strain values for the probeset", body = Envelope<Vec<db::ProbeSetValue>>),
    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 probeset 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 dataset_probeset_values(
    ctx: Ctx,
    Path((dataset, probeset)): Path<(String, String)>,
    token: AuthToken,
) -> Result<Json<Envelope<Vec<db::ProbeSetValue>>>, ApiError> {
    let rid = ctx.request_info();
    let not_found_dataset = dataset.clone();
    let not_found_probeset = probeset.clone();
    let auth_server_url = Config::load().auth_server_url.clone();
    tokio::task::spawn_blocking(move || {
        get_dataset_probeset_values_result(&dataset, &probeset, &auth_server_url, &token)
    })
    .await
    .map_err(|e| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            e.to_string(),
            "dataset_probeset_values",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|e| match e {
        DatasetAuthError::Db(e) => {
            ApiError::from_db(e, "dataset_probeset_values").with_request_id(rid.clone())
        }
        DatasetAuthError::Auth(e) => ApiError::new(
            StatusCode::BAD_GATEWAY,
            "auth_server_error",
            "Could not check authorization",
            e,
            "dataset_probeset_values",
        )
        .with_request_id(rid.clone()),
    })
    .and_then(|lookup| match lookup {
        DatasetProbesetLookup::Found(authorized, values) => {
            let _: Authorized = authorized;
            let actions = suggest::mapping_actions_for(
                &values,
                &format!("{}::{}", not_found_dataset, not_found_probeset),
            );
            Ok(Json(
                ctx.envelope(values)
                    .with_actions(actions)
                    .with_next(
                        &format!(
                            "/datasets/{}/probesets/{}",
                            path_segment(&not_found_dataset),
                            path_segment(&not_found_probeset)
                        ),
                        "The probeset's metadata",
                    )
                    .with_next(
                        &format!("/datasets/{}/probesets", path_segment(&not_found_dataset)),
                        "The other probesets of this dataset",
                    )
                    .with_links(crate::suggest::root_links()),
            ))
        }
        DatasetProbesetLookup::Forbidden => Err(ApiError::new(
            StatusCode::FORBIDDEN,
            "forbidden",
            "Not authorized",
            format!(
                "'{not_found_probeset}' in dataset '{not_found_dataset}' is not public, \
                     and you are not authorized to view it."
            ),
            "dataset_probeset_values",
        )
        .with_request_id(rid.clone())),
        DatasetProbesetLookup::DatasetNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "dataset_not_found",
            "Dataset not found",
            format!("No dataset matching '{not_found_dataset}'."),
            "dataset_probeset_values",
        )
        .with_request_id(rid.clone())),
        DatasetProbesetLookup::ProbesetNotFound => Err(ApiError::new(
            StatusCode::NOT_FOUND,
            "probeset_not_found",
            "Probeset not found",
            format!("No probeset '{not_found_probeset}' in dataset '{not_found_dataset}'."),
            "dataset_probeset_values",
        )
        .with_request_id(rid)),
    })
}