| 1 | use v5.14; | ||
| 2 | use warnings; | ||
| 3 | |||
| 4 | =head1 NAME | ||
| 5 | |||
| 6 | AtteanX::Endpoint::GraphStoreProtocol - SPARQL 1.1 Graph Store Protocol | ||
| 7 | |||
| 8 | =head1 VERSION | ||
| 9 | |||
| 10 | This document describes AtteanX::Endpoint::GraphStoreProtocol version 0.004 | ||
| 11 | |||
| 12 | =head1 SYNOPSIS | ||
| 13 | |||
| 14 | plackup -p 9091 scripts/endpoint.psgi | ||
| 15 | |||
| 16 | =head1 DESCRIPTION | ||
| 17 | |||
| 18 | The AtteanX::Endpoint::GraphStoreProtocol class implements the logic for the | ||
| 19 | SPARQL Graph Store 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::GraphStoreProtocol 0.004 { | ||
| 44 | use Moo; | ||
| 45 | use Attean; | ||
| 46 | use Attean::RDF qw(iri); | ||
| 47 | use Encode qw(encode); | ||
| 48 | use UUID::Tiny ':std'; | ||
| 49 | use Types::Standard qw(ConsumerOf CodeRef HashRef ArrayRef Str Int); | ||
| 50 | use namespace::clean; | ||
| 51 | |||
| 52 | with 'MooX::Log::Any'; | ||
| 53 | |||
| 54 | has 'planner' => ( | ||
| 55 | is => 'ro', | ||
| 56 | isa => ConsumerOf['Attean::API::QueryPlanner'], | ||
| 57 | required => 1, | ||
| 58 | default => sub { | ||
| 59 | Attean::IDPQueryPlanner->new(); | ||
| 60 | } | ||
| 61 | ); | ||
| 62 | has 'model' => (is => 'ro', isa => ConsumerOf['Attean::API::Model'], required => 1); | ||
| 63 | has 'conf' => (is => 'ro', isa => HashRef, required => 1); | ||
| 64 | has 'graph' => (is => 'ro', isa => ConsumerOf['Attean::API::IRI'], required => 1); | ||
| 65 | |||
| 66 | =item C<< run( $request, $response ) >> | ||
| 67 | |||
| 68 | Extract the SPARQL Graph Store Protocol request from C<< $request >>, run the | ||
| 69 | corresponding query/update, and populate C<< $response >> with results or error | ||
| 70 | information. | ||
| 71 | |||
| 72 | =cut | ||
| 73 | |||
| 74 | sub run { | ||
| 75 | my $self = shift; | ||
| 76 | my $req = shift; | ||
| 77 | my $env = $req->env; | ||
| 78 | my $response = shift; | ||
| 79 | my $gsp_path = shift; | ||
| 80 | |||
| 81 | my $config = $self->{conf}; | ||
| 82 | my $model = $self->{model}; | ||
| 83 | my $headers = $req->headers; | ||
| 84 | my $type = $headers->header('Accept') || 'application/sparql-results+xml'; | ||
| 85 | if (my $t = $req->param('media-type')) { | ||
| 86 | $type = $t; | ||
| 87 | $headers->header('Accept' => $type); | ||
| 88 | } | ||
| 89 | |||
| 90 | # my $ae = $req->headers->header('Accept-Encoding') || ''; | ||
| 91 | my ($graph, $new, $default) = $self->get_gsp_graph($req, $gsp_path); | ||
| 92 | unless ($graph) { | ||
| 93 | die AtteanX::Endpoint::ClientError->new( | ||
| 94 | code => 400, | ||
| 95 | message => 'No graph specified', uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_no_graph' | ||
| 96 | ); | ||
| 97 | } | ||
| 98 | my $base = $req->base; | ||
| 99 | my $parser = Attean->get_parser('SPARQL')->new(base => $base); | ||
| 100 | my $algebra; | ||
| 101 | my $content; | ||
| 102 | if ($req->method eq 'GET' or $req->method eq 'HEAD') { | ||
| 103 | my $sparql = 'CONSTRUCT WHERE { ?s ?p ?o }'; | ||
| 104 | ($algebra) = eval { $parser->parse($sparql, base => $base) }; | ||
| 105 | $self->log_gsp_request( $req ); | ||
| 106 | if ($@ or not($algebra)) { | ||
| 107 | my $error = $@ || 'Internal error'; | ||
| 108 | $self->log_error( $req, $error ); | ||
| 109 | my $eclass = ($error =~ /Syntax/) ? 'AtteanX::Endpoint::ClientError' : 'AtteanX::Endpoint::ServerError'; | ||
| 110 | die $eclass->new(message => 'SPARQL GSP parse error', uri => 'http://id.kasei.us/rdf-endpoint/error/parse_error', details => { error => $error }); | ||
| 111 | } | ||
| 112 | } else { | ||
| 113 | unless ($config->{endpoint}{update}) { | ||
| 114 | die AtteanX::Endpoint::ClientError->new(code => 405, message => 'Method not allowed', uri => 'http://id.kasei.us/rdf-endpoint/error/bad_http_method'); | ||
| 115 | } | ||
| 116 | if ($req->method eq 'PUT' or $req->method eq 'POST') { | ||
| 117 | my $ct = $req->headers->header('Content-Type'); | ||
| 118 | |||
| 119 | unless ($ct) { | ||
| 120 | die AtteanX::Endpoint::ClientError->new( | ||
| 121 | code => 400, | ||
| 122 | message => 'No Content-Type specified for PUT request', uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_no_media_type' | ||
| 123 | ); | ||
| 124 | } | ||
| 125 | |||
| 126 | if ($req->method eq 'POST' and $ct =~ m#^multipart/form-data#) { | ||
| 127 | my $uploads = $req->uploads; | ||
| 128 | my @ops; | ||
| 129 | foreach my $file (keys %$uploads) { | ||
| 130 | my $f = $uploads->get($file); | ||
| 131 | my $ct = $f->content_type; | ||
| 132 | my $ok = open(my $fh, '<:raw', $f->path); | ||
| 133 | unless ($ok) { | ||
| 134 | die AtteanX::Endpoint::ServerError->new( | ||
| 135 | code => 500, | ||
| 136 | message => "Failed to open uploaded file in GSP request", uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_upload_error' | ||
| 137 | ); | ||
| 138 | } | ||
| 139 | my $insert = $self->update_for_io($req, $graph, $ct, $fh); | ||
| 140 | push(@ops, $insert); | ||
| 141 | } | ||
| 142 | my $seq = Attean::Algebra::Sequence->new(children => \@ops); | ||
| 143 | $algebra = $seq; | ||
| 144 | } else { | ||
| 145 | my $pclass = Attean->get_parser(media_type => $ct) // Attean->get_parser('turtle'); | ||
| 146 | unless ($pclass) { | ||
| 147 | die AtteanX::Endpoint::ClientError->new( | ||
| 148 | code => 400, | ||
| 149 | message => "No parser available for media type $ct", uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_unrecognized_media_type' | ||
| 150 | ); | ||
| 151 | } | ||
| 152 | |||
| 153 | my $parser = $pclass->new(); | ||
| 154 | my $iter = eval { $parser->parse_iter_from_bytes($req->content) }; | ||
| 155 | if ($@) { | ||
| 156 | die AtteanX::Endpoint::ClientError->new( | ||
| 157 | code => 400, | ||
| 158 | message => "Failed to parse the body in GSP request: " . $req->method, uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_body_syntax_error' | ||
| 159 | ); | ||
| 160 | } | ||
| 161 | |||
| 162 | my @ops; | ||
| 163 | if ($req->method eq 'PUT') { | ||
| 164 | my $drop = Attean::Algebra::Clear->new(drop => 1, silent => 1, target => 'GRAPH', graph => $graph); | ||
| 165 | push(@ops, $drop); | ||
| 166 | } | ||
| 167 | my $insert = Attean::Algebra::Modify->new(insert => [$iter->as_quads($graph)->elements]); | ||
| 168 | push(@ops, $insert); | ||
| 169 | my $seq = Attean::Algebra::Sequence->new(children => \@ops); | ||
| 170 | # warn $seq->as_string; | ||
| 171 | $algebra = $seq; | ||
| 172 | } | ||
| 173 | } elsif ($req->method eq 'DELETE') { | ||
| 174 | $algebra = Attean::Algebra::Clear->new(drop => 1, silent => 1, target => 'GRAPH', graph => $graph); | ||
| 175 | } else { | ||
| 176 | die AtteanX::Endpoint::ClientError->new( | ||
| 177 | code => 400, | ||
| 178 | message => "Unsupported HTTP method: " . $req->method, uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_unrecognized_http_method' | ||
| 179 | ); | ||
| 180 | } | ||
| 181 | } | ||
| 182 | |||
| 183 | if ($self->log->is_trace) { | ||
| 184 | $self->log->trace("Algebra:\n" . $algebra->as_string); | ||
| 185 | } | ||
| 186 | my $default_graphs = [$graph]; | ||
| 187 | my $planner = $self->planner; | ||
| 188 | if ($self->log->is_trace) { | ||
| 189 | $self->log->debug('Planning with default graphs:'); | ||
| 190 | foreach my $g (@$default_graphs) { | ||
| 191 | $self->log->trace($g->as_string); | ||
| 192 | } | ||
| 193 | } | ||
| 194 | |||
| 195 | my $plan = $planner->plan_for_algebra($algebra, $model, $default_graphs); | ||
| 196 | if ($self->log->is_debug) { | ||
| 197 | $self->log->debug("Plan:\n" . $plan->as_string); | ||
| 198 | } | ||
| 199 | my $empty_graph = do { | ||
| 200 | my $iter = $model->get_quads(undef, undef, undef, $graph); | ||
| 201 | my $st = $iter->next; | ||
| 202 | ref($st) ? 0 : 1; | ||
| 203 | }; | ||
| 204 | my $code; | ||
| 205 | if ($new) { | ||
| 206 | $code = 201; | ||
| 207 | } elsif ($req->method eq 'PUT') { | ||
| 208 | # Return 201 Created on empty graphs (these are considered newly created) | ||
| 209 | # unless it's the default graph (which always exists, so can't be "created"). | ||
| 210 | $code = ($empty_graph and not($default)) ? 201 : 204; | ||
| 211 | } elsif ($req->method eq 'POST') { | ||
| 212 | $code = 204; | ||
| 213 | } elsif ($req->method eq 'DELETE') { | ||
| 214 | $code = $empty_graph ? 404 : 204; | ||
| 215 | } elsif ($req->method =~ m/^(GET|HEAD)$/) { | ||
| 216 | if ($self->graph->equals($graph)) { | ||
| 217 | # never return a 404 for the default graph | ||
| 218 | $code = 200; | ||
| 219 | } else { | ||
| 220 | $code = $empty_graph ? 404 : 200; | ||
| 221 | } | ||
| 222 | } else { | ||
| 223 | die $req->method; | ||
| 224 | } | ||
| 225 | eval { | ||
| 226 | my $iter = $plan->evaluate($model); | ||
| 227 | if ($req->method eq 'GET' or $req->method eq 'HEAD') { # RDF content | ||
| 228 | my $sclass = Attean->negotiate_serializer(request_headers => $headers, role => 'Attean::API::TripleSerializer') // Attean->get_serializer('ntriples'); | ||
| 229 | my @args; | ||
| 230 | $self->log->debug("Serializer class: $sclass"); | ||
| 231 | my $s = $sclass->new(@args); | ||
| 232 | my $stype = $s->canonical_media_type; | ||
| 233 | if ($req->method eq 'GET') { | ||
| 234 | $content = $s->serialize_iter_to_bytes($iter); | ||
| 235 | } | ||
| 236 | $response->headers->content_type($stype); | ||
| 237 | } else { | ||
| 238 | $response->headers->content_type('text/plain'); | ||
| 239 | $content = "OK\n"; | ||
| 240 | } | ||
| 241 | }; | ||
| 242 | |||
| 243 | if ($new) { | ||
| 244 | $response->header('Location' => $graph->value); | ||
| 245 | } | ||
| 246 | |||
| 247 | if ($@) { | ||
| 248 | my $error = $@; | ||
| 249 | $self->log->fatal($error); | ||
| 250 | die AtteanX::Endpoint::ServerError->new(code => 500, message => 'SPARQL GSP execution error', uri => 'http://id.kasei.us/rdf-endpoint/error/execution_error', details => { error => $@ }); | ||
| 251 | } | ||
| 252 | |||
| 253 | $response->status($code); | ||
| 254 | $response->body($content); | ||
| 255 | return $content; | ||
| 256 | } | ||
| 257 | |||
| 258 | =item C<< update_for_io( $request, $graph, $content_type, $io ) >> | ||
| 259 | |||
| 260 | Parses RDF content of type C<< $content_type >> from C<< $io >>, and inserts | ||
| 261 | it into the specified C<< $graph >>, clearing that graph first if | ||
| 262 | C<< $request->method >> is 'PUT'. | ||
| 263 | |||
| 264 | C<< $io >> is expected to be a byte-oriented filehandle (one opened with the | ||
| 265 | C<< :raw >> layer, for example). A handle carrying a character encoding layer | ||
| 266 | is also accepted, as its contents are re-encoded to UTF-8 before parsing. | ||
| 267 | |||
| 268 | =cut | ||
| 269 | |||
| 270 | sub update_for_io { | ||
| 271 | my $self = shift; | ||
| 272 | my $req = shift; | ||
| 273 | my $graph = shift; | ||
| 274 | my $ct = shift; | ||
| 275 | my $io = shift; | ||
| 276 | my $bytes = do { local $/; <$io> } // ''; | ||
| 277 | $bytes = encode('UTF-8', $bytes) if (utf8::is_utf8($bytes)); | ||
| 278 | my $pclass = Attean->get_parser(media_type => $ct) // Attean->get_parser('turtle'); | ||
| 279 | unless ($pclass) { | ||
| 280 | die AtteanX::Endpoint::ClientError->new( | ||
| 281 | code => 400, | ||
| 282 | message => "No parser available for media type $ct", uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_unrecognized_media_type' | ||
| 283 | ); | ||
| 284 | } | ||
| 285 | |||
| 286 | my $parser = $pclass->new(); | ||
| 287 | my $iter = eval { $parser->parse_iter_from_bytes($bytes) }; | ||
| 288 | if ($@) { | ||
| 289 | die AtteanX::Endpoint::ClientError->new( | ||
| 290 | code => 400, | ||
| 291 | message => "Failed to parse the body in GSP request: " . $req->method, uri => 'http://id.kasei.us/rdf-endpoint/error/gsp_body_syntax_error' | ||
| 292 | ); | ||
| 293 | } | ||
| 294 | |||
| 295 | my @ops; | ||
| 296 | if ($req->method eq 'PUT') { | ||
| 297 | my $drop = Attean::Algebra::Clear->new(drop => 1, silent => 1, target => 'GRAPH', graph => $graph); | ||
| 298 | push(@ops, $drop); | ||
| 299 | } | ||
| 300 | my $insert = Attean::Algebra::Modify->new(insert => [$iter->as_quads($graph)->elements]); | ||
| 301 | return $insert; | ||
| 302 | } | ||
| 303 | |||
| 304 | =item C<< get_gsp_graph( $request ) >> | ||
| 305 | |||
| 306 | Return a list C<< ( $g, $new ) >> of the graph identified by the GSP request | ||
| 307 | (either directly- or indirectly-identified, or C<< $self->graph >> for the | ||
| 308 | default graph), and a boolean flag indicating if the graph should be newly | ||
| 309 | created (in the case of a POST to the GSP endpoint without identifying a | ||
| 310 | graph). | ||
| 311 | |||
| 312 | =cut | ||
| 313 | |||
| 314 | sub get_gsp_graph { | ||
| 315 | my $self = shift; | ||
| 316 | my $req = shift; | ||
| 317 | my $env = $req->env; | ||
| 318 | my $host = $env->{'HTTP_HOST'}; | ||
| 319 | my $scheme = $env->{'psgi.url_scheme'}; | ||
| 320 | my $gsp_path = shift; | ||
| 321 | my $direct = ((substr($req->path, 0, length($gsp_path)) eq $gsp_path) and not($req->param('graph')) and length($req->path) > length($gsp_path)); | ||
| 322 | my $query = $req->parameters; | ||
| 323 | my $g; | ||
| 324 | my $new = 0; | ||
| 325 | my $is_default = 0; | ||
| 326 | if ($req->query_string eq 'default') { | ||
| 327 | my $default = $self->graph; | ||
| 328 | $g = $default; | ||
| 329 | $is_default = 1; | ||
| 330 | } elsif (my $graph = $req->param('graph')) { | ||
| 331 | $g = iri($graph); | ||
| 332 | } elsif ($direct) { | ||
| 333 | my $uri = "${scheme}://$host" . $req->path; | ||
| 334 | $g = iri($uri); | ||
| 335 | } else { | ||
| 336 | $g = Attean::IRI->new('urn:uuid:' . uc(uuid_to_string(create_uuid()))); | ||
| 337 | $new = 1; | ||
| 338 | } | ||
| 339 | return ($g, $new, $is_default); | ||
| 340 | } | ||
| 341 | |||
| 342 | =item C<< log_gsp_request( $request ) >> | ||
| 343 | |||
| 344 | Log the request. | ||
| 345 | |||
| 346 | =cut | ||
| 347 | |||
| 348 | sub log_gsp_request { | ||
| 349 | my $self = shift; | ||
| 350 | my $req = shift; | ||
| 351 | $self->log->info("GSP query:\n" . $req->method); | ||
| 352 | $self->_log( $req, { level => 'info' } ); | ||
| 353 | } | ||
| 354 | |||
| 355 | =item C<< log_error ( $message ) >> | ||
| 356 | |||
| 357 | =cut | ||
| 358 | |||
| 359 | sub log_error { | ||
| 360 | my $self = shift; | ||
| 361 | my $req = shift; | ||
| 362 | my $message = shift; | ||
| 363 | $self->log->error($message); | ||
| 364 | $self->_log( $req, { level => 'error', message => $message } ); | ||
| 365 | } | ||
| 366 | |||
| 367 | sub _log { | ||
| 368 | my $self = shift; | ||
| 369 | my $req = shift; | ||
| 370 | my $data = shift; | ||
| 371 | my $logger = $req->logger || sub {}; | ||
| 372 | |||
| 373 | $logger->($data); | ||
| 374 | } | ||
| 375 | } | ||
| 376 | |||
| 377 | 1; | ||
| 378 | |||
| 379 | __END__ |