API.pm

filter: Statementstmt 37.2% 38 / 102 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 47.3% 9 / 19 Podpod 100% 3 / 3 totaltotal 30.1% 50 / 166 SCAR 45.9
CC
15
Cov
28%
stream_rs
56.0
__ANON__
20.0
__ANON__
12.0
CRAP 98.5
« API/Controller/Summary.pm ↑ Summary API/Controller/Release.pm »
1 package CPAN::Testers::API;
2 6 our $VERSION = '0.025';
3 # ABSTRACT: REST API for CPAN Testers data
4  
5 #pod =head1 SYNOPSIS
6 #pod
7 #pod $ cpantesters-api daemon
8 #pod Listening on http://*:5000
9 #pod
10 #pod =head1 DESCRIPTION
11 #pod
12 #pod This is a REST API on to the data contained in the CPAN Testers
13 #pod database. This data includes test reports, CPAN distributions, and
14 #pod various aggregate test reporting.
15 #pod
16 #pod =head1 CONFIG
17 #pod
18 #pod This application can be configured by setting the C<MOJO_CONFIG>
19 #pod environment variable to the path to a configuration file. The
20 #pod configuration file is a Perl script containing a single hash reference,
21 #pod like:
22 #pod
23 #pod # api.conf
24 #pod {
25 #pod broker => 'ws://127.0.0.1:5000',
26 #pod schema => 'dbi:SQLite:api.db',
27 #pod }
28 #pod
29 #pod The possible configuration keys are below:
30 #pod
31 #pod =over
32 #pod
33 #pod =item broker
34 #pod
35 #pod The URL to a L<Mercury> message broker, starting with C<ws://>. This
36 #pod broker is used to forward messages to every connected user.
37 #pod
38 #pod =item schema
39 #pod
40 #pod The DBI connect string to give to L<CPAN::Testers::Schema>. If not specified,
41 #pod will use L<CPAN::Testers::Schema/connect_from_config>.
42 #pod
43 #pod =back
44 #pod
45 #pod =head1 LOCAL TESTING
46 #pod
47 #pod To run an instance of this for local testing, create an C<api.conf> file
48 #pod to configure a SQLite schema:
49 #pod
50 #pod # api.conf
51 #pod {
52 #pod schema => 'dbi:SQLite:api.sqlite3'
53 #pod }
54 #pod
55 #pod For the L<CPAN::Testers::Schema> to work with SQLite, you will need to
56 #pod install an additional CPAN module, L<DateTime::Format::SQLite>.
57 #pod
58 #pod Once this is configured, you can deploy a new, blank database using
59 #pod C<< cpantesters-api eval 'app->schema->deploy' >>.
60 #pod
61 #pod Now you can run the API using C<< cpantesters-api daemon >>.
62 #pod
63 #pod =head1 SEE ALSO
64 #pod
65 #pod L<Mojolicious>, L<Mojolicious::Plugin::OpenAPI>,
66 #pod L<CPAN::Testers::Schema>,
67 #pod L<http://github.com/cpan-testers/cpantesters-project>,
68 #pod L<http://www.cpantesters.org>
69 #pod
70 #pod =cut
71  
72 6 ▶use Mojo::Base 'Mojolicious';
Subroutine BEGIN: called CC=1 SCAR=0.0
73 6 ▶use CPAN::Testers::API::Base;
Subroutine BEGIN: called CC=1 SCAR=0.0
74 6 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
75 6 ▶use File::Share qw( dist_dir dist_file );
Subroutine BEGIN: called CC=1 SCAR=0.0
76 6 ▶use Log::Any::Adapter;
Subroutine BEGIN: called CC=1 SCAR=0.0
77 6 ▶use Alien::SwaggerUI;
Subroutine BEGIN: called CC=1 SCAR=0.0
78 6 ▶use File::Spec::Functions qw( catdir catfile );
Subroutine BEGIN: called CC=1 SCAR=0.0
79 6 ▶use JSON::MaybeXS qw( encode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
80  
81 #pod =method schema
82 #pod
83 #pod my $schema = $c->schema;
84 #pod
85 #pod Get the schema, a L<CPAN::Testers::Schema> object. By default, the
86 #pod schema is connected from the local user's config. See
87 #pod L<CPAN::Testers::Schema/connect_from_config> for details.
88 #pod
89 #pod =cut
90  
91 has schema => sub {
92 0 ▶ my ( $app ) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
93 0 require CPAN::Testers::Schema;
94 0 ▶ if ( $app->config->{schema} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($app->config->{"schema"}) 0 0 0
95 0 return CPAN::Testers::Schema->connect( $app->config->{schema} );
96 }
97 0 return CPAN::Testers::Schema->connect_from_config;
98 6 };
99  
100 #pod =method startup
101 #pod
102 #pod # Called automatically by Mojolicious
103 #pod
104 #pod This method starts up the application, loads any plugins, sets up routes,
105 #pod and registers helpers.
106 #pod
107 #pod =cut
108  
109 ▶sub startup ( $app ) {
Subroutine startup: called CC=1 SCAR=4.1
Pod documented
110 5 $app->log( Mojo::Log->new ); # Log only to STDERR
111 5 unshift @{ $app->renderer->paths },
112 catdir( dist_dir( 'CPAN-Testers-API' ), 'templates' );
113 5 unshift @{ $app->static->paths },
114 catdir( dist_dir( 'CPAN-Testers-API' ), 'public' );
115  
116 5 $app->moniker( 'api' );
117 5 $app->plugin( Config => {
118 default => { }, # Allow living without config file
119 } );
120  
121 # Allow CORS for everyone
122 $app->hook( after_build_tx => sub {
123 0 ▶ my ( $tx, $app ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
124 0 $tx->res->headers->header( 'Access-Control-Allow-Origin' => '*' );
125 0 $tx->res->headers->header( 'Access-Control-Allow-Methods' => 'GET, POST, PUT, PATCH, DELETE, OPTIONS' );
126 0 $tx->res->headers->header( 'Access-Control-Max-Age' => 3600 );
127 0 $tx->res->headers->header( 'Access-Control-Allow-Headers' => 'Content-Type, X-Requested-With' );
128 5 } );
129  
130 5 my $r = $app->routes;
131 5 $r->get( '/' => 'index' );
132 $r->get( '/docs/*path' => { path => 'index.html' } )->to(
133 cb => sub {
134 0 ▶ my ( $c ) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
135 # Redirect so that trailing / helps browser build URLs and
136 # we have our spec loaded. Can't make its own route because
137 # the trailing `/` is optional in the Mojolicious route
138 # since we declared a default `path`. Must pass in
139 # a Mojo::URL object to redirect_to() so that the trailing
140 # slash is maintained.
141 0 ▶ if ( !$c->req->url->path->trailing_slash && $c->req->url->path eq '/docs' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $c->req->url->path->trailing_slash and $c->req->url->path eq "/docs") 0 0 0
Condition0%0/3
not $c->req->url->path->trailing_slash and $c->req->url->path eq "/docs"
!ll&&!rl&&r
000
MC/DC0%0/2
not $c->req->url->path->trailing_slash and $c->req->url->path eq "/docs"
not $c->req->url->path->trailing_slash $c->req->url->path eq "/docs"
Truth table0%0/3
not(A) and B
A= not $c->req->url->path->trailing_slashB= $c->req->url->path eq "/docs"
ABresult
0X0
100
111
142 0 $c->req->url->path->trailing_slash(1);
143 0 $c->req->url->query( url => '/v3' );
144 0 return $c->redirect_to( $c->req->url );
145 }
146 0 my $path = catfile( Alien::SwaggerUI->root_dir, $c->stash( 'path' ) );
147 0 my $file = Mojo::Asset::File->new( path => $path );
148 0 $c->reply->asset( $file );
149 },
150 5 );
151  
152 0 $r->websocket( '/v1/upload' )->to( 'Upload#feed' );
153 0 $r->websocket( '/v1/upload/dist/:dist' )->to( 'Upload#feed' );
154 0 $r->websocket( '/v1/upload/author/:author' )->to( 'Upload#feed' );
155  
156 0 $r->websocket( '/v3/upload' )->to( 'Upload#feed' );
157 0 $r->websocket( '/v3/upload/dist/:dist' )->to( 'Upload#feed' );
158 0 $r->websocket( '/v3/upload/author/:author' )->to( 'Upload#feed' );
159  
160 ▶ my $render_fast_json = sub( $c, $data ) {
Subroutine __ANON__: not called CC=4 SCAR=30.0
161 0 ▶ if ( blessed $data || ( ref $data eq 'HASH' && $data->{errors} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($data) or ref $data eq "HASH" and $data->{"errors"}) 0 0 0
Condition0%0/6
builtin::blessed($data) or ref $data eq "HASH" and $data->{"errors"}
l!l&&r!l&&!r
000
ref $data eq "HASH" and $data->{"errors"}
!ll&&!rl&&r
000
MC/DC0%0/3
builtin::blessed($data) or ref $data eq "HASH" and $data->{"errors"}
builtin::blessed($data) ref $data eq "HASH" $data->{"errors"}
Truth table0%0/4
A or B and C
A= builtin::blessed($data)B= ref $data eq "HASH"C= $data->{"errors"}
ABCresult
1XX1
0111
00X0
0100
162 0 return Mojo::JSON::encode_json( $data );
163 }
164 0 return encode_json( $data );
165 0 };
166  
167 0 $app->plugin( OpenAPI => {
168 url => dist_file( 'CPAN-Testers-API' => 'v1.json' ),
169 allow_invalid_ref => 1,
170 renderer => $render_fast_json,
171 } );
172 0 $app->plugin( OpenAPI => {
173 url => dist_file( 'CPAN-Testers-API' => 'v3.json' ),
174 allow_invalid_ref => 1,
175 renderer => $render_fast_json,
176 } );
177 0 ▶ $app->helper( schema => sub { shift->app->schema } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
178 0 $app->helper( render_error => \&render_error );
179 0 $app->helper( stream_rs => \&stream_rs );
180  
181 0 Log::Any::Adapter->set( 'MojoLog', logger => $app->log );
182 }
183  
184 #pod =method render_error
185 #pod
186 #pod return $c->render_error( 400 => 'Bad Request' );
187 #pod return $c->render_error( 400, {
188 #pod path => '/since',
189 #pod message => 'Invalid date/time',
190 #pod } );
191 #pod
192 #pod Render an error in JSON like other OpenAPI errors. The first argument
193 #pod is the HTTP status code. The remaining arguments are a list of errors
194 #pod to report. Plain strings are turned into one-element hashrefs with a
195 #pod C<message> key. Hashrefs are used as-is.
196 #pod
197 #pod The resulting JSON looks like so:
198 #pod
199 #pod {
200 #pod "errors": [
201 #pod {
202 #pod "path": "/",
203 #pod "message": "Bad Request"
204 #pod }
205 #pod ]
206 #pod }
207 #pod
208 #pod {
209 #pod "errors": [
210 #pod {
211 #pod "path": "/since",
212 #pod "message": "Invalid date/time"
213 #pod }
214 #pod ]
215 #pod }
216 #pod
217 #pod =cut
218  
219 ▶sub render_error( $c, $status, @errors ) {
Subroutine render_error: not called CC=2 SCAR=17.9
Pod documented
220 return $c->render(
221 status => $status,
222 openapi => {
223 errors => [
224 0 ▶ map { !ref $_ ? { message => $_, path => '/' } : $_ } @errors,
Branch: 1 branch
BranchTrueFalseTotal
!ref($_) ? : 0 0 0
225 ],
226 },
227 );
228 }
229  
230 #pod =method stream_rs
231 #pod
232 #pod $c->stream_rs( $rs, $processor );
233 #pod
234 #pod Stream a L<DBIx::Class::ResultSet> object to the browser. This prevents
235 #pod problems with proxy servers and CDNs timing out waiting for data. This
236 #pod uses L<Mojolicious::Controller/write_chunk> to transfer a chunked
237 #pod response. If there are no results in the ResultSet object, this method
238 #pod returns a 404 error.
239 #pod
240 #pod C<$processor> is an optional subref that allows for processing each row
241 #pod before it is written. Use this to translate column names or values into
242 #pod the format the API expects.
243 #pod
244 #pod For this to work usefully behind Fastly, we also need to enable streaming
245 #pod miss so that Fastly streams the data to the end-user as it gets it:
246 #pod L<https://docs.fastly.com/guides/performance-tuning/improving-caching-performance-with-large-files#streaming-miss>.
247 #pod
248 #pod =cut
249  
250 sub stream_rs {
251 0 ▶ my ( $c, $rs, $process ) = @_;
Subroutine stream_rs: not called CC=7 SCAR=40.3
Pod documented
252 0 ▶ $process //= sub { shift };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$process //= sub {
l!l&&r!l&&!r
000
MC/DC0%0/2
$process //= sub { shift(); }
$process sub { shift(); }
Truth table0%0/3
A //= B
A= $processB= sub { shift(); }
ABresult
1X1
011
000
253 0 my $wrote_open = 0;
254 0 my $written = 0;
255 0 my @to_write;
256  
257 my $flush_write = sub {
258 0 ▶ my $leading_comma = ',';
Subroutine __ANON__: not called CC=2 SCAR=17.9
259 0 ▶ if ( !$wrote_open ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($wrote_open) 0 0 0
260 0 $c->write_chunk( '[' );
261 0 $wrote_open = 1;
262 0 $leading_comma = '';
263 }
264 0 my $to_write = join ",", map { encode_json( $process->( $_ ) ) } @to_write;
265 0 $c->write_chunk( $leading_comma . $to_write );
266 0 $written += @to_write;
267 0 @to_write = ();
268 0 };
269  
270 0 ▶ while ( my $row = $rs->next ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $rs->next) 0 0 0
271 0 push @to_write, $row;
272 0 ▶ if ( @to_write >= 5 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@to_write >= 5) 0 0 0
273 0 $flush_write->();
274 }
275 }
276 0 ▶ if ( !$written && !@to_write ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($written or @to_write) 0 0 0
Condition0%0/3
$written or @to_write
l!l&&r!l&&!r
000
MC/DC0%0/2
$written or @to_write
$written @to_write
Truth table0%0/3
A or B
A= $writtenB= @to_write
ABresult
1X1
011
000
277 0 return $c->render_error( 404, 'No results found' );
278 }
279 0 ▶ if ( @to_write ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@to_write) 0 0 0
280 0 $flush_write->();
281 }
282 0 ▶ return $c->write_chunk( ']', sub { shift->finish } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
283 }
284  
285 6 1;
286  
287 __END__
288  
289 =pod
290  
291 =head1 NAME
292  
293 CPAN::Testers::API - REST API for CPAN Testers data
294  
295 =head1 VERSION
296  
297 version 0.025
298  
299 =head1 SYNOPSIS
300  
301 $ cpantesters-api daemon
302 Listening on http://*:5000
303  
304 =head1 DESCRIPTION
305  
306 This is a REST API on to the data contained in the CPAN Testers
307 database. This data includes test reports, CPAN distributions, and
308 various aggregate test reporting.
309  
310 =head1 METHODS
311  
312 =head2 schema
313  
314 my $schema = $c->schema;
315  
316 Get the schema, a L<CPAN::Testers::Schema> object. By default, the
317 schema is connected from the local user's config. See
318 L<CPAN::Testers::Schema/connect_from_config> for details.
319  
320 =head2 startup
321  
322 # Called automatically by Mojolicious
323  
324 This method starts up the application, loads any plugins, sets up routes,
325 and registers helpers.
326  
327 =head2 render_error
328  
329 return $c->render_error( 400 => 'Bad Request' );
330 return $c->render_error( 400, {
331 path => '/since',
332 message => 'Invalid date/time',
333 } );
334  
335 Render an error in JSON like other OpenAPI errors. The first argument
336 is the HTTP status code. The remaining arguments are a list of errors
337 to report. Plain strings are turned into one-element hashrefs with a
338 C<message> key. Hashrefs are used as-is.
339  
340 The resulting JSON looks like so:
341  
342 {
343 "errors": [
344 {
345 "path": "/",
346 "message": "Bad Request"
347 }
348 ]
349 }
350  
351 {
352 "errors": [
353 {
354 "path": "/since",
355 "message": "Invalid date/time"
356 }
357 ]
358 }
359  
360 =head2 stream_rs
361  
362 $c->stream_rs( $rs, $processor );
363  
364 Stream a L<DBIx::Class::ResultSet> object to the browser. This prevents
365 problems with proxy servers and CDNs timing out waiting for data. This
366 uses L<Mojolicious::Controller/write_chunk> to transfer a chunked
367 response. If there are no results in the ResultSet object, this method
368 returns a 404 error.
369  
370 C<$processor> is an optional subref that allows for processing each row
371 before it is written. Use this to translate column names or values into
372 the format the API expects.
373  
374 For this to work usefully behind Fastly, we also need to enable streaming
375 miss so that Fastly streams the data to the end-user as it gets it:
376 L<https://docs.fastly.com/guides/performance-tuning/improving-caching-performance-with-large-files#streaming-miss>.
377  
378 =head1 CONFIG
379  
380 This application can be configured by setting the C<MOJO_CONFIG>
381 environment variable to the path to a configuration file. The
382 configuration file is a Perl script containing a single hash reference,
383 like:
384  
385 # api.conf
386 {
387 broker => 'ws://127.0.0.1:5000',
388 schema => 'dbi:SQLite:api.db',
389 }
390  
391 The possible configuration keys are below:
392  
393 =over
394  
395 =item broker
396  
397 The URL to a L<Mercury> message broker, starting with C<ws://>. This
398 broker is used to forward messages to every connected user.
399  
400 =item schema
401  
402 The DBI connect string to give to L<CPAN::Testers::Schema>. If not specified,
403 will use L<CPAN::Testers::Schema/connect_from_config>.
404  
405 =back
406  
407 =head1 LOCAL TESTING
408  
409 To run an instance of this for local testing, create an C<api.conf> file
410 to configure a SQLite schema:
411  
412 # api.conf
413 {
414 schema => 'dbi:SQLite:api.sqlite3'
415 }
416  
417 For the L<CPAN::Testers::Schema> to work with SQLite, you will need to
418 install an additional CPAN module, L<DateTime::Format::SQLite>.
419  
420 Once this is configured, you can deploy a new, blank database using
421 C<< cpantesters-api eval 'app->schema->deploy' >>.
422  
423 Now you can run the API using C<< cpantesters-api daemon >>.
424  
425 =head1 SEE ALSO
426  
427 L<Mojolicious>, L<Mojolicious::Plugin::OpenAPI>,
428 L<CPAN::Testers::Schema>,
429 L<http://github.com/cpan-testers/cpantesters-project>,
430 L<http://www.cpantesters.org>
431  
432 =head1 AUTHOR
433  
434 Doug Bell <preaction@cpan.org>
435  
436 =head1 CONTRIBUTORS
437  
438 =for stopwords Breno G. de Oliveira mohawk2 Nick Tonkin
439  
440 =over 4
441  
442 =item *
443  
444 Breno G. de Oliveira <garu@cpan.org>
445  
446 =item *
447  
448 mohawk2 <mohawk2@users.noreply.github.com>
449  
450 =item *
451  
452 Nick Tonkin <1nickt@users.noreply.github.com>
453  
454 =back
455  
456 =head1 COPYRIGHT AND LICENSE
457  
458 This software is copyright (c) 2018 by Doug Bell.
459  
460 This is free software; you can redistribute it and/or modify it under
461 the same terms as the Perl 5 programming language system itself.
462  
463 =cut
« API/Controller/Summary.pm ↑ Summary API/Controller/Release.pm »