blib/lib/PGXN/API/Router.pm

filter: Statementstmt 100% 107 / 107 Branchbran 85.0% 17 / 20 Conditioncond 85.7% 12 / 14 MC/DCmcdc 77.7% 7 / 9 Subroutinesub 100% 25 / 25 Podpod 100% 1 / 1 totaltotal 96.0% 169 / 176 CC 18 SCAR 11.3
CC
18
Cov
96%
__ANON__
7.0
__ANON__
5.1
app
4.0
CRAP 3.1
« Build ↑ Summary blib/lib/PGXN/API.pm »
1 package PGXN::API::Router;
2  
3 1 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use PGXN::API;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Plack::Builder;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Plack::App::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Plack::App::Directory;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use PGXN::API::Searcher;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use List::MoreUtils qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Plack::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use File::Spec::Functions qw(catdir);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 our $VERSION = v0.21.1;
17  
18 sub app {
19 2 ▶ my ($class, %params) = @_;
Subroutine app: called CC=4 SCAR=13.9
Pod documented
20  
21 2 ▶ unless ($params{errors_to} && $params{errors_from}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params{"errors_to"} and $params{"errors_from"}) 1 1 2
Condition66%2/3
$params{"errors_to"} and $params{"errors_from"}
!ll&&!rl&&r
101
MC/DC50%1/2
$params{"errors_to"} and $params{"errors_from"}
$params{"errors_to"} $params{"errors_from"}
Truth table66%2/3
A and B
A= $params{"errors_to"}B= $params{"errors_from"}
ABresult
0X0
100
111
22 1 die "Missing required parameters errors_to and errors_from\n";
23 }
24  
25 PGXN::API->instance->doc_root(delete $params{doc_root})
26 1 ▶ if $params{doc_root};
Branch: 1 branch
BranchTrueFalseTotal
if $params{"doc_root"} 0 1 1
27 1 my $root = PGXN::API->instance->doc_root;
28  
29 # Identify distribution files as zip files.
30 1 my ($zip_ext) = PGXN::API->instance->uri_templates->{download} =~ /([.][^.]+)$/;
31 1 $Plack::MIME::MIME_TYPES->{$zip_ext} = $Plack::MIME::MIME_TYPES->{'.zip'};
32  
33 builder {
34 1 ▶ enable 'ErrorDocument', 500, '/error', subrequest => 1;
Subroutine __ANON__: called CC=4 SCAR=13.9
35 1 enable 'HTTPExceptions';
36 1 enable 'StackTrace', no_print_errors => 1;
37 1 enable 'JSONP', callback_key => 'callback';
38 enable sub {
39 1 ▶ my $app = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
40 sub {
41 39 ▶ my $res = $app->(@_);
Subroutine __ANON__: called CC=1 SCAR=0.0
42 Plack::Util::response_cb($res, sub {
43 39 ▶ my $res = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
44 39 push @{ $res->[1] },
45 'X-PGXN-API-Version' => PGXN::API->version_string;
46 39 });
47 1 };
48 1 };
49  
50 # Serve most stuff as plain files.
51 1 my $files = Plack::App::File->new(root => $root)->to_app;
52 mount '/' => sub {
53 7 ▶ my $env = shift;
Subroutine __ANON__: called CC=2 SCAR=6.9
54 7 ▶ $env->{PATH_INFO} = '/index.html' if $env->{PATH_INFO} eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $env->{"PATH_INFO"} eq "/" 1 6 7
55 7 $files->($env);
56 1 };
57  
58 # Handle searches.
59 1 my $searcher = PGXN::API::Searcher->new($root);
60 mount '/search' => sub {
61 23 ▶ my $req = Plack::Request->new(shift);
Subroutine __ANON__: called CC=7 SCAR=19.5
62  
63 # Make sure we have a valid request.
64 23 local $1;
65 return [
66 23 ▶ 404,
Branch: 1 branch
BranchTrueFalseTotal
unless $req->path_info =~ m[^/((?:d(?:oc|ist)|extension|user|tag)s)/?$]u 5 18 23
67 ['Content-Type' => 'text/plain', 'Content-Length' => 9],
68 ['not found']
69 ] if $req->path_info !~ m{^/((?:d(?:oc|ist)|extension|user|tag)s)/?$};
70 18 my $in = $1;
71  
72 18 my $params = $req->query_parameters;
73 18 my $q = $params->{q};
74 return [
75 400,
76 ['Content-Type' => 'text/plain', 'Content-Length' => 38],
77 ['Bad request: Invalid or missing "q" query param.']
78 18 ▶ ] if !defined $q || any { $q eq $_ } '', '*', '?';
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if not defined $q or &any(sub { $q eq $_; } , "", "*", "?") 4 14 18
Condition100%3/3
not defined $q or &any(sub {
l!l&&r!l&&!r
1314
MC/DC100%2/2
not defined $q or &any(sub { $q eq $_; } , "", "*", "?")
not defined $q &any(sub { $q eq $_; } , "", "*", "?")
Truth table100%3/3
not(A) or B
A= not defined $qB= &any(sub { $q eq $_; } , "", "*", "?")
ABresult
1X1
011
000
79  
80 # Make sure "o" and "l" params are valid.
81 14 for my $param (qw(o l)) {
82 27 my $val = $params->{$param};
83 return [
84 27 ▶ 400,
Branch: 1 branch
BranchTrueFalseTotal
if $val and not $val =~ /^\d+$/u 2 25 27
Condition100%3/3
$val and not $val =~ /^\d+$/u
!ll&&!rl&&r
5202
MC/DC100%2/2
$val and not $val =~ /^\d+$/u
$val not $val =~ /^\d+$/u
Truth table100%3/3
A and not(B)
A= $valB= not $val =~ /^\d+$/u
ABresult
0X0
100
111
85 ['Content-Type' => 'text/plain', 'Content-Length' => 37],
86 [qq{Bad request: invalid "$param" query param.}]
87 ] if $val && $val !~ /^\d+$/;
88 }
89  
90 # Give 'em the results.
91 my $json = encode_json $searcher->search(
92 in => $in,
93 query => decode_utf8($q),
94 offset => scalar $params->{o},
95 limit => scalar $params->{l},
96 12 );
97 return [
98 12 200,
99 ['Content-Type' => 'application/json', 'Content-Length' => length $json ],
100 [$json],
101 ]
102 1 };
103  
104 # For source browsing, some things should be text/plain.
105 1 my $mimes = { %{ $Plack::MIME::MIME_TYPES } };
106 1 for my $ext (keys %{ $mimes }) {
107 $mimes->{$ext} = 'text/plain'
108 if $mimes->{$ext} =~ /html|x-c|xml|calendar|vcard/
109 640 ▶ || any { $ext eq $_ } qw(.bat .css .eml .js .json .mime .swf);
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if $mimes->{$ext} =~ /html|x-c|xml|calendar|vcard/u or &any(sub { $ext eq $_; } , ".bat", ".css", ".eml", ".js", ".json", ".mime", ".swf") 104 536 640
Condition100%3/3
$mimes->{$ext} =~ /html|x-c|xml|calendar|vcard/u or &any(sub {
l!l&&r!l&&!r
977536
MC/DC100%2/2
$mimes->{$ext} =~ /html|x-c|xml|calendar|vcard/u or &any(sub { $ext eq $_; } , ".bat", ".css", ".eml", ".js", ".json", ".mime", ".swf")
$mimes->{$ext} =~ /html|x-c|xml|calendar|vcard/u &any(sub { $ext eq $_; } , ".bat", ".css", ".eml", ".js", ".json", ".mime", ".swf")
Truth table100%3/3
A or B
A= $mimes->{$ext} =~ /html|x-c|xml|calendar|vcard/uB= &any(sub { $ext eq $_; } , ".bat", ".css", ".eml", ".js", ".json", ".mime", ".swf")
ABresult
1X1
011
000
110 }
111 1 my $src_dir = Plack::App::Directory->new(
112 root => catdir $root, 'src'
113 )->to_app;
114  
115 mount '/src' => sub {
116 4 ▶ local $Plack::MIME::MIME_TYPES = $mimes;
Subroutine __ANON__: called CC=1 SCAR=0.0
117 4 $src_dir->(shift)
118 1 };
119  
120 mount '/_index' => sub {
121 # Never allow access here.
122 return [
123 4 ▶ 404,
Subroutine __ANON__: called CC=1 SCAR=0.0
124 ['Content-Type' => 'text/plain', 'Content-Length' => 9],
125 ['not found']
126 ];
127 1 };
128  
129 mount '/error' => sub {
130 1 ▶ my $env = shift;
Subroutine __ANON__: called CC=5 SCAR=16.2
131  
132 # Pull together the original request environment.
133 my $err_env = { map {
134 26 my $k = $_;
135 s/^psgix[.]errordocument[.]//
136 26 ▶ ? /plack[.]stacktrace[.]/ ? () : ($_ => $env->{$k} )
Branch: 2 branches
BranchTrueFalseTotal
s/^psgix[.]errordocument[.]//u ? : 3 23 26
/plack[.]stacktrace[.]/u ? : 0 3 3
137 : ();
138 1 } keys %{ $env } };
139 1 my $uri = Plack::Request->new($err_env)->uri;
140  
141 1 ▶ if (%{ $err_env }) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$err_env;}) 1 0 1
142 # Send an email to the administrator.
143 # XXX Need configuration.
144 1 require Email::MIME;
145 1 require Email::Sender::Simple;
146 1 require Data::Dump;
147 my $email = Email::MIME->create(
148 header => [
149 From => $params{errors_from},
150 To => $params{errors_to},
151 Subject => 'PGXN API Internal Server Error',
152 ],
153 attributes => {
154 content_type => 'text/plain',
155 charset => 'UTF-8',
156 },
157 body => "An error occurred during a request to $uri.\n\n"
158 . "Environment:\n\n" . Data::Dump::pp($err_env)
159 . "\n\nTrace:\n\n"
160 1 ▶ . ($env->{'plack.stacktrace.text'} || 'None found. :-(')
Condition50%1/2
$env->{'plack.stacktrace.text'} || 'None found. :-('
l!l
10
MC/DC0%0/1
$env->{'plack.stacktrace.text'} || 'None found. :-('
$env->{'plack.stacktrace.text'}
Truth table50%1/2
A
A= $env->{'plack.stacktrace.text'}
Aresult
11
00
161 . "\n",
162 );
163 1 Email::Sender::Simple->send($email);
164 }
165  
166 return [
167 1 200, # Only handled by ErrorDocument, which keeps 500.
168 ['Content-Type' => 'text/plain', 'Content-Length' => 21],
169 ['internal server error']
170 ];
171 1 };
172  
173 1 };
174 }
175  
176 1 1;
177  
178 =head1 Name
179  
180 PGXN::API::Router - The PGXN::API request router.
181  
182 =head1 Synopsis
183  
184 # In app.pgsi
185 use PGXN::API::Router;
186 PGXN::API::Router->app;
187  
188 =head1 Description
189  
190 This class defines the HTTP request routing table used by PGXN::API. Unless
191 you're modifying the PGXN::API routes, you won't have to worry about it. Just
192 know that this is the class that Plack uses to fire up the app.
193  
194 =head1 Interface
195  
196 =head2 Class Methods
197  
198 =head3 C<app>
199  
200 PGXN::API->app(%params);
201  
202 Returns the PGXN::API Plack app. The supported parameters are:
203  
204 =over
205  
206 =item C<doc_root>
207  
208 The path to use for the API document root.
209  
210 =item C<errors_to>
211  
212 An email address to which error emails should be sent.
213  
214 =item C<errors_from>
215  
216 An email address from which alert emails should be sent.
217  
218 =back
219  
220 See L<pgxn_api_server> for an example usage.
221  
222 =head1 Author
223  
224 David E. Wheeler <david.wheeler@pgexperts.com>
225  
226 =head1 Copyright and License
227  
228 Copyright (c) 2011-2025 David E. Wheeler.
229  
230 This module is free software; you can redistribute it and/or modify it under
231 the L<PostgreSQL License|http://www.opensource.org/licenses/postgresql>.
232  
233 Permission to use, copy, modify, and distribute this software and its
234 documentation for any purpose, without fee, and without a written agreement is
235 hereby granted, provided that the above copyright notice and this paragraph
236 and the following two paragraphs appear in all copies.
237  
238 In no event shall David E. Wheeler be liable to any party for direct,
239 indirect, special, incidental, or consequential damages, including lost
240 profits, arising out of the use of this software and its documentation, even
241 if David E. Wheeler has been advised of the possibility of such damage.
242  
243 David E. Wheeler specifically disclaims any warranties, including, but not
244 limited to, the implied warranties of merchantability and fitness for a
245 particular purpose. The software provided hereunder is on an "as is" basis,
246 and David E. Wheeler has no obligations to provide maintenance, support,
247 updates, enhancements, or modifications.
248  
249 =cut
« Build ↑ Summary blib/lib/PGXN/API.pm »