Skip to main content

waratah_api/
serialize.rs

1//! SPARQL Results and RDF graph serialization.
2
3use std::cell::RefCell;
4use std::fmt::Write as _;
5use std::io::{self, BufWriter, Write};
6use std::rc::Rc;
7
8use bytes::Bytes;
9use oxrdf::vocab::xsd;
10use oxrdf::{BlankNodeRef, GraphName, LiteralRef, NamedNodeRef, Quad, TermRef};
11use oxrdfio::{RdfFormat, RdfSerializer};
12use sparesults::{QueryResultsFormat, QueryResultsSerializer, WriterSolutionsSerializer};
13use tokio::sync::mpsc;
14use waratah_compute::{ProjectedSolutions, QueryContext, QueryResults};
15use waratah_storage::{
16    EncodedTerm, Literal, NamedNode, StrHash, StrHashMap, Term, Variable, well_known_iri,
17};
18
19use crate::error::ApiError;
20
21/// HTTP body chunk size for streamed SPARQL SELECT results.
22pub(crate) const SELECT_HTTP_CHUNK: usize = 65_536;
23
24/// Pick JSON, XML, CSV, or TSV from an `Accept` header; default JSON.
25///
26/// First acceptable entry wins; media-type parameters (`q`, profiles) are
27/// ignored. Wildcards map to a format we can actually produce: JSON for
28/// `*/*` / `application/*`, CSV for `text/*`. An `Accept` that lists only
29/// media types we cannot produce is a client error (406 Not Acceptable),
30/// matching RDF4J and RFC 9110 §12.5.1.
31pub fn negotiate_results_format(accept: Option<&str>) -> Result<QueryResultsFormat, ApiError> {
32    negotiate_results_format_with_default(accept, QueryResultsFormat::Json)
33}
34
35/// Like [`negotiate_results_format`], but absent / wildcard `Accept` values
36/// (`*`, `*/*`) fall back to `default` instead of JSON.
37///
38/// The SPARQL query endpoint passes CSV so a client without an `Accept`
39/// gets `text/csv` SELECT and ASK bodies; the repository and namespace
40/// listings keep the JSON default of [`negotiate_results_format`].
41pub fn negotiate_results_format_with_default(
42    accept: Option<&str>,
43    default: QueryResultsFormat,
44) -> Result<QueryResultsFormat, ApiError> {
45    let Some(accept) = accept.map(str::trim).filter(|value| !value.is_empty()) else {
46        return Ok(default);
47    };
48
49    for part in accept.split(',') {
50        let media = part.split(';').next().unwrap_or("").trim();
51        match media {
52            "" | "*" | "*/*" => return Ok(default),
53            "application/*" => return Ok(QueryResultsFormat::Json),
54            "text/*" => return Ok(QueryResultsFormat::Csv),
55            _ => {}
56        }
57        // `QueryResultsFormat` only has the four variants we support, so any
58        // parse hit is directly acceptable.
59        if let Some(format) = QueryResultsFormat::from_media_type(media) {
60            return Ok(format);
61        }
62    }
63
64    Err(ApiError::NotAcceptable(accept.to_owned()))
65}
66
67/// Pick Turtle, N-Triples, TriG, N-Quads, RDF/XML, or JSON-LD from an
68/// `Accept` header; default Turtle.
69///
70/// Same rules as [`negotiate_results_format`]: first acceptable entry wins,
71/// parameters ignored, wildcards map to a producible format (Turtle for
72/// `*/*` / `text/*`, RDF/XML for `application/*`), and an `Accept` listing
73/// only unproducible media types is a 406.
74pub fn negotiate_graph_format(accept: Option<&str>) -> Result<RdfFormat, ApiError> {
75    let Some(accept) = accept.map(str::trim).filter(|value| !value.is_empty()) else {
76        return Ok(RdfFormat::Turtle);
77    };
78
79    for part in accept.split(',') {
80        let media = part.split(';').next().unwrap_or("").trim();
81        match media {
82            "" | "*/*" | "text/*" => return Ok(RdfFormat::Turtle),
83            "application/*" => return Ok(RdfFormat::RdfXml),
84            _ => {}
85        }
86        if let Some(format) = RdfFormat::from_media_type(media)
87            && matches!(
88                format,
89                RdfFormat::Turtle
90                    | RdfFormat::NTriples
91                    | RdfFormat::TriG
92                    | RdfFormat::NQuads
93                    | RdfFormat::RdfXml
94                    | RdfFormat::JsonLd { .. }
95            )
96        {
97            return Ok(format);
98        }
99    }
100
101    Err(ApiError::NotAcceptable(accept.to_owned()))
102}
103
104/// Serialize SELECT bindings, an ASK boolean, or a CONSTRUCT/DESCRIBE graph.
105pub fn serialize_query_results(
106    results: &QueryResults,
107    accept: Option<&str>,
108) -> Result<(Vec<u8>, &'static str), ApiError> {
109    serialize_query_results_with_default(results, accept, QueryResultsFormat::Json)
110}
111
112/// Like [`serialize_query_results`], but solutions and boolean results fall
113/// back to `solutions_default` for absent / wildcard `Accept` values.
114///
115/// Graph results ignore `solutions_default` and keep the Turtle default of
116/// [`negotiate_graph_format`].
117pub fn serialize_query_results_with_default(
118    results: &QueryResults,
119    accept: Option<&str>,
120    solutions_default: QueryResultsFormat,
121) -> Result<(Vec<u8>, &'static str), ApiError> {
122    match results {
123        QueryResults::Solutions { .. } => serialize_bindings(
124            results,
125            negotiate_results_format_with_default(accept, solutions_default)?,
126        ),
127        QueryResults::Boolean(value) => serialize_boolean(
128            *value,
129            negotiate_results_format_with_default(accept, solutions_default)?,
130        ),
131        QueryResults::Graph { triples } => {
132            serialize_graph(triples, negotiate_graph_format(accept)?)
133        }
134    }
135}
136
137fn serialize_boolean(
138    value: bool,
139    format: QueryResultsFormat,
140) -> Result<(Vec<u8>, &'static str), ApiError> {
141    let serializer = QueryResultsSerializer::from_format(format);
142    let mut buffer = Vec::new();
143    serializer
144        .serialize_boolean_to_writer(&mut buffer, value)
145        .map_err(|error| ApiError::Serialize(error.to_string()))?;
146    Ok((buffer, format.media_type()))
147}
148
149fn serialize_bindings(
150    results: &QueryResults,
151    format: QueryResultsFormat,
152) -> Result<(Vec<u8>, &'static str), ApiError> {
153    let serializer = QueryResultsSerializer::from_format(format);
154    let mut buffer = Vec::new();
155    let mut writer = serializer
156        .serialize_solutions_to_writer(&mut buffer, results.variables().to_vec())
157        .map_err(|error| ApiError::Serialize(error.to_string()))?;
158    for row in results.solutions() {
159        let bindings = results
160            .variables()
161            .iter()
162            .zip(row.iter())
163            .filter_map(|(variable, term)| {
164                term.as_ref()
165                    .map(|term| (variable.as_ref(), TermRef::from(term)))
166            });
167        writer
168            .serialize(bindings)
169            .map_err(|error| ApiError::Serialize(error.to_string()))?;
170    }
171    writer
172        .finish()
173        .map_err(|error| ApiError::Serialize(error.to_string()))?;
174    Ok((buffer, format.media_type()))
175}
176
177fn serialize_graph(
178    triples: &[waratah_storage::Triple],
179    format: RdfFormat,
180) -> Result<(Vec<u8>, &'static str), ApiError> {
181    let mut serializer = RdfSerializer::from_format(format).for_writer(Vec::new());
182    for triple in triples {
183        let quad = Quad {
184            subject: triple.subject.clone(),
185            predicate: triple.predicate.clone(),
186            object: triple.object.clone(),
187            graph_name: GraphName::DefaultGraph,
188        };
189        serializer
190            .serialize_quad(&quad)
191            .map_err(|error| ApiError::Serialize(error.to_string()))?;
192    }
193    let buffer = serializer
194        .finish()
195        .map_err(|error| ApiError::Serialize(error.to_string()))?;
196    Ok((buffer, format.media_type()))
197}
198
199/// Build a SPARQL Results payload for the namespace list (`prefix`, `namespace`).
200pub fn serialize_namespaces(
201    namespaces: &[(String, String)],
202    format: QueryResultsFormat,
203) -> Result<(Vec<u8>, &'static str), ApiError> {
204    let variables = vec![
205        Variable::new("prefix").expect("valid variable"),
206        Variable::new("namespace").expect("valid variable"),
207    ];
208    let solutions: Vec<Vec<Option<Term>>> = namespaces
209        .iter()
210        .map(|(prefix, namespace)| {
211            vec![
212                Some(Term::from(Literal::from(prefix.as_str()))),
213                Some(Term::from(Literal::from(namespace.as_str()))),
214            ]
215        })
216        .collect();
217
218    serialize_bindings(
219        &QueryResults::Solutions {
220            variables,
221            solutions,
222        },
223        format,
224    )
225}
226
227/// RDF4J `GET /repositories` tuple: uri, id, title, readable, writable.
228pub fn serialize_repository_list(
229    rows: &[(String, String, String, bool, bool)],
230    format: QueryResultsFormat,
231) -> Result<(Vec<u8>, &'static str), ApiError> {
232    let variables = vec![
233        Variable::new("uri").expect("valid variable"),
234        Variable::new("id").expect("valid variable"),
235        Variable::new("title").expect("valid variable"),
236        Variable::new("readable").expect("valid variable"),
237        Variable::new("writable").expect("valid variable"),
238    ];
239    let mut solutions = Vec::with_capacity(rows.len());
240    for (uri, id, title, readable, writable) in rows {
241        let node = NamedNode::new(uri.as_str()).map_err(|error| {
242            ApiError::InvalidArgument(format!("invalid repository URI `{uri}`: {error}"))
243        })?;
244        solutions.push(vec![
245            Some(Term::from(node)),
246            Some(Term::from(Literal::from(id.as_str()))),
247            Some(Term::from(Literal::from(title.as_str()))),
248            Some(Term::from(Literal::from(*readable))),
249            Some(Term::from(Literal::from(*writable))),
250        ]);
251    }
252    serialize_bindings(
253        &QueryResults::Solutions {
254            variables,
255            solutions,
256        },
257        format,
258    )
259}
260
261/// Serialize projected SELECT rows onto a blocking mpsc, 64 KiB chunks.
262///
263/// The first item is the SPARQL Results `head` (flushed before any row). Failures
264/// after that close the channel.
265pub(crate) fn spawn_select_stream(
266    projected: ProjectedSolutions,
267    format: QueryResultsFormat,
268    ctx: QueryContext,
269) -> mpsc::Receiver<Result<Bytes, io::Error>> {
270    let (tx, rx) = mpsc::channel(4);
271    tokio::task::spawn_blocking(move || {
272        if let Err(error) = write_select_to_channel(&projected, format, &tx, &ctx) {
273            let _ = tx.blocking_send(Err(error));
274        }
275    });
276    rx
277}
278
279fn write_select_to_channel(
280    projected: &ProjectedSolutions,
281    format: QueryResultsFormat,
282    tx: &mpsc::Sender<Result<Bytes, io::Error>>,
283    ctx: &QueryContext,
284) -> io::Result<()> {
285    let sink = ChannelSink {
286        tx: tx.clone(),
287        ctx: ctx.clone(),
288    };
289    let buffered = BufWriter::with_capacity(SELECT_HTTP_CHUNK, sink);
290    // sparesults owns the BufWriter for the whole document; a second handle
291    // lets us flush the SPARQL Results head before any solution row.
292    let mut shared = SharedWrite(Rc::new(RefCell::new(buffered)));
293    let serializer = QueryResultsSerializer::from_format(format);
294    let mut writer = serializer
295        .serialize_solutions_to_writer(shared.clone(), projected.variables.clone())
296        .map_err(|error| io::Error::other(error.to_string()))?;
297    shared.flush()?;
298    write_select_rows(projected, &mut writer, ctx)?;
299    writer
300        .finish()
301        .map_err(|error| io::Error::other(error.to_string()))?;
302    shared.flush()?;
303    Ok(())
304}
305
306#[cfg(test)]
307fn write_select_solutions<W: Write>(
308    projected: &ProjectedSolutions,
309    format: QueryResultsFormat,
310    mut sink: W,
311    ctx: &QueryContext,
312) -> io::Result<()> {
313    let serializer = QueryResultsSerializer::from_format(format);
314    let mut writer = serializer
315        .serialize_solutions_to_writer(&mut sink, projected.variables.clone())
316        .map_err(|error| io::Error::other(error.to_string()))?;
317    write_select_rows(projected, &mut writer, ctx)?;
318    writer
319        .finish()
320        .map_err(|error| io::Error::other(error.to_string()))?;
321    Ok(())
322}
323
324fn write_select_rows<W: Write>(
325    projected: &ProjectedSolutions,
326    writer: &mut WriterSolutionsSerializer<W>,
327    ctx: &QueryContext,
328) -> io::Result<()> {
329    let width = projected.variables.len();
330    let mut encoded_cells: Vec<Option<EncodedTerm>> = vec![None; width];
331    let mut scratches: Vec<String> = vec![String::new(); width];
332
333    for row in 0..projected.solutions.len() {
334        ctx.check_abort()
335            .map_err(|error| io::Error::other(error.to_string()))?;
336        projected
337            .solutions
338            .fill_optional_row(row, &mut encoded_cells)
339            .map_err(|error| io::Error::other(error.to_string()))?;
340        for (i, term) in encoded_cells.iter().enumerate() {
341            scratches[i].clear();
342            if let Some(term) = term.as_ref() {
343                fill_native_scratch(term, &mut scratches[i]);
344            }
345        }
346        serialize_filled_row(
347            writer,
348            &projected.variables,
349            &encoded_cells,
350            &scratches,
351            &projected.strings,
352        )?;
353    }
354    Ok(())
355}
356
357fn serialize_filled_row<W: Write>(
358    writer: &mut WriterSolutionsSerializer<W>,
359    variables: &[Variable],
360    encoded_cells: &[Option<EncodedTerm>],
361    scratches: &[String],
362    strings: &StrHashMap,
363) -> io::Result<()> {
364    let mut bindings = Vec::with_capacity(variables.len());
365    for (i, variable) in variables.iter().enumerate() {
366        let Some(term) = encoded_cells[i].as_ref() else {
367            continue;
368        };
369        let term_ref =
370            term_ref_from_encoded(term, strings, &scratches[i]).map_err(io::Error::other)?;
371        bindings.push((variable.as_ref(), term_ref));
372    }
373    writer
374        .serialize(bindings)
375        .map_err(|error| io::Error::other(error.to_string()))
376}
377
378/// `Write` clone that shares one `BufWriter` so we can flush after `start`.
379struct SharedWrite<W>(Rc<RefCell<W>>);
380
381impl<W> Clone for SharedWrite<W> {
382    fn clone(&self) -> Self {
383        Self(Rc::clone(&self.0))
384    }
385}
386
387impl<W: Write> Write for SharedWrite<W> {
388    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
389        self.0.borrow_mut().write(buf)
390    }
391
392    fn flush(&mut self) -> io::Result<()> {
393        self.0.borrow_mut().flush()
394    }
395}
396
397struct ChannelSink {
398    tx: mpsc::Sender<Result<Bytes, io::Error>>,
399    ctx: QueryContext,
400}
401
402impl Write for ChannelSink {
403    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
404        if buf.is_empty() {
405            return Ok(0);
406        }
407        self.ctx
408            .check_abort()
409            .map_err(|error| io::Error::other(error.to_string()))?;
410        self.tx
411            .blocking_send(Ok(Bytes::copy_from_slice(buf)))
412            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "client disconnected"))?;
413        Ok(buf.len())
414    }
415
416    fn flush(&mut self) -> io::Result<()> {
417        Ok(())
418    }
419}
420
421fn fill_native_scratch(term: &EncodedTerm, scratch: &mut String) {
422    match term {
423        EncodedTerm::NumericalBlankNode { id } => {
424            let _ = write!(scratch, "{:x}", u128::from_be_bytes(*id));
425        }
426        EncodedTerm::BooleanLiteral(value) => {
427            let _ = write!(scratch, "{value}");
428        }
429        EncodedTerm::FloatLiteral(value) => {
430            let _ = write!(scratch, "{value}");
431        }
432        EncodedTerm::DoubleLiteral(value) => {
433            let _ = write!(scratch, "{value}");
434        }
435        EncodedTerm::IntegerLiteral(value) => {
436            let _ = write!(scratch, "{value}");
437        }
438        EncodedTerm::DecimalLiteral(value) => {
439            let _ = write!(scratch, "{value}");
440        }
441        EncodedTerm::DateTimeLiteral(value) => {
442            let _ = write!(scratch, "{value}");
443        }
444        EncodedTerm::TimeLiteral(value) => {
445            let _ = write!(scratch, "{value}");
446        }
447        EncodedTerm::DateLiteral(value) => {
448            let _ = write!(scratch, "{value}");
449        }
450        EncodedTerm::GYearMonthLiteral(value) => {
451            let _ = write!(scratch, "{value}");
452        }
453        EncodedTerm::GYearLiteral(value) => {
454            let _ = write!(scratch, "{value}");
455        }
456        EncodedTerm::GMonthDayLiteral(value) => {
457            let _ = write!(scratch, "{value}");
458        }
459        EncodedTerm::GDayLiteral(value) => {
460            let _ = write!(scratch, "{value}");
461        }
462        EncodedTerm::GMonthLiteral(value) => {
463            let _ = write!(scratch, "{value}");
464        }
465        EncodedTerm::DurationLiteral(value) => {
466            let _ = write!(scratch, "{value}");
467        }
468        EncodedTerm::YearMonthDurationLiteral(value) => {
469            let _ = write!(scratch, "{value}");
470        }
471        EncodedTerm::DayTimeDurationLiteral(value) => {
472            let _ = write!(scratch, "{value}");
473        }
474        _ => {}
475    }
476}
477
478fn lookup(strings: &StrHashMap, hash: StrHash) -> Result<&str, String> {
479    strings
480        .get(&hash)
481        .map(String::as_str)
482        .ok_or_else(|| format!("registry miss for hash {}", hash.as_u128()))
483}
484
485fn iri_ref<'a>(hash: StrHash, strings: &'a StrHashMap) -> Result<NamedNodeRef<'a>, String> {
486    let iri = well_known_iri(hash)
487        .or_else(|| strings.get(&hash).map(String::as_str))
488        .ok_or_else(|| format!("registry miss for hash {}", hash.as_u128()))?;
489    Ok(NamedNodeRef::new_unchecked(iri))
490}
491
492fn term_ref_from_encoded<'a>(
493    term: &'a EncodedTerm,
494    strings: &'a StrHashMap,
495    scratch: &'a str,
496) -> Result<TermRef<'a>, String> {
497    Ok(match term {
498        EncodedTerm::DefaultGraph => {
499            return Err("the default graph is not an RDF term".into());
500        }
501        EncodedTerm::Placeholder => {
502            return Err("internal Placeholder is not an RDF term".into());
503        }
504        EncodedTerm::NamedNode { iri_id } => iri_ref(*iri_id, strings)?.into(),
505        EncodedTerm::NumericalBlankNode { .. } => BlankNodeRef::new_unchecked(scratch).into(),
506        EncodedTerm::SmallBlankNode(id) => BlankNodeRef::new_unchecked(id.as_str()).into(),
507        EncodedTerm::BigBlankNode { id_id } => {
508            BlankNodeRef::new_unchecked(lookup(strings, *id_id)?).into()
509        }
510        EncodedTerm::SmallStringLiteral(value) => {
511            LiteralRef::new_simple_literal(value.as_str()).into()
512        }
513        EncodedTerm::BigStringLiteral { value_id } => {
514            LiteralRef::new_simple_literal(lookup(strings, *value_id)?).into()
515        }
516        EncodedTerm::SmallSmallLangStringLiteral { value, language } => {
517            LiteralRef::new_language_tagged_literal_unchecked(value.as_str(), language.as_str())
518                .into()
519        }
520        EncodedTerm::SmallBigLangStringLiteral { value, language_id } => {
521            LiteralRef::new_language_tagged_literal_unchecked(
522                value.as_str(),
523                lookup(strings, *language_id)?,
524            )
525            .into()
526        }
527        EncodedTerm::BigSmallLangStringLiteral { value_id, language } => {
528            LiteralRef::new_language_tagged_literal_unchecked(
529                lookup(strings, *value_id)?,
530                language.as_str(),
531            )
532            .into()
533        }
534        EncodedTerm::BigBigLangStringLiteral {
535            value_id,
536            language_id,
537        } => LiteralRef::new_language_tagged_literal_unchecked(
538            lookup(strings, *value_id)?,
539            lookup(strings, *language_id)?,
540        )
541        .into(),
542        EncodedTerm::SmallTypedLiteral { value, datatype_id } => {
543            LiteralRef::new_typed_literal(value.as_str(), iri_ref(*datatype_id, strings)?).into()
544        }
545        EncodedTerm::BigTypedLiteral {
546            value_id,
547            datatype_id,
548        } => LiteralRef::new_typed_literal(
549            lookup(strings, *value_id)?,
550            iri_ref(*datatype_id, strings)?,
551        )
552        .into(),
553        EncodedTerm::BooleanLiteral(_) => {
554            LiteralRef::new_typed_literal(scratch, xsd::BOOLEAN).into()
555        }
556        EncodedTerm::FloatLiteral(_) => LiteralRef::new_typed_literal(scratch, xsd::FLOAT).into(),
557        EncodedTerm::DoubleLiteral(_) => LiteralRef::new_typed_literal(scratch, xsd::DOUBLE).into(),
558        EncodedTerm::IntegerLiteral(_) => {
559            LiteralRef::new_typed_literal(scratch, xsd::INTEGER).into()
560        }
561        EncodedTerm::DecimalLiteral(_) => {
562            LiteralRef::new_typed_literal(scratch, xsd::DECIMAL).into()
563        }
564        EncodedTerm::DateTimeLiteral(_) => {
565            LiteralRef::new_typed_literal(scratch, xsd::DATE_TIME).into()
566        }
567        EncodedTerm::TimeLiteral(_) => LiteralRef::new_typed_literal(scratch, xsd::TIME).into(),
568        EncodedTerm::DateLiteral(_) => LiteralRef::new_typed_literal(scratch, xsd::DATE).into(),
569        EncodedTerm::GYearMonthLiteral(_) => {
570            LiteralRef::new_typed_literal(scratch, xsd::G_YEAR_MONTH).into()
571        }
572        EncodedTerm::GYearLiteral(_) => LiteralRef::new_typed_literal(scratch, xsd::G_YEAR).into(),
573        EncodedTerm::GMonthDayLiteral(_) => {
574            LiteralRef::new_typed_literal(scratch, xsd::G_MONTH_DAY).into()
575        }
576        EncodedTerm::GDayLiteral(_) => LiteralRef::new_typed_literal(scratch, xsd::G_DAY).into(),
577        EncodedTerm::GMonthLiteral(_) => {
578            LiteralRef::new_typed_literal(scratch, xsd::G_MONTH).into()
579        }
580        EncodedTerm::DurationLiteral(_) => {
581            LiteralRef::new_typed_literal(scratch, xsd::DURATION).into()
582        }
583        EncodedTerm::YearMonthDurationLiteral(_) => {
584            LiteralRef::new_typed_literal(scratch, xsd::YEAR_MONTH_DURATION).into()
585        }
586        EncodedTerm::DayTimeDurationLiteral(_) => {
587            LiteralRef::new_typed_literal(scratch, xsd::DAY_TIME_DURATION).into()
588        }
589        // Native geo / blob literals resolve through the strings map under
590        // their deterministic `geo_lexical_key` (resolve_projection rendered
591        // them through the geo plugin before serialization).
592        EncodedTerm::LiteralPoint { .. }
593        | EncodedTerm::LiteralGeometry { .. }
594        | EncodedTerm::BlobLiteral { .. } => {
595            let key =
596                waratah_storage::geo_lexical_key(term).ok_or("geo term without a lexical key")?;
597            let lexical = lookup(strings, key)?;
598            let datatype_iri = match term {
599                EncodedTerm::BlobLiteral { datatype_id, .. } => well_known_iri(*datatype_id)
600                    .or_else(|| strings.get(datatype_id).map(String::as_str))
601                    .ok_or_else(|| {
602                        format!("registry miss for datatype hash {}", datatype_id.as_u128())
603                    })?,
604                _ => match term {
605                    EncodedTerm::LiteralPoint { geo_datatype, .. }
606                    | EncodedTerm::LiteralGeometry { geo_datatype, .. } => geo_datatype.iri(),
607                    _ => unreachable!("geo term arm"),
608                },
609            };
610            LiteralRef::new_typed_literal(lexical, NamedNodeRef::new_unchecked(datatype_iri)).into()
611        }
612    })
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618    use axum::http::StatusCode;
619    use pretty_assertions::assert_eq;
620    use waratah_compute::EncodedSolutions;
621    use waratah_storage::{
622        NamedNode, SnapshotId, encode_term, new_str_blob_map, new_str_hash_map,
623        strings_entries_for_term,
624    };
625
626    #[test]
627    fn negotiate_prefers_xml_when_listed_first() {
628        assert_eq!(
629            negotiate_results_format(Some("application/sparql-results+xml, application/json"))
630                .unwrap(),
631            QueryResultsFormat::Xml
632        );
633    }
634
635    #[test]
636    fn negotiate_prefers_csv_and_tsv() {
637        assert_eq!(
638            negotiate_results_format(Some("text/csv")).unwrap(),
639            QueryResultsFormat::Csv
640        );
641        assert_eq!(
642            negotiate_results_format(Some("text/tab-separated-values")).unwrap(),
643            QueryResultsFormat::Tsv
644        );
645    }
646
647    #[test]
648    fn negotiate_defaults_to_json() {
649        assert_eq!(
650            negotiate_results_format(None).unwrap(),
651            QueryResultsFormat::Json
652        );
653        assert_eq!(
654            negotiate_results_format(Some("*")).unwrap(),
655            QueryResultsFormat::Json
656        );
657        assert_eq!(
658            negotiate_results_format(Some("*/*")).unwrap(),
659            QueryResultsFormat::Json
660        );
661        assert_eq!(
662            negotiate_results_format(Some("application/*")).unwrap(),
663            QueryResultsFormat::Json
664        );
665    }
666
667    #[test]
668    fn negotiate_with_default_csv_for_wildcards() {
669        // Query endpoint: absent or wildcard Accept means CSV SELECT / ASK
670        // bodies, including a wildcard rescuing an unsupported first entry.
671        for accept in [None, Some("*"), Some("*/*"), Some("image/png, */*")] {
672            assert_eq!(
673                negotiate_results_format_with_default(accept, QueryResultsFormat::Csv).unwrap(),
674                QueryResultsFormat::Csv,
675                "{accept:?}"
676            );
677        }
678        // Range wildcards still map to their fixed producible formats.
679        assert_eq!(
680            negotiate_results_format_with_default(Some("application/*"), QueryResultsFormat::Csv)
681                .unwrap(),
682            QueryResultsFormat::Json
683        );
684        assert_eq!(
685            negotiate_results_format_with_default(Some("text/*"), QueryResultsFormat::Csv).unwrap(),
686            QueryResultsFormat::Csv
687        );
688    }
689
690    #[test]
691    fn serialize_with_default_csv_select_and_graph_turtle() {
692        let (body, media) =
693            serialize_query_results_with_default(&sample_results(), None, QueryResultsFormat::Csv)
694                .unwrap();
695        assert_eq!(media, "text/csv; charset=utf-8");
696        assert!(String::from_utf8(body).unwrap().contains("s,label,n"));
697
698        // ASK keeps the solutions default too (CSV body is bare `true`).
699        let (body, media) = serialize_query_results_with_default(
700            &QueryResults::Boolean(true),
701            Some("*"),
702            QueryResultsFormat::Csv,
703        )
704        .unwrap();
705        assert_eq!(media, "text/csv; charset=utf-8");
706        assert_eq!(body, b"true");
707
708        // Graph responses ignore the solutions default.
709        let triple = waratah_storage::Triple::new(
710            NamedNode::new("http://ex/alice").unwrap(),
711            NamedNode::new("http://ex/name").unwrap(),
712            Literal::from("Alice"),
713        );
714        let (body, media) = serialize_query_results_with_default(
715            &QueryResults::Graph {
716                triples: vec![triple],
717            },
718            None,
719            QueryResultsFormat::Csv,
720        )
721        .unwrap();
722        assert_eq!(media, "text/turtle");
723        assert!(String::from_utf8(body).unwrap().contains("http://ex/alice"));
724    }
725
726    #[test]
727    fn negotiate_text_wildcard_is_csv() {
728        // `text/*` promises the client any text subtype, so answer with the
729        // text media type we can produce rather than 406.
730        assert_eq!(
731            negotiate_results_format(Some("text/*")).unwrap(),
732            QueryResultsFormat::Csv
733        );
734    }
735
736    #[test]
737    fn negotiate_unsupported_accept_is_406() {
738        for accept in [
739            "application/x-unknown",
740            "text/turtle", // Turtle is a graph format, not a results format
741            "image/png, video/webm",
742        ] {
743            let error = negotiate_results_format(Some(accept)).unwrap_err();
744            assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE, "{accept}");
745            assert!(error.to_string().contains(accept));
746        }
747        assert!(
748            negotiate_graph_format(Some("application/x-unknown"))
749                .unwrap_err()
750                .to_string()
751                .contains("application/x-unknown")
752        );
753    }
754
755    #[test]
756    fn negotiate_wildcard_rescues_unsupported_entries() {
757        assert_eq!(
758            negotiate_results_format(Some("image/png, */*")).unwrap(),
759            QueryResultsFormat::Json
760        );
761        assert_eq!(
762            negotiate_graph_format(Some("image/png, */*")).unwrap(),
763            RdfFormat::Turtle
764        );
765    }
766
767    #[test]
768    fn negotiate_graph_defaults_to_turtle() {
769        assert_eq!(negotiate_graph_format(None).unwrap(), RdfFormat::Turtle);
770        assert_eq!(
771            negotiate_graph_format(Some("*/*")).unwrap(),
772            RdfFormat::Turtle
773        );
774        assert_eq!(
775            negotiate_graph_format(Some("application/n-triples")).unwrap(),
776            RdfFormat::NTriples
777        );
778    }
779
780    #[test]
781    fn negotiate_graph_wildcards_pick_producible_formats() {
782        // `text/turtle` and `application/rdf+xml` are the canonical members
783        // of the two wildcard ranges we can satisfy for graph responses.
784        assert_eq!(
785            negotiate_graph_format(Some("text/*")).unwrap(),
786            RdfFormat::Turtle
787        );
788        assert_eq!(
789            negotiate_graph_format(Some("application/*")).unwrap(),
790            RdfFormat::RdfXml
791        );
792    }
793
794    #[test]
795    fn negotiate_graph_accepts_json_ld_and_quad_formats() {
796        assert!(matches!(
797            negotiate_graph_format(Some("application/ld+json")).unwrap(),
798            RdfFormat::JsonLd { .. }
799        ));
800        // Media-type parameters are ignored.
801        assert!(matches!(
802            negotiate_graph_format(Some(
803                "application/ld+json;profile=http://www.w3.org/ns/json-ld#streaming"
804            ))
805            .unwrap(),
806            RdfFormat::JsonLd { .. }
807        ));
808        assert_eq!(
809            negotiate_graph_format(Some("application/trig")).unwrap(),
810            RdfFormat::TriG
811        );
812        assert_eq!(
813            negotiate_graph_format(Some("application/n-quads")).unwrap(),
814            RdfFormat::NQuads
815        );
816    }
817
818    #[test]
819    fn serialize_graph_json_ld_is_valid_json() {
820        let triple = waratah_storage::Triple::new(
821            NamedNode::new("http://ex/alice").unwrap(),
822            NamedNode::new("http://ex/name").unwrap(),
823            Literal::from("Alice"),
824        );
825        let results = QueryResults::Graph {
826            triples: vec![triple],
827        };
828        let (body, media) = serialize_query_results(&results, Some("application/ld+json")).unwrap();
829        assert_eq!(media, "application/ld+json");
830        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid JSON-LD");
831        let text = json.to_string();
832        assert!(text.contains("http://ex/alice"), "{text}");
833        assert!(text.contains("Alice"), "{text}");
834    }
835
836    fn sample_results() -> QueryResults {
837        QueryResults::Solutions {
838            variables: vec![
839                Variable::new("s").unwrap(),
840                Variable::new("label").unwrap(),
841                Variable::new("n").unwrap(),
842            ],
843            solutions: vec![vec![
844                Some(Term::from(NamedNode::new("http://ex/alice").unwrap())),
845                Some(Term::from(
846                    Literal::new_language_tagged_literal("Alice", "en").unwrap(),
847                )),
848                Some(Term::from(Literal::from(42_i32))),
849            ]],
850        }
851    }
852
853    fn projected_from_results(results: &QueryResults) -> ProjectedSolutions {
854        let QueryResults::Solutions {
855            variables,
856            solutions,
857        } = results
858        else {
859            panic!("expected SELECT results");
860        };
861        let mut strings = new_str_hash_map();
862        // Never written by this helper (the runtime projection files blob
863        // payloads by blob id from the mint/store; re-encoded test terms
864        // carry no payload pairs) — kept so the helper's shape mirrors
865        // `ProjectedSolutions`.
866        let blobs = new_str_blob_map();
867        let mut encoded_rows = Vec::with_capacity(solutions.len());
868        for row in solutions {
869            let mut encoded_row = Vec::with_capacity(row.len());
870            for cell in row {
871                match cell {
872                    None => encoded_row.push(None),
873                    Some(term) => {
874                        let encoded = encode_term(term).unwrap();
875                        for (hash, raw) in strings_entries_for_term(term, &encoded) {
876                            strings.insert(hash, raw);
877                        }
878                        // Mirror the runtime seeding's blob half: the mint's
879                        // content-addressed payload pairs under the blob id
880                        // (the retired geo-key lexical carriage lives only
881                        // in this helper's history). Non-geo literals carry
882                        // no pairs, so plain `From` re-encoding suffices.
883                        let _ = &encoded;
884                        encoded_row.push(Some(encoded));
885                    }
886                }
887            }
888            encoded_rows.push(encoded_row);
889        }
890        ProjectedSolutions {
891            variables: variables.clone(),
892            solutions: EncodedSolutions::from_optional_rows(
893                QueryContext::from_snapshot(SnapshotId::latest()).term_dict(),
894                variables.clone(),
895                encoded_rows,
896            )
897            .unwrap(),
898            strings,
899            blobs,
900        }
901    }
902
903    fn serialize_projected(projected: &ProjectedSolutions, format: QueryResultsFormat) -> Vec<u8> {
904        let mut buffer = Vec::new();
905        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
906        write_select_solutions(projected, format, &mut buffer, &ctx).unwrap();
907        buffer
908    }
909
910    #[test]
911    fn serialize_ask_json_is_a_boolean_result() {
912        let (body, media) = serialize_query_results(&QueryResults::Boolean(true), None).unwrap();
913        assert_eq!(media, "application/sparql-results+json");
914        let text = String::from_utf8(body).unwrap();
915        assert!(text.contains("\"boolean\":true"), "{text}");
916        assert!(text.contains("\"head\""), "{text}");
917    }
918
919    #[test]
920    fn serialize_select_json_contains_bindings() {
921        let (body, media) = serialize_query_results(&sample_results(), None).unwrap();
922        assert_eq!(media, "application/sparql-results+json");
923        let text = String::from_utf8(body).unwrap();
924        assert!(text.contains("\"s\""));
925        assert!(text.contains("http://ex/alice"));
926        assert!(text.contains("42"));
927    }
928
929    #[test]
930    fn serialize_select_csv_is_lossy_plain_cells() {
931        let (body, media) = serialize_query_results(&sample_results(), Some("text/csv")).unwrap();
932        assert_eq!(media, "text/csv; charset=utf-8");
933        let text = String::from_utf8(body).unwrap();
934        assert!(text.contains("s,label,n"));
935        assert!(text.contains("http://ex/alice,Alice,42"));
936        assert!(!text.contains('<'), "CSV must not Turtle-wrap IRIs");
937        assert!(!text.contains("@en"), "CSV must drop language tags");
938    }
939
940    #[test]
941    fn serialize_select_tsv_uses_turtle_term_syntax() {
942        let (body, media) =
943            serialize_query_results(&sample_results(), Some("text/tab-separated-values")).unwrap();
944        assert_eq!(media, "text/tab-separated-values; charset=utf-8");
945        let text = String::from_utf8(body).unwrap();
946        assert!(text.contains("?s\t?label\t?n"));
947        assert!(text.contains("<http://ex/alice>"));
948        assert!(text.contains("\"Alice\"@en"));
949        assert!(text.contains("42"));
950    }
951
952    #[test]
953    fn termref_select_matches_decoded_query_results() {
954        let decoded = sample_results();
955        let projected = projected_from_results(&decoded);
956        for accept in [
957            None,
958            Some("application/sparql-results+xml"),
959            Some("text/csv"),
960            Some("text/tab-separated-values"),
961        ] {
962            let (from_terms, media) = serialize_query_results(&decoded, accept).unwrap();
963            let format = negotiate_results_format(accept).unwrap();
964            let from_refs = serialize_projected(&projected, format);
965            assert_eq!(
966                String::from_utf8(from_refs).unwrap(),
967                String::from_utf8(from_terms).unwrap(),
968                "TermRef serialize diverged from decoded Terms ({media})"
969            );
970        }
971    }
972
973    #[test]
974    fn serialize_graph_turtle_contains_triple() {
975        let triple = waratah_storage::Triple::new(
976            NamedNode::new("http://ex/alice").unwrap(),
977            NamedNode::new("http://ex/name").unwrap(),
978            Literal::from("Alice"),
979        );
980        let results = QueryResults::Graph {
981            triples: vec![triple],
982        };
983        let (body, media) = serialize_query_results(&results, Some("text/turtle")).unwrap();
984        assert_eq!(media, "text/turtle");
985        let text = String::from_utf8(body).unwrap();
986        assert!(text.contains("http://ex/alice"));
987        assert!(text.contains("Alice"));
988    }
989
990    #[tokio::test]
991    async fn first_chunk_contains_sparql_results_head() {
992        let decoded = sample_results();
993        let QueryResults::Solutions {
994            variables,
995            solutions,
996        } = decoded
997        else {
998            panic!("expected SELECT");
999        };
1000        let one = solutions[0].clone();
1001        let many = QueryResults::Solutions {
1002            variables,
1003            solutions: vec![one; 2048],
1004        };
1005        let projected = projected_from_results(&many);
1006        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
1007        let mut rx = spawn_select_stream(projected, QueryResultsFormat::Json, ctx);
1008        let first = rx.recv().await.expect("head chunk").expect("head ok");
1009        let text = String::from_utf8(first.to_vec()).unwrap();
1010        assert!(text.contains("\"head\""), "{text}");
1011        assert!(text.contains("\"bindings\""), "{text}");
1012        assert!(
1013            first.len() < SELECT_HTTP_CHUNK,
1014            "head flush must not wait for a 64 KiB row buffer ({})",
1015            first.len()
1016        );
1017        assert!(
1018            !text.contains("http://ex/alice"),
1019            "head chunk must leave before solution rows: {text}"
1020        );
1021    }
1022}