lib/PAGI/Middleware/XSendfile.pm

filter: Statementstmt 97.4% 76 / 78 Branchbran 85.2% 29 / 34 Conditioncond 71.4% 10 / 14 MC/DCmcdc 55.5% 5 / 9 Subroutinesub 100% 11 / 11 Podpod 100% 1 / 1 totaltotal 89.8% 132 / 147 CC 24 SCAR 17.4
CC
24
Cov
91%
__ANON__
9.0
_extract_path
7.3
_map_path
6.1
CRAP 5.7
« lib/PAGI/App/Throttle.pm ↑ Summary lib/PAGI/Middleware/TrustedHosts.pm »
1 package PAGI::Middleware::XSendfile;
2 1 $PAGI::Middleware::XSendfile::VERSION = '0.002002';
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use parent 'PAGI::Middleware';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 PAGI::Middleware::XSendfile - Delegate file serving to reverse proxy
12  
13 =head1 SYNOPSIS
14  
15 use PAGI::Middleware::Builder;
16  
17 # For Nginx (X-Accel-Redirect)
18 my $app = builder {
19 enable 'XSendfile',
20 type => 'X-Accel-Redirect',
21 mapping => '/protected/files/'; # URL prefix for internal location
22 $my_app;
23 };
24  
25 # For Apache (mod_xsendfile)
26 my $app = builder {
27 enable 'XSendfile',
28 type => 'X-Sendfile';
29 $my_app;
30 };
31  
32 # For Lighttpd
33 my $app = builder {
34 enable 'XSendfile',
35 type => 'X-Lighttpd-Send-File';
36 $my_app;
37 };
38  
39 =head1 DESCRIPTION
40  
41 PAGI::Middleware::XSendfile intercepts file responses and replaces them with
42 a special header that tells the reverse proxy (Nginx, Apache, Lighttpd) to
43 serve the file directly. This is the recommended approach for serving large
44 files in production, as it:
45  
46 =over 4
47  
48 =item * Frees up your application worker immediately
49  
50 =item * Uses the reverse proxy's optimized sendfile implementation
51  
52 =item * Supports all the proxy's features (caching, range requests, etc.)
53  
54 =back
55  
56 =head2 How It Works
57  
58 When your application sends a file response:
59  
60 await $send->({
61 type => 'http.response.body',
62 file => '/var/www/files/large.bin',
63 });
64  
65 This middleware intercepts it and instead sends:
66  
67 # Headers include: X-Accel-Redirect: /protected/files/large.bin
68 # Body is empty - proxy serves the file
69  
70 =head1 REVERSE PROXY CONFIGURATION
71  
72 =head2 Nginx
73  
74 Configure an internal location that maps to your files:
75  
76 location /protected/files/ {
77 internal;
78 alias /var/www/files/;
79 }
80  
81 Then use:
82  
83 enable 'XSendfile',
84 type => 'X-Accel-Redirect',
85 mapping => { '/var/www/files/' => '/protected/files/' };
86  
87 =head2 Apache
88  
89 Enable mod_xsendfile and allow sending from your directory:
90  
91 XSendFile On
92 XSendFilePath /var/www/files
93  
94 Then use:
95  
96 enable 'XSendfile', type => 'X-Sendfile';
97  
98 =head2 Lighttpd
99  
100 Enable mod_fastcgi with C<x-sendfile> option:
101  
102 fastcgi.server = (
103 "/" => ((
104 "socket" => "/tmp/app.sock",
105 "x-sendfile" => "enable"
106 ))
107 )
108  
109 Then use:
110  
111 enable 'XSendfile', type => 'X-Lighttpd-Send-File';
112  
113 =head1 CONFIGURATION
114  
115 =over 4
116  
117 =item * type (required)
118  
119 The header type to use. One of:
120  
121 X-Accel-Redirect - Nginx
122 X-Sendfile - Apache mod_xsendfile
123 X-Lighttpd-Send-File - Lighttpd
124  
125 =item * mapping (for X-Accel-Redirect)
126  
127 Path mapping from filesystem paths to Nginx internal URLs. Can be:
128  
129 A string prefix (simple case):
130  
131 mapping => '/protected/'
132 # /var/www/files/foo.txt => /protected/var/www/files/foo.txt
133  
134 A hashref for path translation:
135  
136 mapping => { '/var/www/files/' => '/protected/' }
137 # /var/www/files/foo.txt => /protected/foo.txt
138  
139 =item * variation (optional)
140  
141 Additional string appended to Vary header to prevent caching issues.
142  
143 =back
144  
145 =head1 RANGE REQUESTS / PARTIAL CONTENT
146  
147 B<For best results with XSendfile, disable range handling in your app.>
148  
149 When using XSendfile with a reverse proxy, you should disable Range request
150 handling in your file-serving app (L<PAGI::App::File> or L<PAGI::Middleware::Static>)
151 and let the proxy handle Range requests natively:
152  
153 use PAGI::Middleware::Builder;
154 use PAGI::App::File;
155  
156 my $app = builder {
157 enable 'XSendfile',
158 type => 'X-Accel-Redirect',
159 mapping => { '/var/www/files/' => '/protected/' };
160  
161 PAGI::App::File->new(
162 root => '/var/www/files',
163 handle_ranges => 0, # Let nginx handle Range requests
164 )->to_app;
165 };
166  
167 With C<handle_ranges =E<gt> 0>:
168  
169 =over 4
170  
171 =item * Your app always sends full file paths via X-Sendfile
172  
173 =item * The proxy receives Range headers directly from clients
174  
175 =item * The proxy handles Range requests using its optimized sendfile
176  
177 =back
178  
179 This is more efficient than handling ranges in Perl.
180  
181 =head2 Why Partial Responses Bypass XSendfile
182  
183 If your app does process Range requests (the default behavior), it sends
184 file responses with C<offset> and C<length>. This middleware will pass
185 such responses through unchanged because reverse proxies don't support
186 byte range parameters in X-Sendfile headers:
187  
188 # This will use X-Sendfile (full file)
189 await $send->({
190 type => 'http.response.body',
191 file => '/path/to/file.bin',
192 });
193  
194 # This will bypass X-Sendfile (partial content)
195 await $send->({
196 type => 'http.response.body',
197 file => '/path/to/file.bin',
198 offset => 1000,
199 length => 500,
200 });
201  
202 The recommended approach is to set C<handle_ranges =E<gt> 0> so your app
203 never produces partial responses, and let the proxy handle Range requests.
204  
205 =head1 FILEHANDLE SUPPORT
206  
207 This middleware supports two types of file responses:
208  
209 =head2 File Path (Recommended)
210  
211 await $send->({
212 type => 'http.response.body',
213 file => '/path/to/file.bin',
214 });
215  
216 This always works - the path is used directly.
217  
218 =head2 Filehandle with path() Method
219  
220 use IO::File::WithPath; # or similar
221 my $fh = IO::File::WithPath->new('/path/to/file.bin', 'r');
222  
223 await $send->({
224 type => 'http.response.body',
225 fh => $fh,
226 });
227  
228 For filehandle responses, the middleware will only intercept if the
229 filehandle object has a C<path()> method that returns the filesystem path.
230 This is compatible with:
231  
232 =over 4
233  
234 =item * L<IO::File::WithPath>
235  
236 =item * L<Plack::Util/set_io_path>
237  
238 =item * Any blessed filehandle with a C<path()> method
239  
240 =back
241  
242 B<Plain filehandles without a path() method will be served normally>
243 (not via X-Sendfile). If you need X-Sendfile support for filehandles,
244 add a C<path> method to your IO object:
245  
246 # Simple approach: bless and add path method
247 sub make_sendfile_fh {
248 my ($path) = @_;
249 open my $fh, '<', $path or die $!;
250 bless $fh, 'My::FH::WithPath';
251 return $fh;
252 }
253  
254 package My::FH::WithPath;
255 sub path { ${*{$_[0]}}{path} } # or store path however you prefer
256  
257 =cut
258  
259 1 my %VALID_TYPES = (
260 'X-Accel-Redirect' => 1,
261 'X-Sendfile' => 1,
262 'X-Lighttpd-Send-File' => 1,
263 );
264  
265 16 ▶sub _init {
Subroutine _init: called CC=3 SCAR=11.0
266 16 my ($self, $config) = @_;
267  
268 my $type = $config->{type}
269 16 ▶ or die "XSendfile middleware requires 'type' parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $type = $config->{"type"} or die "XSendfile middleware requires 'type' parameter" 15 1 16
270  
271 die "Invalid XSendfile type '$type'. Must be one of: "
272 . join(', ', sort keys %VALID_TYPES)
273 15 ▶ unless $VALID_TYPES{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_TYPES{$type} 1 14 15
274  
275 14 $self->{type} = $type;
276 14 $self->{mapping} = $config->{mapping};
277 14 $self->{variation} = $config->{variation};
278 }
279  
280 14 ▶sub wrap {
Subroutine wrap: called CC=1 SCAR=0.0
Pod documented
281 14 my ($self, $app) = @_;
282  
283 14 ▶ return async sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
284 14 my ($scope, $receive, $send) = @_;
285  
286 # Only handle HTTP requests
287 14 ▶ if ($scope->{type} ne 'http') {
Branch: 1 branch
BranchTrueFalseTotal
if ($scope->{"type"} ne "http") 1 13 14
288 1 await $app->($scope, $receive, $send);
289 1 return;
290 }
291  
292 13 my $pending_start;
293  
294 27 ▶ my $wrapped_send = async sub {
Subroutine __ANON__: called CC=9 SCAR=22.0
295 27 my ($event) = @_;
296 27 my $type = $event->{type};
297  
298 27 ▶ if ($type eq 'http.response.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "http.response.start") 13 14 27
299 # Buffer the start event - we might need to modify headers
300 13 $pending_start = $event;
301 13 return;
302 }
303  
304 14 ▶ if ($type eq 'http.response.body') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "http.response.body") 14 0 14
305 14 my $path = $self->_extract_path($event);
306  
307 # Skip XSendfile for partial content (offset/length) - proxies don't support it
308 14 ▶ my $is_partial = defined $event->{offset} || defined $event->{length};
Condition100%3/3
defined $event->{'offset'} || defined $event->{'length'}
l!l&&r!l&&!r
1112
MC/DC100%2/2
defined $event->{'offset'} || defined $event->{'length'}
defined $event->{'offset'} defined $event->{'length'}
Truth table100%3/3
A || B
A= defined $event->{'offset'}B= defined $event->{'length'}
ABresult
1X1
011
000
309  
310 14 ▶ if (defined $path && !$is_partial) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path and not $is_partial) 8 6 14
Condition100%3/3
defined $path and not $is_partial
!ll&&!rl&&r
428
MC/DC100%2/2
defined $path and not $is_partial
defined $path not $is_partial
Truth table100%3/3
A and not(B)
A= defined $pathB= not $is_partial
ABresult
0X0
100
111
311 # We have a full file path - use X-Sendfile
312 8 my $mapped_path = $self->_map_path($path);
313 8 ▶ my @headers = @{$pending_start->{headers} // []};
Condition50%1/2
$pending_start->{"headers"} // []
l!l
80
MC/DC0%0/1
$pending_start->{"headers"} // []
$pending_start->{"headers"}
Truth table50%1/2
A
A= $pending_start->{"headers"}
Aresult
11
00
314  
315 # Add the X-Sendfile header
316 8 push @headers, [$self->{type}, $mapped_path];
317  
318 # Add Vary header if configured
319 8 ▶ if ($self->{variation}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"variation"}) 1 7 8
320 1 push @headers, ['Vary', $self->{variation}];
321 }
322  
323 # Send response with empty body
324 await $send->({
325 type => 'http.response.start',
326 status => $pending_start->{status},
327 headers => \@headers,
328 8 });
329 8 await $send->({
330 type => 'http.response.body',
331 body => '',
332 });
333  
334 8 $pending_start = undef;
335 8 return;
336 }
337 }
338  
339 # Not a file response, or no path available - pass through
340 6 ▶ if ($pending_start) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pending_start) 5 1 6
341 5 await $send->($pending_start);
342 5 $pending_start = undef;
343 }
344 6 await $send->($event);
345 13 };
346  
347 13 await $app->($scope, $receive, $wrapped_send);
348  
349 # Flush any pending start that wasn't followed by a body
350 13 ▶ if ($pending_start) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pending_start) 0 13 13
351 0 await $send->($pending_start);
352 }
353 14 };
354 }
355  
356 14 ▶sub _extract_path {
Subroutine _extract_path: called CC=7 SCAR=19.9
357 14 my ($self, $event) = @_;
358  
359 # Direct file path - always works
360 14 ▶ return $event->{file} if defined $event->{file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $event->{"file"} 9 5 14
361  
362 # Filehandle - only if it has a path() method
363 5 ▶ if (my $fh = $event->{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fh = $event->{"fh"}) 2 3 5
364 2 ▶ if (blessed($fh) && $fh->can('path')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($fh) and $fh->can("path")) 1 1 2
Condition66%2/3
builtin::blessed($fh) and $fh->can("path")
!ll&&!rl&&r
101
MC/DC50%1/2
builtin::blessed($fh) and $fh->can("path")
builtin::blessed($fh) $fh->can("path")
Truth table66%2/3
A and B
A= builtin::blessed($fh)B= $fh->can("path")
ABresult
0X0
100
111
365 1 my $path = $fh->path;
366 1 ▶ return $path if defined $path && length $path;
Branch: 1 branch
BranchTrueFalseTotal
if defined $path and length $path 1 0 1
Condition33%1/3
defined $path and length $path
!ll&&!rl&&r
001
MC/DC0%0/2
defined $path and length $path
defined $path length $path
Truth table33%1/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
367 }
368 }
369  
370 4 return undef;
371 }
372  
373 8 ▶sub _map_path {
Subroutine _map_path: called CC=6 SCAR=18.2
374 8 my ($self, $path) = @_;
375  
376 8 my $mapping = $self->{mapping};
377  
378 # No mapping - return path as-is (for X-Sendfile/Lighttpd)
379 8 ▶ return $path unless defined $mapping;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mapping 6 2 8
380  
381 # Simple string prefix
382 2 ▶ if (!ref $mapping) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $mapping) 1 1 2
383 1 return $mapping . $path;
384 }
385  
386 # Hash mapping - find matching prefix and replace
387 1 ▶ if (ref $mapping eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mapping eq "HASH") 1 0 1
388 1 for my $from (keys %$mapping) {
389 1 ▶ if (substr($path, 0, length($from)) eq $from) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($path, 0, length $from) eq $from) 1 0 1
390 1 my $to = $mapping->{$from};
391 1 return $to . substr($path, length($from));
392 }
393 }
394 }
395  
396 # No mapping matched - return as-is
397 0 return $path;
398 }
399  
400 1 1;
401  
402 __END__
« lib/PAGI/App/Throttle.pm ↑ Summary lib/PAGI/Middleware/TrustedHosts.pm »