AtteanX/Endpoint/Protocol.pm untested

filter: Statementstmt 0.0% 0 / 281 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 56 MC/DCmcdc 0.0% 0 / 36 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 494 CC 50 SCAR 69.8
CC
50
Cov
0%
run
1722.0
service_description
110.0
log_query
2.0
CRAP 1070.7
1 use v5.14;
2 use warnings;
3  
4 =head1 NAME
5  
6 AtteanX::Endpoint::Protocol - SPARQL 1.1 Protocol
7  
8 =head1 VERSION
9  
10 This document describes AtteanX::Endpoint::Protocol version 0.004
11  
12 =head1 SYNOPSIS
13  
14 plackup -p 9091 scripts/endpoint.psgi
15  
16 =head1 DESCRIPTION
17  
18 The AtteanX::Endpoint::Protocol class implements the logic for the
19 SPARQL Protocol.
20  
21 =head1 ATTRIBUTES
22  
23 =over 4
24  
25 =item C<< graph >>
26  
27 The L<Attean::API::IRI> of the graph in the model that represents the default graph.
28  
29 =item C<< model >>
30  
31 =item C<< conf >>
32  
33 =item C<< planner >>
34  
35 =back
36  
37 =head1 METHODS
38  
39 =over 4
40  
41 =cut
42  
43 package AtteanX::Endpoint::Protocol 0.004 {
44 use Moo;
45 use Attean;
46 use Encode qw(encode_utf8);
47 use Scalar::Util qw(blessed);
48 use Attean::RDF qw(iri);
49 use Attean::DatasetModel;
50 use UUID::Tiny ':std';
51 use Module::Load::Conditional qw(can_load);
52 use Types::Standard qw(ConsumerOf CodeRef HashRef ArrayRef Str Int);
53 use HTML::HTML5::Writer qw(DOCTYPE_XHTML_RDFA);
54 use namespace::clean;
55  
56 with 'MooX::Log::Any';
57  
58 has 'planner' => (
59 is => 'ro',
60 isa => ConsumerOf['Attean::API::QueryPlanner'],
61 required => 1,
62 default => sub {
63 Attean::IDPQueryPlanner->new();
64 }
65 );
66 has 'model' => (is => 'ro', isa => ConsumerOf['Attean::API::Model'], required => 1);
67 has 'conf' => (is => 'ro', isa => HashRef, required => 1);
68 has 'graph' => (is => 'ro', isa => ConsumerOf['Attean::API::IRI'], required => 1);
69  
70 =item C<< run( $request, $response ) >>
71  
72 Extract the SPARQL Protocol request from C<< $request >>, run the corresponding
73 query/update, and populate C<< $response >> with results or error information.
74  
75 =cut
76  
77 sub run {
78 my $self = shift;
79 my $req = shift;
80 my $env = $req->env;
81 my $response = shift;
82  
83 my $config = $self->{conf};
84 my $model = $self->{model};
85 my $headers = $req->headers;
86 my $type = $headers->header('Accept') || 'application/sparql-results+xml';
87 if (my $t = $req->param('media-type')) {
88 $type = $t;
89 $headers->header('Accept' => $type);
90 }
91
92 my $ae = $req->headers->header('Accept-Encoding') || '';
93
94 my $sparql;
95 my $content;
96 my $ct = $req->header('Content-type');
97 my $is_update = 0;
98 if ($req->method !~ /^(GET|POST)$/i) {
99 my $method = uc($req->method);
100 $content = "Unexpected method $method (expecting GET or POST)";
101 $self->log_error( $req, $content );
102 $response->header('Allow' => 'GET, POST');
103 die AtteanX::Endpoint::ClientError->new(code => 405, message => 'Method not allowed', uri => 'http://id.kasei.us/rdf-endpoint/error/bad_http_method');
104 } elsif (defined($ct) and $ct eq 'application/sparql-query') {
105 $sparql = $req->content;
106 } elsif (defined($ct) and $ct eq 'application/sparql-update') {
107 $is_update = 1;
108 if ($config->{endpoint}{update} and $req->method eq 'POST') {
109 $sparql = $req->content;
110 }
111 } elsif ($req->param('query')) {
112 my @sparql = $req->param('query');
113 if (scalar(@sparql) > 1) {
114 $content = "More than one query string submitted";
115 $self->log_error( $req, $content );
116 die AtteanX::Endpoint::ClientError->new(code => 400, message => 'Multiple query strings not allowed', uri => 'http://id.kasei.us/rdf-endpoint/error/multiple_queries');
117 } else {
118 $sparql = $sparql[0];
119 }
120 } elsif ($req->param('update')) {
121 $is_update = 1;
122 my @sparql = $req->param('update');
123 if (scalar(@sparql) > 1) {
124 $content = "More than one update string submitted";
125 $self->log_error( $req, $content );
126 die AtteanX::Endpoint::ClientError->new(code => 400, message => 'Multiple update strings not allowed', uri => 'http://id.kasei.us/rdf-endpoint/error/multiple_updates');
127 }
128
129 if ($config->{endpoint}{update} and $req->method eq 'POST') {
130 $sparql = $sparql[0];
131 } elsif ($req->method ne 'POST') {
132 my $method = $req->method;
133 $content = "Update operations must use POST";
134 $self->log_error( $req, $content );
135 $response->header('Allow' => 'POST');
136 die AtteanX::Endpoint::ClientError->new(code => 405, message => "$method Not Allowed for Update Operation", uri => 'http://id.kasei.us/rdf-endpoint/error/bad_http_method_update');
137 }
138 }
139
140 my $dir = $ENV{ATTEAN_ENDPOINT_SHAREDIR} || File::Spec->catdir((eval { dist_dir('AtteanX-Endpoint') } || 'share'), 'endpoint');
141 if ($sparql) {
142 my %args;
143 $args{ update } = 1 if ($config->{endpoint}{update} and $req->method eq 'POST');
144 $args{ load_data } = 1 if ($config->{endpoint}{load_data});
145
146 my $base = Attean::IRI->new( value => $req->base->as_string );
147 my $parser = Attean->get_parser('SPARQL')->new(base => $base);
148 $parser->update(1) if ($args{update});
149 my ($algebra) = eval { $args{update} ? $parser->parse_update($sparql, base => $base) : $parser->parse($sparql, base => $base) };
150
151 if ($@ or not($algebra)) {
152 my $error = $@ || 'Internal error';
153 $self->log_error( $req, $error );
154 my $eclass = ($error =~ /Expect|Syntax/) ? 'AtteanX::Endpoint::ClientError' : 'AtteanX::Endpoint::ServerError';
155 if ($req->method ne 'POST' and $error =~ /read-only queries/sm) {
156 $error = 'Updates must use a HTTP POST request.';
157 die $eclass->new(message => 'Updates must use a HTTP POST request', uri => 'http://id.kasei.us/rdf-endpoint/error/bad_http_method_update');
158 } else {
159 die $eclass->new(message => 'SPARQL query/update parse error', uri => 'http://id.kasei.us/rdf-endpoint/error/parse_error', details => { error => $error, sparql => $sparql });
160 }
161 }
162
163 my $protocol_specifies_query_dataset = 0;
164 my $protocol_specifies_update_dataset = 0;
165 my @default_graphs = ($self->graph);
166 {
167 my @default = map { iri($_) } $req->parameters->get_all('default-graph-uri');
168 my @named = map { iri($_) } $req->parameters->get_all('named-graph-uri');
169 if (scalar(@default) or scalar(@named)) {
170 $protocol_specifies_query_dataset = 1;
171 if ($is_update) {
172 if (scalar(@default)) {
173 die AtteanX::Endpoint::ClientError->new(
174 code => 400,
175 message => 'Unexpected default-graph-uri specified in update request',
176 uri => 'http://id.kasei.us/rdf-endpoint/error/invalid_update_dataset'
177 );
178 } else {
179 die AtteanX::Endpoint::ClientError->new(
180 code => 400,
181 message => 'Unexpected named-graph-uri specified in update request',
182 uri => 'http://id.kasei.us/rdf-endpoint/error/invalid_update_dataset'
183 );
184 }
185 }
186 $model = Attean::MutableDatasetModel->new( model => $model, graphs => [@named, @default] );
187 @default_graphs = scalar(@default) ? @default : (Attean::IRI->new('urn:uuid:' . uc(uuid_to_string(create_uuid())))); # some default graph that will not match any data
188 }
189 }
190
191 my @update_default;
192 my @update_named;
193 {
194 @update_default = map { iri($_) } $req->parameters->get_all('using-graph-uri');
195 @update_named = map { iri($_) } $req->parameters->get_all('using-named-graph-uri');
196 if (scalar(@update_named) or scalar(@update_default)) {
197 if ($is_update) {
198 my $specifies_dataset = 0;
199 $algebra->walk( prefix => sub {
200 my $a = shift;
201 if ($a->isa('Attean::Algebra::Modify')) {
202 $specifies_dataset ||= $a->specifies_dataset;
203 }
204 });
205 if ($specifies_dataset) {
206 die AtteanX::Endpoint::ClientError->new(
207 code => 400,
208 message => 'Update request specifies dataset in both using-graph-uri/using-named-graph-uri parameter and USING/WITH clause',
209 uri => 'http://id.kasei.us/rdf-endpoint/error/update_specifies_multiple_datasets'
210 );
211 }
212 } else {
213 if (scalar(@update_default)) {
214 die AtteanX::Endpoint::ClientError->new(
215 code => 400,
216 message => 'Unexpected using-graph-uri specified in query request',
217 uri => 'http://id.kasei.us/rdf-endpoint/error/invalid_query_dataset'
218 );
219 } else {
220 die AtteanX::Endpoint::ClientError->new(
221 code => 400,
222 message => 'Unexpected using-named-graph-uri specified in query request',
223 uri => 'http://id.kasei.us/rdf-endpoint/error/invalid_query_dataset'
224 );
225 }
226 }
227 $protocol_specifies_update_dataset = 1;
228 $model = Attean::MutableDatasetModel->new( model => $model, graphs => [@update_named, @update_default] );
229 @default_graphs = scalar(@update_default) ? @update_default : (Attean::IRI->new('urn:uuid:' . uc(uuid_to_string(create_uuid())))); # some default graph that will not match any data
230 }
231 }
232
233 # my $match = $headers->header('if-none-match') || '';
234 # my $etag = md5_base64( join('#', $self->run_tag, $model->etag, $type, $ae, $sparql) );
235 # if (length($match)) {
236 # if (defined($etag) and ($etag eq $match)) {
237 # $response->status(304);
238 # return $response;
239 # }
240 # }
241
242 {
243 $self->log_query( $req, $sparql );
244 if ($self->log->is_trace) {
245 $self->log->trace("Algebra:\n" . $algebra->as_string);
246 }
247 my $default_graphs = \@default_graphs;
248 my $planner = $self->planner;
249  
250 if ($self->log->is_trace) {
251 $self->log->debug('Planning with default graphs:');
252 foreach my $g (@$default_graphs) {
253 $self->log->trace($g->as_string);
254 }
255 }
256  
257 $planner->suppress_dataset( $protocol_specifies_query_dataset );
258 my $plan = $planner->plan_for_algebra($algebra, $model, $default_graphs);
259 if ($self->log->is_debug) {
260 $self->log->debug("Plan:\n" . $plan->as_string);
261 }
262 eval {
263 my $iter = $plan->evaluate($model);
264 $response->status(200);
265 my $accept = $headers->header('Accept');
266 if (defined($accept) and $accept eq '*/*') {
267 $headers->remove_header('Accept');
268 }
269
270 my $is_ask = $algebra->child->isa('Attean::Algebra::Ask');
271 my $is_rdf = ($algebra->child->isa('Attean::Algebra::Construct') or $algebra->child->isa('Attean::Algebra::Describe'));
272
273 if ($is_update) {
274 $content = "OK\n";
275 $response->headers->content_type('text/plain');
276 } else {
277 my $role = $is_rdf ? 'Attean::API::TripleSerializer' : 'Attean::API::ResultSerializer';
278 my $default = $is_rdf ? 'ntriples' : 'sparqlxml';
279 my %args;
280 if ($is_ask) {
281 $args{restrict} = ['AtteanX::Serializer::SPARQLJSON', 'AtteanX::Serializer::SPARQLXML'];
282 }
283 my $sclass = eval { Attean->negotiate_serializer(request_headers => $headers, role => $role, %args) } // Attean->get_serializer($default);
284 if ($sclass eq 'AtteanX::Serializer::SPARQLHTML') {
285 my $s = $sclass->new(full_document => 0);
286 my $table = $s->serialize_iter_to_bytes($iter);
287 my $tpath = File::Spec->catfile($dir, 'templates', 'results.html');
288 my $template = do { local($/); open(my $fh, '<:utf8', $tpath); <$fh> };
289
290 $template =~ s/\$RESULTS\$/$table/sm;
291 $template =~ s/\$QUERY\$/$sparql/sm;
292 $content = $template;
293 my $stype = $s->canonical_media_type;
294 $response->headers->content_type($stype);
295 } else {
296 my $s = $sclass->new();
297 $content = $s->serialize_iter_to_bytes($iter);
298 my $stype = $s->canonical_media_type;
299 $response->headers->content_type($stype);
300 }
301 }
302 };
303 if ($@) {
304 my $error = $@;
305 $self->log->fatal($error);
306 die AtteanX::Endpoint::ServerError->new(code => 500, message => 'SPARQL query/update execution error', uri => 'http://id.kasei.us/rdf-endpoint/error/execution_error', details => { error => $@, sparql => $sparql });
307 }
308 }
309 } elsif ($req->method eq 'POST') {
310 $content = "POST without recognized query or update";
311 $self->log_error( $req, $content );
312 die AtteanX::Endpoint::ClientError->new(message => 'Missing SPARQL Query/Update String', uri => 'http://id.kasei.us/rdf-endpoint/error/missing_sparql_string');
313 } else {
314 $content = $self->service_description($req, $response, $type, $dir);
315 # $response->headers->header('Link', '</sparql-service-description>; rel="service-desc"');
316 }
317
318 return $content;
319 }
320
321 sub service_description {
322 my $self = shift;
323 my $req = shift;
324 my $response = shift;
325 my $type = shift;
326 my $dir = shift;
327 my $config = $self->{conf};
328  
329 my @serializers;
330 foreach my $sclass (Attean->serializers()) {
331 if (can_load( modules => { $sclass => 0 })) {
332 next unless ($sclass->does('Attean::API::Serializer'));
333 next unless ($sclass->can('canonical_iri'));
334 my $iri = $sclass->canonical_iri;
335 push(@serializers, "<${iri}>");
336 }
337 }
338
339 my @functions = map { "<$_>" } Attean->get_functions();
340 my @aggregates = map { "<$_>" } Attean->get_aggregates();
341  
342 my @features;
343 push(@features, 'sd:DereferencesURIs') if ($config->{endpoint}{load_data});
344  
345 my $env = $req->env;
346 my $sclass = Attean->get_serializer( media_type => $type );
347 if ($sclass and $sclass->does('Attean::API::TripleSerializer')) {
348 my $host = $env->{'HTTP_HOST'};
349 my $scheme = $env->{'psgi.url_scheme'};
350 my $path = $env->{'PATH_INFO'};
351 my $endpoint = "${scheme}://${host}${path}";
352 my $prefixes = <<'END';
353 @prefix sparql: <http://www.w3.org/ns/sparql#> .
354 @prefix sd: <http://www.w3.org/ns/sparql-service-description#> .
355 @prefix void: <http://rdfs.org/ns/void#> .
356 END
357
358 my $formats = scalar(@serializers) ? 'sd:resultFormat ' . join(', ', @serializers) . ' ;' : '';
359 my $functions = scalar(@functions) ? 'sd:extensionFunction ' . join(', ', @functions) . ' ;' : '';
360 my $aggregates = scalar(@aggregates) ? 'sd:extensionAggregate ' . join(', ', @aggregates) . ' ;' : '';
361 my $features = scalar(@features) ? 'sd:feature ' . join(', ', @features) . ' ;' : '';
362
363 my $ttl = <<"END";
364
365 ${prefixes}
366 [] a sd:Service ;
367 sd:endpoint <${endpoint}> ;
368 sd:supportedLanguage sd:SPARQLQuery ;
369 sd:supportedVersion sparql:version-1.2, sparql:version-1.2-basic, sparql:version-1.1, sparql:version-1.0 ;
370  
371 $formats
372  
373 ${functions}
374 ${aggregates}
375 ${features}
376
377 .
378 END
379  
380 # TODO dataset details:
381 # sd:defaultDataset [
382 # a sd:Dataset ;
383 # sd:defaultGraph [
384 # a sd:Graph ;
385 # void:triples 100
386 # ] ;
387 # sd:namedGraph [
388 # a sd:NamedGraph ;
389 # sd:name <http://www.example/named-graph> ;
390 # sd:graph [
391 # a sd:Graph ;
392 # void:triples 2000
393 # ]
394 # ]
395 # ] ;
396  
397  
398 my $parser = Attean->get_parser('Turtle')->new();
399 my $iter = $parser->parse_iter_from_bytes(encode_utf8($ttl));
400 my $map = URI::NamespaceMap->new( {
401 'sparql' => iri('http://www.w3.org/ns/sparql#'),
402 'sd' => iri('http://www.w3.org/ns/sparql-service-description#'),
403 'void' => iri('http://rdfs.org/ns/void#'),
404 'rdf' => iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#'),
405 } );
406 my $ser = $sclass->new( namespaces => $map );
407  
408 $response->status(200);
409 $response->headers->content_type($type);
410 return $ser->serialize_iter_to_bytes($iter);
411 } else {
412 my $stype = 'text/html';
413 my $template = File::Spec->catfile($dir, 'index.html');
414 my $parser = XML::LibXML->new(validation => 0, suppress_errors => 1, no_network => 1, recover => 2);
415 my $doc = $parser->parse_file( $template );
416 # my $gen = RDF::RDFa::Generator->new( style => 'HTML::Head');
417 # $gen->inject_document($doc, $sdmodel);
418
419 my $writer = HTML::HTML5::Writer->new( markup => 'xhtml', doctype => DOCTYPE_XHTML_RDFA );
420 my $content = encode_utf8( $writer->document($doc) );
421 $response->status(200);
422 $response->headers->content_type('text/html');
423 return $content;
424 }
425 }
426  
427 =item C<< log_query ( $request, $sparql ) >>
428  
429 Log the C<< $sparql >> query string after having been parsed from the
430 C<< $request >> but before evaluation.
431  
432 =cut
433  
434 sub log_query {
435 my $self = shift;
436 my $req = shift;
437 my $message = shift;
438 $self->log->info("SPARQL query:\n" . $message);
439 $self->_log( $req, { level => 'info', message => $message } );
440 }
441  
442 =item C<< log_error ( $message ) >>
443  
444 =cut
445  
446 sub log_error {
447 my $self = shift;
448 my $req = shift;
449 my $message = shift;
450 $self->log->error($message);
451 $self->_log( $req, { level => 'error', message => $message } );
452 }
453  
454 sub _log {
455 my $self = shift;
456 my $req = shift;
457 my $data = shift;
458 my $logger = $req->logger || sub {};
459
460 $logger->($data);
461 }
462 }
463  
464 1;
465  
466 __END__