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
|
//! `GET|POST /baskets`, `GET|PATCH|DELETE /baskets/{name}`: a user's own
//! column of values, in their own SQLite file.
//!
//! A basket is how a user changes data without changing the database: take a
//! trait's values, edit one or more of them (or build a covariate column that
//! does not exist), keep it under a name, and map *that* instead. MariaDB is
//! never written to; the only thing that grows is a per-user SQLite file
//! (`BASKET_DIR/<sha256(sub)>.sqlite`, 0600).
//!
//! The full column is stored, not a diff: the client has the original beside
//! it and the comparison is its business, while a mapping needs one complete
//! column. Values are kept as text with a parsed copy beside them, so `NA` and
//! `0` stay different claims, and a column with something that is neither a
//! number nor a missing marker is refused by name rather than silently
//! dropped.
//!
//! Every edit bumps `revision` and changes `digest`; a mapping reply records
//! both, so two runs on one basket name can never differ silently.
use axum::Json;
use axum::extract::{Path, Query};
use axum::http::StatusCode;
use serde::Deserialize;
use serde_json::Value;
use gnauth_macros::gnauth;
use crate::auth::AuthToken;
use crate::baskets::{self, BasketError, BasketInfo};
use crate::config::Config;
use crate::error::{ApiError, Unauthorized};
use crate::response::{Ctx, Envelope, RequestInfo};
/// One value as posted: a number, a string (`"NA"`), or null for missing.
#[derive(Deserialize, utoipa::ToSchema)]
pub struct PostedValue {
pub name: String,
#[schema(value_type = Object)]
pub value: Option<Value>,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct CreateBasket {
/// URL-safe, unique per user: letters, digits, `-`, `_`, `.`.
pub name: String,
/// `trait` (default) or `covariate`.
pub kind: Option<String>,
/// What this column is and why it was changed.
pub description: Option<String>,
/// The column itself: one value per sample.
pub values: Vec<PostedValue>,
/// Where the column came from, for provenance (`/baskets/{name}` echoes
/// it): the published trait it started as.
pub base_dataset: Option<String>,
pub base_trait: Option<u32>,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct ReviseBasket {
/// The complete replacement column: a revision replaces, it does not
/// merge, so a caller cannot silently keep a value it meant to drop.
pub values: Vec<PostedValue>,
}
#[derive(Deserialize, utoipa::IntoParams)]
pub struct RevisionQuery {
/// A specific stored revision; absent means the current one.
pub revision: Option<i64>,
}
#[derive(Deserialize, utoipa::IntoParams)]
pub struct BasketQuery {
/// Include the column? `/baskets/{name}/values` is the shaped way to ask.
#[serde(default)]
pub values: Option<bool>,
}
/// Turn posted values into the text the store keeps.
fn posted(values: &[PostedValue]) -> Result<Vec<(String, Option<String>)>, ApiError> {
let mut named = Vec::with_capacity(values.len());
for posted in values {
let raw = match &posted.value {
None | Some(Value::Null) => None,
Some(Value::Number(number)) => Some(number.to_string()),
Some(Value::String(text)) => Some(text.clone()),
Some(other) => {
return Err(ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"invalid_value",
"Invalid value",
format!(
"'{}': a value must be a number, a string or null (for missing), not {other}",
posted.name
),
"baskets",
));
}
};
named.push((posted.name.clone(), raw));
}
Ok(named)
}
fn map_error(error: BasketError, rid: RequestInfo) -> ApiError {
match error {
BasketError::NotFound(message) => ApiError::new(
StatusCode::NOT_FOUND,
"basket_not_found",
"Basket not found",
message,
"baskets",
)
.with_request_id(rid),
BasketError::Invalid(message) => ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"invalid_basket",
"Invalid basket",
message,
"baskets",
)
.with_request_id(rid),
BasketError::Store(message) => ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"basket_store_error",
"The basket store failed",
message,
"baskets",
)
.with_request_id(rid),
}
}
#[utoipa::path(get, path = "/baskets",
summary = "This user's baskets, newest first",
description = "The columns this token's user has stored: a name, whether it is a trait or a \
covariate column, where it came from, its description, its revision and the digest of its \
values. Baskets are private to their owner -- each user has their own SQLite file -- and no \
other user's baskets are visible here.",
responses(
(status = 200, description = "Every basket of this user", body = Envelope<Vec<BasketInfo>>),
Unauthorized
)
)]
#[gnauth(token_only)]
pub async fn list_baskets(
ctx: Ctx,
_token: AuthToken,
) -> Result<Json<Envelope<Vec<BasketInfo>>>, ApiError> {
let rid = ctx.request_info();
let owner = _token.sub.clone();
let dir = Config::load().basket_dir;
let baskets = tokio::task::spawn_blocking(move || {
baskets::list(std::path::Path::new(&dir), &owner)
})
.await
.map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))?
.map_err(|error| map_error(error, rid.clone()))?;
let mut envelope = ctx
.envelope(baskets)
.with_note("Baskets are yours: they live in your own SQLite file, not in GeneNetwork's \
database.")
.with_note("A mapping can name one instead of posting values: POST /compute/qtl2 with \
\"basket\": \"<name>\".");
envelope = envelope.with_links(crate::suggest::root_links());
Ok(Json(envelope))
}
#[utoipa::path(post, path = "/baskets",
summary = "Create a basket from a column of values",
description = "Store a complete column -- a trait's values with some of them changed, or a \
covariate -- under a name. Values are kept as text with a parsed copy, so \"NA\" and 0 stay \
different claims; a column containing something that is neither a number nor a missing marker \
(NA, x, -, ., ?) is refused with the offending samples named.",
request_body = CreateBasket,
responses(
(status = 201, description = "The stored basket", body = Envelope<BasketInfo>),
Unauthorized,
(status = 422, description = "An invalid name or value", body = ApiError)
)
)]
#[gnauth(token_only)]
pub async fn create_basket(
ctx: Ctx,
token: AuthToken,
Json(request): Json<CreateBasket>,
) -> Result<(StatusCode, Json<Envelope<BasketInfo>>), ApiError> {
let rid = ctx.request_info();
let owner = token.sub.clone();
let dir = Config::load().basket_dir;
let named = posted(&request.values)?;
let kind = request.kind.clone().unwrap_or_else(|| "trait".to_string());
let cells = baskets::cells(&named).map_err(|error| map_error(error, rid.clone()))?;
let name = request.name.clone();
let description = request.description.clone();
let base = request
.base_dataset
.clone()
.map(|dataset| (dataset, request.base_trait.unwrap_or_default()));
let stored = tokio::task::spawn_blocking(move || {
baskets::create(
std::path::Path::new(&dir),
&owner,
&name,
&kind,
base.as_ref().map(|(dataset, trait_id)| (dataset.as_str(), *trait_id)),
description.as_deref(),
&cells,
)
})
.await
.map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))?
.map_err(|error| map_error(error, rid.clone()))?;
let mut envelope = ctx.envelope(stored).with_note(
"Stored. Edit it with PATCH (a new revision, a new digest) and map it with \
POST /compute/qtl2 {\"basket\": \"<name>\"}.",
);
envelope = envelope.with_links(crate::suggest::root_links());
Ok((StatusCode::CREATED, Json(envelope)))
}
#[utoipa::path(get, path = "/baskets/{name}",
summary = "One basket's metadata",
description = "The name, kind, provenance, description, revision, digest and cell counts. \
The values themselves are at /baskets/{name}/values.",
params(("name" = String, Path, description = "Basket name"), BasketQuery),
responses(
(status = 200, description = "The basket", body = Envelope<BasketInfo>),
Unauthorized,
(status = 404, description = "No such basket for this user", body = ApiError)
)
)]
#[gnauth(token_only)]
pub async fn get_basket(
ctx: Ctx,
token: AuthToken,
Path(name): Path<String>,
) -> Result<Json<Envelope<BasketInfo>>, ApiError> {
let rid = ctx.request_info();
let owner = token.sub.clone();
let dir = Config::load().basket_dir;
let wanted = name.clone();
let stored = tokio::task::spawn_blocking(move || {
baskets::get(std::path::Path::new(&dir), &owner, &wanted, false)
})
.await
.map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))?
.map_err(|error| map_error(error, rid.clone()))?;
let links = vec![(
format!("/baskets/{}/values", crate::response::path_segment(&name)),
"This basket's column (sample, raw, value, status)",
)];
let mut envelope = ctx
.envelope(stored)
.with_note("`revision` and `digest` identify these exact values: a mapping reply records \
them, so an edit cannot make two runs look alike.")
.with_note("Map it: POST /compute/qtl2 with \"basket\": \"<name>\" in place of `samples`.");
envelope = envelope.with_links(links);
Ok(Json(envelope))
}
#[utoipa::path(get, path = "/baskets/{name}/values",
summary = "One basket's column",
description = "The stored cells: sample, what was typed (`raw`, absent when explicitly \
missing), the parsed number and the status (`ok`, `missing`). Positional rows; meta.columns \
names them.",
params(("name" = String, Path, description = "Basket name")),
responses(
(status = 200, description = "The cells, positional (meta.columns names them)", body = Envelope<Value>),
Unauthorized,
(status = 404, description = "No such basket for this user", body = ApiError)
)
)]
#[gnauth(token_only)]
pub async fn basket_values(
ctx: Ctx,
token: AuthToken,
Path(name): Path<String>,
Query(params): Query<RevisionQuery>,
) -> Result<Json<Envelope<Value>>, ApiError> {
let rid = ctx.request_info();
let owner = token.sub.clone();
let dir = Config::load().basket_dir;
let wanted = name.clone();
let revision = params.revision;
let cells = tokio::task::spawn_blocking(move || {
baskets::cells_of(std::path::Path::new(&dir), &owner, &wanted, revision)
})
.await
.map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))?
.map_err(|error| map_error(error, rid.clone()))?;
let rows: Vec<Value> = cells
.iter()
.map(|cell| {
serde_json::json!([cell.sample, cell.raw, cell.value, cell.status])
})
.collect();
let num_rows = rows.len();
let mut envelope = ctx
.envelope(Value::Array(rows))
.with_columns(
["sample", "raw", "value", "status"]
.iter()
.map(|name| name.to_string())
.collect(),
num_rows,
)
.with_note("`raw` is what was typed, `value` the parsed number, `status` which it is.");
envelope = envelope.with_next(
&format!("/baskets/{}", crate::response::path_segment(&name)),
"This basket's metadata (revision, digest)",
);
Ok(Json(envelope))
}
#[utoipa::path(patch, path = "/baskets/{name}",
summary = "Replace a basket's column with a new revision",
description = "The complete new column. A revision replaces, it does not merge: a caller \
cannot keep a value by leaving it out. The basket's revision is bumped and its digest changes, \
which is what keeps two mappings on one name distinguishable.",
params(("name" = String, Path, description = "Basket name")),
request_body = ReviseBasket,
responses(
(status = 200, description = "The revised basket", body = Envelope<BasketInfo>),
Unauthorized,
(status = 404, description = "No such basket for this user", body = ApiError),
(status = 422, description = "An invalid value", body = ApiError)
)
)]
#[gnauth(token_only)]
pub async fn revise_basket(
ctx: Ctx,
token: AuthToken,
Path(name): Path<String>,
Json(request): Json<ReviseBasket>,
) -> Result<Json<Envelope<BasketInfo>>, ApiError> {
let rid = ctx.request_info();
let owner = token.sub.clone();
let dir = Config::load().basket_dir;
let named = posted(&request.values)?;
let cells = baskets::cells(&named).map_err(|error| map_error(error, rid.clone()))?;
let wanted = name.clone();
let stored = tokio::task::spawn_blocking(move || {
baskets::revise(std::path::Path::new(&dir), &owner, &wanted, &cells)
})
.await
.map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))?
.map_err(|error| map_error(error, rid.clone()))?;
let mut envelope = ctx.envelope(stored).with_note(
"The revision moved, so this is a new column as far as a mapping is concerned: the old \
revision's digest is not this one's.",
);
envelope = envelope.with_links(crate::suggest::root_links());
Ok(Json(envelope))
}
#[utoipa::path(delete, path = "/baskets/{name}",
summary = "Delete a basket",
description = "Removes the basket and its column. A mapping that named it can no longer be \
reproduced, so export the values first if that matters.",
params(("name" = String, Path, description = "Basket name")),
responses(
(status = 204, description = "Deleted"),
Unauthorized,
(status = 404, description = "No such basket for this user", body = ApiError)
)
)]
#[gnauth(token_only)]
pub async fn delete_basket(
ctx: Ctx,
token: AuthToken,
Path(name): Path<String>,
) -> Result<StatusCode, ApiError> {
let rid = ctx.request_info();
let owner = token.sub.clone();
let dir = Config::load().basket_dir;
let wanted = name.clone();
tokio::task::spawn_blocking(move || {
baskets::delete(std::path::Path::new(&dir), &owner, &wanted)
})
.await
.map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))?
.map_err(|error| map_error(error, rid.clone()))?;
Ok(StatusCode::NO_CONTENT)
}
/// Resolve a basket for a mapping endpoint: the column, plus the note that
/// records which revision and digest ran. One helper so `/compute/qtl2`,
/// `/compute/rqtl`, `/compute/gemma` and `/compute/fitqtl` behave alike --
/// a basket is not allowed to mean different things per engine.
pub async fn resolve_for_mapping(
owner: String,
dir: String,
name: String,
endpoint: &'static str,
rid: RequestInfo,
) -> Result<(crate::baskets::Resolved, String), ApiError> {
let wanted = name.clone();
let resolved = tokio::task::spawn_blocking(move || {
baskets::resolve(std::path::Path::new(&dir), &owner, &wanted)
})
.await
.map_err(|error| {
ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
"Internal error",
error.to_string(),
endpoint,
)
.with_request_id(rid.clone())
})?
.map_err(|error| match error {
BasketError::NotFound(detail) => ApiError::new(
StatusCode::NOT_FOUND,
"basket_not_found",
"Basket not found",
format!("{detail}; see /baskets"),
endpoint,
)
.with_request_id(rid.clone()),
other => ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"basket_store_error",
"The basket store failed",
other.to_string(),
endpoint,
)
.with_request_id(rid.clone()),
})?;
let note = format!(
"Basket '{}' revision {} (digest {}): {} value(s), {} missing. These values come from \
the basket, not from a published trait -- report the revision with the result.",
resolved.name,
resolved.revision,
resolved.digest,
resolved.values.len(),
resolved.missing
);
Ok((resolved, note))
}
/// The 422 a request gets when it gives both a basket and inline values.
pub fn ambiguous(endpoint: &'static str, rid: RequestInfo) -> ApiError {
ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"ambiguous_samples",
"Ambiguous values",
"give `basket` or the inline values, not both: a basket already is a column of values."
.to_string(),
endpoint,
)
.with_request_id(rid)
}
#[utoipa::path(get, path = "/baskets/{name}/revisions",
summary = "Every stored revision of a basket",
description = "The automatic version history: revision number, digest, when it was stored \
(Unix seconds), and how many values and missings it had. An edit adds a revision and leaves the \
previous one in place, so a mapping that quoted revision 2 can still be reproduced after the \
basket has moved on to 3 (`basket: \"<name>@2\"`, or `?revision=2` here).",
params(("name" = String, Path, description = "Basket name")),
responses(
(status = 200, description = "Oldest revision first", body = Envelope<Vec<baskets::Version>>),
Unauthorized,
(status = 404, description = "No such basket for this user", body = ApiError)
)
)]
#[gnauth(token_only)]
pub async fn basket_revisions(
ctx: Ctx,
token: AuthToken,
Path(name): Path<String>,
) -> Result<Json<Envelope<Vec<baskets::Version>>>, ApiError> {
let rid = ctx.request_info();
let owner = token.sub.clone();
let dir = Config::load().basket_dir;
let wanted = name.clone();
let versions = tokio::task::spawn_blocking(move || {
baskets::revisions(std::path::Path::new(&dir), &owner, &wanted)
})
.await
.map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone()))?
.map_err(|error| map_error(error, rid.clone()))?;
let mut envelope = ctx
.envelope(versions)
.with_note("Revision 1 is the column as first stored; each PATCH adds one, with its own \
digest and timestamp, and never removes an earlier one.")
.with_note("Unix seconds, as everywhere in this API.")
.with_next(
&format!("/baskets/{}/values", crate::response::path_segment(&name)),
"The current column (?revision=N for an earlier one)",
);
envelope = envelope.with_links(crate::suggest::root_links());
Ok(Json(envelope))
}
|