AtteanX/Endpoint.pm

filter: Statementstmt 95.7% 45 / 47 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 16 / 16 Podpod n/a totaltotal 96.8% 61 / 63 CC 1 SCAR 0.2
CC
1
Cov
96%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« AtteanX/Endpoint/Error.pm ↑ Summary
1 # TODO: If the model supports caching roles, add headers and check for http 304
2 # TODO: Implement and support Accept-Language models (port from RDF::Trine::Store::LanguagePreference)
3 # TODO: Add next/prev link headers if query is paged
4 # TODO: Add configuration and link headers to indicate LDF/SPARQL mirrors
5  
6 5 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 AtteanX::Endpoint - SPARQL 1.1 Protocol Endpoint
12  
13 =head1 VERSION
14  
15 This document describes AtteanX::Endpoint version 0.003_04
16  
17 =head1 SYNOPSIS
18  
19 plackup -p 9091 scripts/endpoint.psgi
20  
21 =head1 DESCRIPTION
22  
23 The AtteanX::Endpoint class implements a PSGI SPARQL Protocol endpoint.
24  
25 =head1 ATTRIBUTES
26  
27 =over 4
28  
29 =item C<< planner >>
30  
31 =item C<< model >>
32  
33 =item C<< conf >>
34  
35 A hash reference containing configuration data for the endpoint. For example:
36  
37 {
38 endpoint => {
39 service_description => {
40 named_graphs => 1,
41 default => 1,
42 },
43 load_data => 0,
44 update => 0,
45 }
46 }
47  
48 =item C<< graph >>
49  
50 The L<Attean::API::IRI> of the graph in the model that represents the default graph.
51  
52 =back
53  
54 =head1 METHODS
55  
56 =over 4
57  
58 =cut
59  
60 package AtteanX::Endpoint {
61 our $VERSION = "0.003_04";
62 5 ▶ use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
63 5 ▶ use Attean;
Subroutine BEGIN: called CC=1 SCAR=0.0
64 5 ▶ use Attean::RDF qw(iri);
Subroutine BEGIN: called CC=1 SCAR=0.0
65 5 ▶ use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
66 5 ▶ use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
67 5 ▶ use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
68 5 ▶ use Plack::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
69 5 ▶ use Plack::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 5 ▶ use Scalar::Util qw(blessed refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
71 5 ▶ use List::MoreUtils qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
72 5 ▶ use File::ShareDir qw(dist_dir);
Subroutine BEGIN: called CC=1 SCAR=0.0
73 5 ▶ use HTTP::Negotiate qw(choose);
Subroutine BEGIN: called CC=1 SCAR=0.0
74 5 ▶ use IO::Compress::Gzip qw(gzip);
Subroutine BEGIN: called CC=1 SCAR=0.0
75 0 ▶ use HTML::HTML5::Writer qw(DOCTYPE_XHTML_RDFA);
Subroutine BEGIN: called CC=1 SCAR=2.6
76 use Carp qw(croak);
77 use Types::Standard qw(ConsumerOf CodeRef HashRef ArrayRef Str Int);
78 # use IO::Handle;
79 # use Digest::MD5 qw(md5_base64);
80 use XML::LibXML 1.70;
81 use AtteanX::Endpoint::GraphStoreProtocol;
82 use AtteanX::Endpoint::Protocol;
83 # use RDF::RDFa::Generator 0.102;
84 # use Hash::Merge::Simple qw/ merge /;
85 # use Fcntl qw(:flock SEEK_END);
86 use AtteanX::Endpoint::Error;
87 use namespace::clean;
88  
89 with 'MooX::Log::Any';
90  
91 has 'planner' => (
92 is => 'ro',
93 isa => ConsumerOf['Attean::API::QueryPlanner'],
94 required => 1,
95 default => sub {
96 Attean::IDPQueryPlanner->new();
97 }
98 );
99 has 'model' => (is => 'ro', isa => ConsumerOf['Attean::API::Model'], required => 1);
100 has 'conf' => (is => 'ro', isa => HashRef, required => 1);
101 has 'graph' => (is => 'ro', isa => ConsumerOf['Attean::API::IRI'], required => 1);
102
103 sub BUILDARGS {
104 my $class = shift;
105 my @params = @_;
106 my %args;
107 if (blessed($params[0]) and $params[0]->does('Attean::API::Model')) {
108 # ->new( $model, \%conf )
109 $args{ model } = shift @params;
110 $args{ conf } = shift @params;
111 $args{ graph } = Attean::IRI->new('http://example.org/graph');
112 } elsif (any { blessed($_) && $_->does('Attean::API::Model') } @params) {
113 # Assume the buildargs can be taken directly
114 return $class->SUPER::BUILDARGS(@params);
115 } else {
116 # ->new( \%conf )
117 my $conf = shift @params;
118 my $store_conf = $conf->{store};
119 my $store;
120 my $file;
121 if (ref($store_conf) eq 'HASH') {
122 my $name = delete $store_conf->{name};
123 $file = delete $store_conf->{load_file};
124 my $sclass = Attean->get_store($name);
125 $store = $sclass->new( %$store_conf );
126 } else {
127 (my $name_, $file) = split(';', $store_conf, 2);
128 my ($name, @args) = split('=', $name_);
129 my $sclass = Attean->get_store($name);
130 $store = $sclass->new(@args);
131 }
132 my $model = Attean::MutableQuadModel->new( store => $store );
133
134 my $guri = 'http://example.org/default-graph';
135 if (my $dataset = $conf->{dataset}) {
136 $guri = $dataset->{default};
137 }
138 my $graph = Attean::IRI->new($guri);
139 if (defined($file) and length($file)) {
140 $graph = Attean::IRI->new('file://' . File::Spec->rel2abs($file));
141 open(my $fh, '<:encoding(UTF-8)', $file) or die $!;
142 #$self->log->debug("Parsing data from $file...");
143 my $pclass = Attean->get_parser( filename => $file ) // 'AtteanX::Parser::Turtle';
144 my $parser = $pclass->new(base => $graph);
145 my $iter = $parser->parse_iter_from_io($fh);
146 my $quads = $iter->as_quads($graph);
147 $model->add_iter($quads);
148 }
149
150 $args{ model } = $model;
151 $args{ conf } = $conf;
152 $args{ graph } = $graph;
153 }
154
155 return $class->SUPER::BUILDARGS(%args);
156 }
157  
158 =item C<< run ( $request ) >>
159  
160 Run the SPARQL request contained in the given C<< $request >> object and return
161 a response object.
162  
163 =cut
164
165 sub run {
166 my $self = shift;
167 my $req = shift;
168
169 try {
170 return $self->_run($req, @_);
171 }
172 catch {
173 my $e = $_;
174 my $resp = Plack::Response->new;
175 my $error = {};
176 my ($code, $status);
177 if (ref($e)) {
178 $error->{describedby} = $e->uri;
179 $code = $e->code;
180 $status = $e->message;
181 if (my $d = $e->details) {
182 $error->{details} = $d;
183 }
184 } else {
185 $code = 500;
186 $status = 'Internal Server Error';
187 $error->{message} = $e;
188 warn $e;
189 }
190
191 $error->{title} = $status;
192
193 my @variants = (
194 ['text/plain', 0.98, 'text/plain'],
195 ['application/json-problem', 0.99, 'application/json-problem'],
196 );
197 my $headers = $req->headers;
198 my $stype = choose( \@variants, $headers ) || 'text/plain';
199 if ($stype eq 'application/json-problem') {
200 $resp->headers->content_type( 'application/json-problem' );
201 $resp->status($code);
202 my $content = encode_json($error);
203 $resp->body($content);
204 } else {
205 $resp->headers->content_type( 'text/plain' );
206 $resp->status($code);
207 my @messages = grep { defined($_) } @{ $error }{ qw(title detail message) };
208 my $content = join("\n\n", $status, @messages);
209 $resp->body($content);
210 }
211 return $resp;
212 }
213 }
214
215 sub _run {
216 my $self = shift;
217 my $req = shift;
218
219 my $config = $self->{conf};
220 my $endpoint_path = $config->{endpoint}{endpoint_path} || '/sparql';
221 my $gsp_path = $config->{endpoint}{gsp_path} || '/gsp';
222
223 my $response = Plack::Response->new;
224  
225 our $VERSION;
226 my $server = "AtteanX::Endpoint/$VERSION";
227 $server .= " " . $response->headers->header('Server') if defined($response->headers->header('Server'));
228 $response->headers->header('Server' => $server);
229  
230 if ($req->path eq $endpoint_path or substr($req->path, 0, length($gsp_path)) eq $gsp_path) {
231 # no-op
232 } else {
233 my $content;
234 my $path = $req->path_info;
235 $path =~ s#^/##;
236 my $dir = $ENV{ATTEAN_ENDPOINT_SHAREDIR} || File::Spec->catdir((eval { dist_dir('AtteanX-Endpoint') } || 'share'), 'endpoint');
237 my $abs = File::Spec->rel2abs($dir);
238 my $file = File::Spec->catfile($abs, 'www', $path);
239 if (-r $file) {
240 open( my $fh, '<', $file ) or croak $!;
241 $response->status(200);
242 $content = $fh;
243 } else {
244 my $path = $req->path;
245 $response->status(404);
246 $content = <<"END";
247 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>404 Not Found</title>\n</head><body>\n
248 <h1>Not Found</h1>\n<p>The requested URL $path was not found on this server.</p>\n</body></html>
249 END
250 }
251 $response->body($content);
252 return $response;
253 }
254
255 my $ae = $req->headers->header('Accept-Encoding') || '';
256 if ($req->path eq $endpoint_path) {
257 my $handler = AtteanX::Endpoint::Protocol->new( model => $self->model, conf => $self->conf, graph => $self->graph );
258 my $content = $handler->run($req, $response, $gsp_path);
259 $self->wrap_response_with_encoding($req, $response, $ae, $content);
260 } else {
261 my $handler = AtteanX::Endpoint::GraphStoreProtocol->new( model => $self->model, conf => $self->conf, graph => $self->graph );
262 my $content = $handler->run($req, $response, $gsp_path);
263 $self->wrap_response_with_encoding($req, $response, $ae, $content);
264 }
265 return $response;
266 }
267  
268 =item C<< wrap_response_with_encoding ( $request, $response, $ae, $body ) >>
269  
270 If $ae includes 'gzip' as a requested Accept-Encoding value, and the body of
271 $response (or $body) is non-empty, gzip-compress the content body, setting
272 the response body to the new compressed data, and set Content-Encoding and
273 Content-Length headers appropriately on $response. Otherwise, set the
274 the response body to the uncompressed content, and set the Content-Length
275 header on $response.
276  
277 =cut
278
279 sub wrap_response_with_encoding {
280 my $self = shift;
281 my $req = shift;
282 my $response = shift;
283 my $ae = shift;
284 my $content = $response->body || shift;
285 return unless (defined($content));
286
287 my $length = 0;
288 my %ae = map { $_ => 1 } split(/\s*,\s*/, $ae);
289 if ($ae{'gzip'}) {
290 my $orig = length($content);
291 my ($rh, $wh);
292 pipe($rh, $wh);
293 if (ref($content)) {
294 gzip $content => $wh;
295 } else {
296 gzip \$content => $wh;
297 }
298 close($wh);
299 my $body = do { local($/) = undef; <$rh> };
300 $self->log->info("Compressed $orig bytes to " . length($body) . " bytes");
301 $length = bytes::length($body);
302 $response->headers->header('Content-Encoding' => 'gzip');
303 $response->headers->header('Content-Length' => $length);
304 $response->body( $body ) unless ($req->method eq 'HEAD');
305 } else {
306 local($/) = undef;
307 my $body = ref($content) ? <$content> : $content;
308 $length = bytes::length($body);
309 $response->headers->header('Content-Length' => $length);
310 $response->body( $body ) unless ($req->method eq 'HEAD');
311 }
312 }
313 }
314  
315 package Plack::App::AtteanX::Endpoint 0.004 {
316 use parent qw(Plack::Component);
317 use Plack::Request;
318
319 sub configure {
320 my $self = shift;
321 $self->{config} = shift;
322 return $self;
323 }
324
325 sub prepare_app {
326 my $self = shift;
327 my $config = $self->{config};
328 $self->{endpoint} = eval { AtteanX::Endpoint->new( $config ) };
329 if ($@) {
330 warn $@;
331 }
332 }
333  
334 sub call {
335 my($self, $env) = @_;
336 my $req = Plack::Request->new($env);
337 unless ($req->method =~ /^(GET|HEAD|POST|PUT|DELETE)$/) {
338 return [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ];
339 }
340  
341 my $ep = $self->{endpoint};
342 my $resp = $ep->run( $req );
343 return $resp->finalize;
344 }
345 }
346  
347  
348 1;
349  
350 __END__
« AtteanX/Endpoint/Error.pm ↑ Summary