sbol-db-server 0.1.8

HTTP server for sbol-db.
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
//! Classic SynBioHub response shaping for the V1 query surface.
//!
//! Classic SynBioHub never returns raw SPARQL-results JSON to a V1 client. Its
//! `sparql.queryJson` folds a SPARQL 1.1 results document into a plain array of
//! row objects (`sparql-results-to-array.js`), and each API/view handler then
//! projects that array into its own wire object. The count family is served as
//! a bare integer in a `text/plain` body. This module reproduces those
//! projections so the adapter's bodies match classic byte-shape (JSON array of
//! objects, or a plain integer) rather than the engine's native SPARQL JSON.

use axum::http::header::CONTENT_TYPE;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde::Serialize;
use serde_json::{json, Map, Value};

/// Flatten one SPARQL binding node to classic's scalar form, mirroring
/// `flattenBinding`: a URI or literal collapses to its bare string value, an
/// `xsd:integer`/`xsd:boolean` literal is coerced to a number/bool, and any
/// other node is passed through unchanged.
fn flatten_binding(node: &Value) -> Value {
    let Some(obj) = node.as_object() else {
        return node.clone();
    };
    match obj.get("type").and_then(Value::as_str) {
        Some("uri") => obj.get("value").cloned().unwrap_or(Value::Null),
        Some("literal") | Some("typed-literal") => {
            let value = obj.get("value").and_then(Value::as_str).unwrap_or("");
            match obj.get("datatype").and_then(Value::as_str) {
                Some("http://www.w3.org/2001/XMLSchema#boolean") => Value::Bool(value == "true"),
                Some("http://www.w3.org/2001/XMLSchema#integer") => value
                    .parse::<i64>()
                    .map(|n| json!(n))
                    .unwrap_or(Value::Null),
                _ => Value::String(value.to_owned()),
            }
        }
        _ => node.clone(),
    }
}

/// Transform a SPARQL-results JSON document into classic's array of row objects:
/// one object per binding carrying every `head.var` as a key (null when the row
/// leaves it unbound), with each bound value flattened. Mirrors
/// `sparqlResultsToArray`.
pub fn results_to_array(results: &Value) -> Vec<Map<String, Value>> {
    let vars: Vec<String> = results
        .get("head")
        .and_then(|h| h.get("vars"))
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_owned))
                .collect()
        })
        .unwrap_or_default();
    let empty = Vec::new();
    let bindings = results
        .get("results")
        .and_then(|r| r.get("bindings"))
        .and_then(Value::as_array)
        .unwrap_or(&empty);
    bindings
        .iter()
        .map(|binding| {
            let mut row = Map::new();
            for var in &vars {
                let value = binding.get(var).map(flatten_binding).unwrap_or(Value::Null);
                row.insert(var.clone(), value);
            }
            row
        })
        .collect()
}

/// A JSON array body with the classic `application/json` content type.
fn json_array(rows: Vec<Value>) -> Response {
    (
        [(CONTENT_TYPE, "application/json")],
        Json(Value::Array(rows)),
    )
        .into_response()
}

/// A field value coerced with classic's `value || ''` fallback: a non-null
/// string passes through, anything else becomes the empty string.
fn string_or_empty(row: &Map<String, Value>, key: &str) -> Value {
    match row.get(key) {
        Some(Value::String(s)) => Value::String(s.clone()),
        _ => Value::String(String::new()),
    }
}

/// A field value coerced with classic's `value || null` fallback: a non-empty
/// string passes through, anything else becomes null.
fn string_or_null(row: &Map<String, Value>, key: &str) -> Value {
    match row.get(key) {
        Some(Value::String(s)) if !s.is_empty() => Value::String(s.clone()),
        _ => Value::Null,
    }
}

/// The `String` form of [`string_or_empty`] (classic's `value || ''`): a string
/// value passes through, anything else becomes the empty string.
fn string_value(row: &Map<String, Value>, key: &str) -> String {
    match row.get(key) {
        Some(Value::String(s)) => s.clone(),
        _ => String::new(),
    }
}

/// The `Option<String>` form of [`string_or_null`] (classic's `value || null`):
/// a non-empty string is `Some`, anything else is `None` (serialized as null).
fn string_option(row: &Map<String, Value>, key: &str) -> Option<String> {
    match row.get(key) {
        Some(Value::String(s)) if !s.is_empty() => Some(s.clone()),
        _ => None,
    }
}

/// `<uri>/metadata`: classic emits `sparqlResultsToArray` of the top-level
/// metadata query verbatim (an array of row objects keyed by the query's vars).
pub fn metadata_response(results: &Value) -> Response {
    let rows = results_to_array(results)
        .into_iter()
        .map(Value::Object)
        .collect();
    json_array(rows)
}

/// `/rootCollections` and `<uri>/subCollections`: classic maps each Collection
/// row to `{uri, name, description, displayId, version}`, renaming the
/// `?Collection` binding to `uri` and defaulting every text field to `''`.
pub fn collections_response(results: &Value) -> Response {
    let rows = results_to_array(results)
        .into_iter()
        .map(|row| {
            json!({
                "uri": row.get("Collection").cloned().unwrap_or(Value::Null),
                "name": string_or_empty(&row, "name"),
                "description": string_or_empty(&row, "description"),
                "displayId": string_or_empty(&row, "displayId"),
                "version": string_or_empty(&row, "version"),
            })
        })
        .collect();
    json_array(rows)
}

/// The `/browse` collection listing: the same collections as
/// [`collections_response`] plus the two fields classic's `/browse` adds, the
/// route `url` (the object URI's path) and the `public` flag.
pub fn browse_response(results: &Value) -> Response {
    let rows = results_to_array(results)
        .into_iter()
        .map(|row| {
            let uri = row.get("Collection").and_then(Value::as_str).unwrap_or("");
            json!({
                "uri": uri,
                "name": string_or_empty(&row, "name"),
                "description": string_or_empty(&row, "description"),
                "displayId": string_or_empty(&row, "displayId"),
                "version": string_or_empty(&row, "version"),
                "url": object_path(uri),
                "public": uri.contains("/public/"),
            })
        })
        .collect();
    json_array(rows)
}

/// The route path of an object URI: the substring from `/public/` or `/user/`
/// onward, which is what the UI navigates to. Falls back to the whole URI.
fn object_path(uri: &str) -> String {
    for marker in ["/public/", "/user/"] {
        if let Some(idx) = uri.find(marker) {
            return uri[idx..].to_owned();
        }
    }
    uri.to_owned()
}

/// One row of classic's search view: the fixed 11-key wire object, with the
/// keys in classic's emission order (`type, uri, name, description, displayId,
/// version, sbolType, role, percentMatch, strandAlignment, CIGAR`). Serialized
/// as a struct so the key order is fixed by field order rather than by the JSON
/// map's collation, matching classic byte-for-byte.
#[derive(Serialize)]
struct SearchRow {
    #[serde(rename = "type")]
    type_iri: String,
    uri: String,
    name: String,
    description: String,
    #[serde(rename = "displayId")]
    display_id: String,
    version: String,
    #[serde(rename = "sbolType")]
    sbol_type: Option<String>,
    role: Option<String>,
    #[serde(rename = "percentMatch")]
    percent_match: String,
    #[serde(rename = "strandAlignment")]
    strand_alignment: String,
    #[serde(rename = "CIGAR")]
    cigar: String,
}

/// `/search`, `<uri>/uses`, `<uri>/twins`, `<uri>/similar` (and sequence
/// search): classic's search view projects each row to a fixed 11-key object,
/// renaming `?subject` to `uri`, filling an empty `name` from the `displayId`,
/// and defaulting the alignment columns. Text fields default to `''`; `sbolType`
/// and `role` default to null.
pub fn search_response(results: &Value) -> Response {
    let rows: Vec<SearchRow> = results_to_array(results)
        .into_iter()
        .map(|row| search_row(&row))
        .collect();
    (
        [(CONTENT_TYPE, "application/json")],
        serde_json::to_string(&rows).unwrap_or_else(|_| "[]".to_owned()),
    )
        .into_response()
}

/// Project one search-result row into classic's 11-key wire object.
fn search_row(row: &Map<String, Value>) -> SearchRow {
    let display_id = string_value(row, "displayId");
    let name = {
        let name = string_value(row, "name");
        if name.is_empty() {
            display_id.clone()
        } else {
            name
        }
    };
    SearchRow {
        type_iri: string_value(row, "type"),
        uri: string_value(row, "subject"),
        name,
        description: string_value(row, "description"),
        display_id,
        version: string_value(row, "version"),
        sbol_type: string_option(row, "sbolType"),
        role: string_option(row, "role"),
        percent_match: string_value(row, "percentMatch"),
        strand_alignment: string_value(row, "strandAlignment"),
        cigar: string_value(row, "CIGAR"),
    }
}

/// `/manage`: classic returns the raw `search()` result rows (not the search
/// view's alignment projection), each tagged with its `triplestore` origin.
/// Every row is a root Collection the caller owns, projected to classic's
/// manage-row keys: identity plus `typeName`, `url`, `prefix`, and
/// `triplestore`, with the alignment columns absent.
pub fn manage_response(results: &Value) -> Response {
    let rows = results_to_array(results)
        .into_iter()
        .map(|row| manage_row(&row))
        .collect();
    json_array(rows)
}

/// Project one owned-collection row into classic's manage-row wire object.
fn manage_row(row: &Map<String, Value>) -> Value {
    let uri = string_or_empty(row, "subject");
    let uri_str = uri.as_str().unwrap_or("");
    let type_iri = string_or_empty(row, "type");
    let type_name = type_iri
        .as_str()
        .unwrap_or("")
        .rsplit(['#', '/'])
        .next()
        .unwrap_or("")
        .to_owned();
    let url = uri_str
        .split_once("://")
        .and_then(|(_, authority_and_path)| {
            authority_and_path
                .find('/')
                .map(|at| &authority_and_path[at..])
        })
        .unwrap_or(uri_str)
        .to_owned();
    let triplestore = if uri_str.contains("/public/") {
        "public"
    } else {
        "private"
    };
    json!({
        "uri": uri,
        "name": string_or_empty(row, "name"),
        "description": string_or_empty(row, "description"),
        "displayId": string_or_empty(row, "displayId"),
        "version": string_or_empty(row, "version"),
        "type": type_iri,
        "typeName": type_name,
        "prefix": namespace_prefix(uri_str),
        "url": url,
        "role": string_or_null(row, "role"),
        "sbolType": string_or_null(row, "sbolType"),
        "triplestore": triplestore,
    })
}

/// The configured RDF namespace prefixes, in classic's declaration order.
/// Classic's `prefixify` scans this list and returns the name of the first
/// namespace the URI falls under; this is the exact set from its
/// `config.namespaces`.
const NAMESPACE_PREFIXES: &[(&str, &str)] = &[
    ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
    ("dcterms", "http://purl.org/dc/terms/"),
    ("dc", "http://purl.org/dc/elements/1.1/"),
    ("sbh", "http://wiki.synbiohub.org/wiki/Terms/synbiohub#"),
    ("prov", "http://www.w3.org/ns/prov#"),
    ("sbol", "http://sbols.org/v2#"),
    ("xsd", "http://www.w3.org/2001/XMLSchema#"),
    ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
    ("purl", "http://purl.obolibrary.org/obo/"),
];

/// Classic's `prefixify`: the name of the first configured RDF namespace the
/// URI falls under, or the empty string when it matches none. A SynBioHub
/// object URI lives under the instance `databasePrefix`, which is not a
/// vocabulary namespace, so it resolves to the empty string; a URI naming an
/// RDF vocabulary term resolves to that vocabulary's prefix.
fn namespace_prefix(uri: &str) -> String {
    NAMESPACE_PREFIXES
        .iter()
        .find(|(_, ns)| uri.starts_with(ns))
        .map(|(name, _)| (*name).to_owned())
        .unwrap_or_default()
}

/// The count family (`/:type/count`, `/searchCount`, `/usesCount`,
/// `/twinsCount`, `/similarCount`): classic sends the bare integer in a
/// `text/plain` body.
pub fn count_response(results: &Value) -> Response {
    (
        [(CONTENT_TYPE, "text/plain")],
        count_value(results).to_string(),
    )
        .into_response()
}

/// The integer from a single-row `COUNT(...) AS ?count` result, or `0` when the
/// result carries no count binding.
fn count_value(results: &Value) -> i64 {
    results
        .get("results")
        .and_then(|r| r.get("bindings"))
        .and_then(Value::as_array)
        .and_then(|b| b.first())
        .and_then(|row| row.get("count"))
        .and_then(|c| c.get("value"))
        .and_then(Value::as_str)
        .and_then(|s| s.parse::<i64>().ok())
        .unwrap_or(0)
}

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

    fn sparql(vars: &[&str], bindings: Value) -> Value {
        json!({
            "head": { "vars": vars },
            "results": { "bindings": bindings },
        })
    }

    #[test]
    fn results_to_array_keys_every_var_and_flattens() {
        let doc = sparql(
            &["subject", "displayId", "version"],
            json!([
                {
                    "subject": { "type": "uri", "value": "http://ex/a" },
                    "displayId": { "type": "literal", "value": "a" },
                },
            ]),
        );
        let rows = results_to_array(&doc);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["subject"], json!("http://ex/a"));
        assert_eq!(rows[0]["displayId"], json!("a"));
        // An unbound var is present and null, matching sparqlResultsToArray.
        assert_eq!(rows[0]["version"], Value::Null);
    }

    #[test]
    fn integer_literals_are_coerced() {
        let doc = sparql(
            &["count"],
            json!([
                {
                    "count": {
                        "type": "literal",
                        "value": "7",
                        "datatype": "http://www.w3.org/2001/XMLSchema#integer",
                    },
                },
            ]),
        );
        let rows = results_to_array(&doc);
        assert_eq!(rows[0]["count"], json!(7));
        assert_eq!(count_value(&doc), 7);
    }

    #[test]
    fn count_value_defaults_to_zero() {
        let doc = sparql(&["count"], json!([]));
        assert_eq!(count_value(&doc), 0);
    }

    #[test]
    fn namespace_prefix_matches_classic_prefixify() {
        // An object URI under the instance databasePrefix is not a vocabulary
        // namespace, so it resolves to the empty string, as classic returns.
        assert_eq!(
            namespace_prefix("http://synbiohub.org/public/igem/BBa_B0012/1"),
            ""
        );
        // A URI naming an RDF vocabulary term resolves to that prefix.
        assert_eq!(namespace_prefix("http://sbols.org/v2#Collection"), "sbol");
        assert_eq!(
            namespace_prefix("http://purl.org/dc/terms/description"),
            "dcterms"
        );
    }
}