Debian Codegraph @

src/rdflib_endpoint/sparql_router.py

raw
1 import logging
2 import os
3 import re
4 from importlib import resources
5 from typing import Any, Callable, Dict, List, Optional, Union
6 from urllib import parse
7
8 from fastapi import APIRouter, Query, Request, Response
9 from fastapi.responses import JSONResponse
10 from rdflib import RDF, BNode, Dataset, Graph, Literal, URIRef
11 from rdflib.namespace import DC, RDFS
12 from rdflib.plugins.sparql import CUSTOM_EVALS, prepareQuery, prepareUpdate
13 from rdflib.plugins.sparql.evaluate import evalPart
14 from rdflib.plugins.sparql.evalutils import _eval
15 from rdflib.plugins.sparql.parserutils import CompValue
16 from rdflib.plugins.sparql.sparql import QueryContext, SPARQLError
17 from rdflib.query import Processor
18
19 from rdflib_endpoint.utils import (
20 API_RESPONSES,
21 FORMATS,
22 GENERIC_CONTENT_TYPE_TO_RDFLIB_FORMAT,
23 GRAPH_CONTENT_TYPE_TO_RDFLIB_FORMAT,
24 SD,
25 SPARQL_RESULT_CONTENT_TYPE_TO_RDFLIB_FORMAT,
26 Defaults,
27 QueryExample,
28 parse_accept_header,
29 )
30
31
32 class SparqlRouter(APIRouter):
33 """Class to deploy a SPARQL endpoint using a RDFLib Graph."""
34
35 def __init__(
36 self,
37 *args: Any,
38 path: str = "/",
39 title: str = Defaults.title,
40 description: str = Defaults.description,
41 version: str = Defaults.version,
42 graph: Union[None, Graph, Dataset] = None,
43 service_description: Union[None, Graph] = None,
44 processor: Union[str, Processor] = "sparql",
45 custom_eval: Optional[Callable[..., Any]] = None,
46 functions: Optional[Dict[str, Callable[..., Any]]] = None,
47 enable_update: bool = False,
48 public_url: str = Defaults.public_url,
49 favicon: str = Defaults.favicon,
50 example_query: str = Defaults.example,
51 example_queries: Optional[Dict[str, QueryExample]] = None,
52 **kwargs: Any,
53 ) -> None:
54 """Create a SPARQL endpoint router.
55
56 The endpoints calls are all defined in this constructor
57 """
58 self.graph = graph if graph is not None else Dataset(default_union=True)
59 """RDFLib Graph for the SPARQL endpoint."""
60 self.service_description = service_description if service_description is not None else Graph()
61 """RDFLib Graph for the SPARQL Service description."""
62 self.functions = functions if functions is not None else {}
63 """Custom SPARQL functions to use in the SPARQL queries."""
64 self.processor = processor
65 """Custom RDFLib SPARQL processor to use for the SPARQL queries."""
66 self.title = title
67 self.description = description
68 self.version = version
69 self.path = path
70 self.public_url = public_url
71 self.example_query = example_query
72 self.example_queries = example_queries
73 self.example_markdown = f"Example query:\n\n```\n{example_query}\n```"
74 self.enable_update = enable_update
75 self.favicon = favicon
76
77 # Instantiate APIRouter
78 super().__init__(
79 *args,
80 responses=API_RESPONSES,
81 **kwargs,
82 )
83
84 # Save custom function in custom evaluation dictionary
85 # Handle multiple functions directly in the evalCustomFunctions function
86 if custom_eval:
87 CUSTOM_EVALS["evalCustomFunctions"] = custom_eval
88 elif len(self.functions) > 0:
89 CUSTOM_EVALS["evalCustomFunctions"] = self.eval_custom_functions
90
91 self.prepare_sd_graph()
92
93 async def handle_sparql_request(
94 request: Request, query: Optional[str] = None, update: Optional[str] = None
95 ) -> Response:
96 """Handle SPARQL requests to the GET and POST endpoints"""
97 if query and update:
98 return JSONResponse(
99 status_code=400,
100 content={"message": "Cannot do both query and update"},
101 )
102
103 if not query and not update:
104 if str(request.headers.get("accept", "")).startswith("text/html"):
105 return self.serve_yasgui()
106 # If not asking HTML, return the SPARQL endpoint service description
107 if request.headers.get("accept") == "text/turtle":
108 return Response(
109 self.service_description.serialize(format="turtle"),
110 media_type="text/turtle",
111 )
112 else:
113 return Response(
114 self.service_description.serialize(format="xml"),
115 media_type="application/xml",
116 )
117
118 # Pretty print the query object
119 # from rdflib.plugins.sparql.algebra import pprintAlgebra
120 # parsed_query = parser.parseQuery(query)
121 # tq = algebraTranslateQuery(parsed_query)
122 # pprintAlgebra(tq)
123
124 graph_ns = dict(self.graph.namespaces())
125
126 if query:
127 try:
128 parsed_query = prepareQuery(query, initNs=graph_ns)
129 query_results = self.graph.query(parsed_query, processor=self.processor)
130
131 # Format and return results depending on Accept mime type in request header
132 mime_types = parse_accept_header(request.headers.get("accept", Defaults.content_type))
133
134 query_operation = re.sub(r"(\w)([A-Z])", r"\1 \2", parsed_query.algebra.name)
135
136 if query_operation == "Construct Query":
137 content_type_to_rdflib_format = {
138 **GRAPH_CONTENT_TYPE_TO_RDFLIB_FORMAT,
139 **GENERIC_CONTENT_TYPE_TO_RDFLIB_FORMAT,
140 }
141 else:
142 content_type_to_rdflib_format = {
143 **SPARQL_RESULT_CONTENT_TYPE_TO_RDFLIB_FORMAT,
144 **GENERIC_CONTENT_TYPE_TO_RDFLIB_FORMAT,
145 }
146
147 # Handle cases that are more complicated, like it includes multiple
148 # types, extra information, etc.
149 output_mime_type = Defaults.content_type
150 for mime_type in mime_types:
151 if mime_type in content_type_to_rdflib_format:
152 output_mime_type = mime_type
153 # Use the first mime_type that matches
154 break
155
156 # Convert generic mime types to specific ones
157 if query_operation == "Construct Query" or query_operation == "Describe Query":
158 if output_mime_type == "text/csv":
159 output_mime_type = "text/turtle"
160 elif output_mime_type == "application/json":
161 output_mime_type = "application/ld+json"
162 elif output_mime_type == "application/xml":
163 output_mime_type = "application/rdf+xml"
164 else:
165 pass
166
167 if query_operation == "Select Query" or query_operation == "Ask Query":
168 if output_mime_type == "text/csv":
169 output_mime_type = "application/sparql-results+csv"
170 elif output_mime_type == "application/json":
171 output_mime_type = "application/sparql-results+json"
172 elif output_mime_type == "application/xml":
173 output_mime_type = "application/sparql-results+xml"
174 else:
175 pass
176
177 try:
178 rdflib_format = content_type_to_rdflib_format.get(output_mime_type, output_mime_type)
179 response = Response(
180 query_results.serialize(format=rdflib_format),
181 media_type=output_mime_type,
182 )
183 except Exception as e:
184 logging.error(f"Error serializing the SPARQL query results with RDFLib: {e}")
185 return JSONResponse(
186 status_code=422,
187 content={"message": f"Error serializing the SPARQL query results with RDFLib: {e}"},
188 )
189 else:
190 return response
191 except Exception as e:
192 logging.error(f"Error executing the SPARQL query on the RDFLib Graph: {e}")
193 return JSONResponse(
194 status_code=400,
195 content={"message": f"Error executing the SPARQL query on the RDFLib Graph: {e}"},
196 )
197 else: # Update
198 if not self.enable_update:
199 return JSONResponse(
200 status_code=403, content={"message": "INSERT and DELETE queries are not allowed."}
201 )
202 if rdflib_apikey := os.environ.get("RDFLIB_APIKEY"):
203 authorized = False
204 if auth_header := request.headers.get("Authorization"): # noqa: SIM102
205 if auth_header.startswith("Bearer ") and auth_header[7:] == rdflib_apikey:
206 authorized = True
207 if not authorized:
208 return JSONResponse(status_code=403, content={"message": "Invalid API KEY."})
209 try:
210 prechecked_update: str = update # type: ignore
211 parsed_update = prepareUpdate(prechecked_update, initNs=graph_ns)
212 self.graph.update(parsed_update, "sparql")
213 return Response(status_code=204)
214 except Exception as e:
215 logging.error(f"Error executing the SPARQL update on the RDFLib Graph: {e}")
216 return JSONResponse(
217 status_code=400,
218 content={"message": f"Error executing the SPARQL update on the RDFLib Graph: {e}"},
219 )
220
221 # TODO: use add_api_route? https://github.com/tiangolo/fastapi/blob/d666ccb62216e45ca78643b52c235ba0d2c53986/fastapi/routing.py#L548
222 @self.get(
223 self.path,
224 name="SPARQL endpoint",
225 description=self.example_markdown,
226 responses=API_RESPONSES,
227 )
228 async def get_sparql_endpoint(
229 request: Request,
230 query: Optional[str] = Query(None),
231 ) -> Response:
232 """Send a SPARQL query to be executed through HTTP GET operation.
233
234 :param request: The HTTP GET request
235 :param query: SPARQL query input.
236 """
237 return await handle_sparql_request(request, query=query)
238
239 @self.post(
240 path,
241 name="SPARQL endpoint",
242 description=self.example_markdown,
243 responses=API_RESPONSES,
244 )
245 async def post_sparql_endpoint(request: Request) -> Response:
246 """Send a SPARQL query to be executed through HTTP POST operation.
247
248 :param request: The HTTP POST request with a .body()
249 """
250 request_body = await request.body()
251 body = request_body.decode("utf-8")
252 content_type = request.headers.get("content-type", "")
253 if "application/sparql-query" in content_type:
254 query = body
255 update = None
256 elif "application/sparql-update" in content_type:
257 query = None
258 update = body
259 elif "application/x-www-form-urlencoded" in content_type:
260 request_params = parse.parse_qsl(body)
261 query_params = [kvp[1] for kvp in request_params if kvp[0] == "query"]
262 query = parse.unquote(query_params[0]) if query_params else None
263 update_params = [kvp[1] for kvp in request_params if kvp[0] == "update"]
264 update = parse.unquote(update_params[0]) if update_params else None
265 # TODO: handle params `using-graph-uri` and `using-named-graph-uri`
266 # https://www.w3.org/TR/sparql11-protocol/#update-operation
267 elif not body and request.query_params:
268 # Blazegraph SERVICE calls uses query_params, not body
269 query = parse.unquote(request.query_params.get("query", ""))
270 update = request.query_params.get("update")
271 else:
272 # Response with the service description
273 query = None
274 update = None
275 return await handle_sparql_request(request, query, update)
276
277 def eval_custom_functions(self, ctx: QueryContext, part: CompValue) -> List[Any]:
278 """Retrieve variables from a SPARQL-query, then execute registered SPARQL functions
279 The results are then stored in Literal objects and added to the query results.
280
281 :param ctx: <class 'rdflib.plugins.sparql.sparql.QueryContext'>
282 :param part: <class 'rdflib.plugins.sparql.parserutils.CompValue'>
283 :return: <class 'rdflib.plugins.sparql.processor.SPARQLResult'>
284 """
285 # This part holds basic implementation for adding new functions
286 if part.name == "Extend":
287 query_results: List[Any] = []
288 # Information is retrieved and stored and passed through a generator
289 for eval_part in evalPart(ctx, part.p):
290 # Checks if the function is a URI (custom function)
291 if hasattr(part.expr, "iri"):
292 # Iterate through the custom functions passed in the constructor
293 for function_uri, custom_function in self.functions.items():
294 # Check if URI correspond to a registered custom function
295 if part.expr.iri == URIRef(function_uri):
296 # Execute each function
297 query_results, ctx, part, _ = custom_function(query_results, ctx, part, eval_part)
298
299 else:
300 # For built-in SPARQL functions (that are not URIs)
301 evaluation: List[Any] = [_eval(part.expr, eval_part.forget(ctx, _except=part._vars))]
302 if isinstance(evaluation[0], SPARQLError):
303 raise evaluation[0]
304 # Append results for built-in SPARQL functions
305 for result in evaluation:
306 query_results.append(eval_part.merge({part.var: Literal(result)}))
307
308 return query_results
309 raise NotImplementedError()
310
311 def serve_yasgui(self) -> Response:
312 """Serve YASGUI interface"""
313 import json
314
315 with resources.open_text("rdflib_endpoint", "yasgui.html") as f:
316 html_str = f.read()
317 html_str = html_str.replace("$TITLE", self.title)
318 html_str = html_str.replace("$DESCRIPTION", self.description)
319 html_str = html_str.replace("$FAVICON", self.favicon)
320 html_str = html_str.replace("$EXAMPLE_QUERY", self.example_query)
321 html_str = html_str.replace("$EXAMPLE_QUERIES", json.dumps(self.example_queries))
322 return Response(content=html_str, media_type="text/html")
323
324 def prepare_sd_graph(self) -> None:
325 """Prepare the endpoint Service Description graph"""
326 # https://www.w3.org/TR/sparql12-service-description/
327 self.service_description.bind("rdfs", "http://www.w3.org/2000/01/rdf-schema#")
328 self.service_description.bind("dc", "http://purl.org/dc/elements/1.1/")
329 self.service_description.bind("sd", SD)
330 self.service_description.bind("ent", "http://www.w3.org/ns/entailment/")
331 self.service_description.bind("prof", "http://www.w3.org/ns/owl-profile/")
332 self.service_description.bind("void", "http://rdfs.org/ns/void#")
333 self.service_description.bind("formats", FORMATS)
334 sd_subj = next(self.service_description.subjects(SD.endpoint, None), None) or BNode()
335
336 if (sd_subj, RDF.type, SD.Service) not in self.service_description:
337 self.service_description.add((sd_subj, RDF.type, SD.Service))
338
339 # Check and add endpoint, label and description
340 if not any(self.service_description.triples((sd_subj, SD.endpoint, None))):
341 self.service_description.add((sd_subj, SD.endpoint, URIRef(self.public_url)))
342 if not any(self.service_description.triples((sd_subj, RDFS.label, None))):
343 self.service_description.add((sd_subj, RDFS.label, Literal(self.title)))
344 if not any(self.service_description.triples((sd_subj, DC.description, None))):
345 self.service_description.add((sd_subj, DC.description, Literal(self.description)))
346
347 # Check and add supported language
348 if not any(self.service_description.triples((sd_subj, SD.supportedLanguage, SD.SPARQL11Query))):
349 self.service_description.add((sd_subj, SD.supportedLanguage, SD.SPARQL11Query))
350 if self.enable_update:
351 self.service_description.add((sd_subj, SD.supportedLanguage, SD.SPARQL11Update))
352
353 # Add features
354 if (
355 isinstance(self.graph, Dataset)
356 and getattr(self.graph, "default_union", False)
357 and not any(self.service_description.triples((sd_subj, SD.feature, SD.BasicFederatedQuery)))
358 ):
359 self.service_description.add((sd_subj, SD.feature, SD.UnionDefaultGraph))
360 if not any(self.service_description.triples((sd_subj, SD.feature, SD.BasicFederatedQuery))):
361 self.service_description.add((sd_subj, SD.feature, SD.BasicFederatedQuery))
362
363 # Add result formats
364 if not any(self.service_description.triples((sd_subj, SD.resultFormat, FORMATS.SPARQL_Results_JSON))):
365 self.service_description.add((sd_subj, SD.resultFormat, FORMATS.SPARQL_Results_JSON))
366 if not any(self.service_description.triples((sd_subj, SD.resultFormat, FORMATS.SPARQL_Results_CSV))):
367 self.service_description.add((sd_subj, SD.resultFormat, FORMATS.SPARQL_Results_CSV))
368 if not any(self.service_description.triples((sd_subj, SD.resultFormat, FORMATS.Turtle))):
369 self.service_description.add((sd_subj, SD.resultFormat, FORMATS.Turtle))
370 if not any(self.service_description.triples((sd_subj, SD.resultFormat, FORMATS.RDF_XML))):
371 self.service_description.add((sd_subj, SD.resultFormat, FORMATS.RDF_XML))
372
373 # Add input formats
374 if not any(self.service_description.triples((sd_subj, SD.inputFormat, None))):
375 self.service_description.add((sd_subj, SD.inputFormat, FORMATS.RDF_XML))
376 self.service_description.add((sd_subj, SD.inputFormat, FORMATS.Turtle))
377 self.service_description.add((sd_subj, SD.inputFormat, FORMATS.JSON_LD))
378 self.service_description.add((sd_subj, SD.inputFormat, FORMATS.N_Triples))
379 self.service_description.add((sd_subj, SD.inputFormat, FORMATS.N_Quads))
380 self.service_description.add((sd_subj, SD.inputFormat, FORMATS.TriG))
381
382 # Check and add entailment regime
383 # sd_default_entailment_regime = URIRef("http://www.w3.org/ns/sparql-service-description#defaultEntailmentRegime")
384 # ent_rdfs = URIRef("http://www.w3.org/ns/entailment/RDFS")
385 # if not any(self.service_description.triples((service_uri, sd_default_entailment_regime, ent_rdfs))):
386 # self.service_description.add((service_uri, sd_default_entailment_regime, ent_rdfs))
387
388 # Check if default dataset exists, if not add it
389 has_dataset = False
390 dataset_node = None
391 for _s, _p, o in self.service_description.triples((sd_subj, SD.defaultDataset, None)):
392 has_dataset = True
393 dataset_node = o
394 break
395
396 if not has_dataset:
397 dataset_node = BNode()
398 self.service_description.add((sd_subj, SD.defaultDataset, dataset_node))
399 self.service_description.add((dataset_node, RDF.type, SD.Dataset))
400
401 # Add default graph to the dataset
402 graph_node = BNode()
403 self.service_description.add((dataset_node, SD.defaultGraph, graph_node))
404 self.service_description.add((graph_node, RDF.type, SD.Graph))
405
406 # Add named graphs to the dataset
407 if isinstance(self.graph, Dataset):
408 # Get the list of distinct graph names with a SPARQL query
409 results: Any = self.graph.query("SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }")
410
411 for row in results:
412 named_graph_node = BNode()
413 graph_node = BNode()
414
415 # Add the named graph reference
416 self.service_description.add((dataset_node, SD.namedGraph, named_graph_node))
417 self.service_description.add((named_graph_node, RDF.type, SD.NamedGraph))
418 self.service_description.add((named_graph_node, SD.name, row.g))
419 # self.service_description.add((named_graph_node, SD.entailmentRegime, URIRef("http://www.w3.org/ns/entailment/OWL-RDF-Based")))
420 # self.service_description.add((named_graph_node, SD.supportedEntailmentProfile, URIRef("http://www.w3.org/ns/owl-profile/RL")))
421
422 # Add graph metadata
423 self.service_description.add((named_graph_node, SD.graph, graph_node))
424 self.service_description.add((graph_node, RDF.type, SD.Graph))
425
426 # Count triples in the named graph and add it to the description
427 triple_count_query = f"SELECT (COUNT(*) AS ?count) WHERE {{ GRAPH <{row.g}> {{ ?s ?p ?o }} }}"
428 count_result: Any = self.graph.query(triple_count_query)
429 triple_count = next(iter(count_result), [Literal(0)])[0]
430 # result_row: Any = next(iter(count_result), None)
431 # triple_count = result_row.count if result_row else Literal(0)
432 self.service_description.add((graph_node, URIRef("http://rdfs.org/ns/void#triples"), triple_count))
433
434 # Add custom functions to the service description
435 for custom_function_uri in self.functions:
436 function_uri = URIRef(custom_function_uri)
437
438 if (function_uri, RDF.type, SD.Function) not in self.service_description:
439 self.service_description.add((function_uri, RDF.type, SD.Function))
440 if (sd_subj, SD.extensionFunction, function_uri) not in self.service_description:
441 self.service_description.add((sd_subj, SD.extensionFunction, function_uri))
442 # return self.service_description
443
444 # Add custom functions URI to the service description
445 for custom_function_uri in self.functions:
446 self.service_description.add(
447 (
448 URIRef(custom_function_uri),
449 RDF.type,
450 SD.Function,
451 )
452 )
453 self.service_description.add(
454 (
455 sd_subj,
456 SD.extensionFunction,
457 URIRef(custom_function_uri),
458 )
459 )