blib/lib/Catalyst/Plugin/Cache/HTTP.pm

filter: Statementstmt 93.1% 54 / 58 Branchbran 75.0% 21 / 28 Conditioncond 54.5% 24 / 44 MC/DCmcdc 33.3% 8 / 24 Subroutinesub 83.3% 10 / 12 Podpod 100% 1 / 1 totaltotal 70.6% 118 / 167 CC 30 SCAR 35.4
CC
30
Cov
76%
_meets_conditions
49.8
finalize_headers
3.0
__ANON__
2.0
CRAP 34.5
↑ Summary
1 package Catalyst::Plugin::Cache::HTTP;
2  
3 2 ▶use base qw(Class::Accessor::Fast);
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 2 ▶use 5.008_001;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 2 ▶use MRO::Compat;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 2 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 require List::Util;
14 2 require HTTP::Headers::ETag;
15 }
16  
17 =head1 NAME
18  
19 Catalyst::Plugin::Cache::HTTP - HTTP/1.1 cache validators for Catalyst
20  
21 =head1 VERSION
22  
23 Version 0.001000
24  
25 =cut
26  
27 2 our $VERSION = "0.001000";
28  
29 2 __PACKAGE__->mk_accessors(qw(_http_mc_finalized_headers));
30  
31 =head1 SYNOPSIS
32  
33 =head2 Load Plugin Into Application
34  
35 package MyApp;
36  
37 use Catalyst qw(Cache::HTTP);
38  
39 =head2 Create a Last-Modified Header
40
41 package MyApp::Controller::Foo;
42  
43 sub bar : Local {
44 my ($self, $c) = @_;
45 my $data = $c->model('MyApp::Model')->fetch_data;
46 my $mtime = $data->mod_time;
47  
48 ...
49 $c->response->headers->last_modified($mtime);
50 ...
51 }
52  
53 =head2 Automatic Creation of ETag
54  
55 package MyApp::View::TT;
56  
57 use base 'Catalyst::View::TT';
58 use MRO::Compat;
59 use Digest::MD5 'md5_hex';
60  
61 sub process {
62 my $self = shift;
63 my $c = $_[0];
64  
65 $self->next::method(@_)
66 or return 0;
67  
68 my $method = $c->request->method;
69 return 1
70 if $method ne 'GET' and $method ne 'HEAD' or
71 $c->stash->{nocache}; # disable caching explicitely
72  
73 my $body = $c->response->body;
74 if ($body) {
75 utf8::encode($body)
76 if utf8::is_utf8($body);
77 $c->response->headers->etag(md5_hex($body));
78 }
79  
80 return 1;
81 }
82  
83 =head1 DESCRIPTION
84  
85 Ever since mankind develops web sites, it has to deal with the problems
86 that arise when a site becomes popular. This is especially true for dynamic
87 contents. Optimizations of the web application itself are usually followed
88 by tweaking the system setup, better hardware, improved connectivity,
89 clustering and load balancing. Good if the site yields enough profit to
90 fund all this (and the people that are required).
91  
92 There are also numerous modules on the CPAN and helpful tips all over the
93 World Wide Web about how to crack the whip on Catalyst applications.
94  
95 Noticeably often is overlooked, that more than a decade ago the "fathers"
96 of the WWW have created concepts in C<HTTP/1.1> to reduce traffic between
97 web server and web client (and proxy where applicable). All common web
98 browsers support these concepts for many years now.
99  
100 These concepts can accelerate a web application and save resources at the
101 same time.
102  
103 How this is possible? You can look up the concept in RFC 2616 section 13.3,
104 plus the implementation in sections 14.19, 14.24, 14.25, 14.26, 14.28 and
105 14.44. To cut a long story short: This plugin does not manage any cache on
106 the server and avoids transmitting data where possible.
107  
108 To utilize this concept in your Catalyst based application some rather small
109 additions have to be made in the code:
110  
111 =over
112  
113 =item 1. Use the plugin
114  
115 This is easy: In the application class (often referred as MyApp.pm) just
116 add C<Cache::HTTP> to the list of plugins after C<use Catalyst>.
117  
118 =item 2. Add appropriate response headers
119  
120 Those headers are C<Last-Modified> and C<ETag>. The
121 L<< headers method of Catalyst::Response|Catalyst::Response/$res->headers >>
122 which actually provides us with an instance of L<HTTP::Headers|HTTP::Headers>
123 gives us two handy accessors to those header lines: C<last_modified> and
124 C<etag>.
125  
126 =over
127  
128 =item 2.1 C<< $c->response->headers->last_modified($unix_timestamp) >>
129  
130 If this exists in a response for a requested resource, then for the next
131 request to the same resource a modern web browser will add a line to the
132 request headers to check if the resource data has changed since the
133 C<Last-Modified> date, that was given with the last response. If the
134 server answers with a status code C<304> and an empty body, the browser
135 takes the data for this resource from its local cache.
136  
137 =item 2.2 C<< $c->response->headers->etag($entity_tag) >>
138  
139 The entity tag is a unique representation of data from a resource. Usually
140 a digest of the response body serves well for this purpose, so for that
141 case whenever you read "ETag" you might replace it with "checksum". If an
142 C<Etag> exists in a response for a requested resource, then for the next
143 request to the same resource the browser will add a line to the request
144 headers with that ETag, that tells the server to only transmit the body if
145 the ETag for the resource has changed. If it hasn't the server responds
146 with a status code C<304> and an empty body, and the browser takes the
147 data for this resource from its local cache.
148  
149 =back
150  
151 =back
152  
153 =head1 CAVEATS
154  
155 Using this concept involves the risk of breaking something!
156  
157 Especially the C<Last-Modified> header has some flaws:
158  
159 First of all the accuracy of it cannot be better than the HTTP time
160 interval: one second.
161  
162 But what is really hazardous is trying to calculate a last_modified
163 timestamp for dynamic pages.
164  
165 As a rough rule of thumb, never use C<last_modified> when
166  
167 =over
168  
169 =item *
170  
171 serving results joined from multiple sources,
172  
173 =item *
174  
175 the output depends on input parameters.
176  
177 =back
178  
179 Hence C<Last-Modified> is ideal for serving data without changing it
180 (e.g. images) or for an RSS feed where C<Last-Modified> is the time of the
181 latest entry.
182  
183 An C<ETag> header that is calculated as a checksum of the actual
184 response body is much more robust in general. The only real drawback is,
185 that calculating this checksum costs a few CPU cycles. The L</SYNOPSIS> at
186 the top shows an example how to create this C<ETag> header automatically.
187  
188 =head1 INTERNAL METHODS
189  
190 =head2 finalize_headers
191  
192 This hooks into the chain of C<finalize_headers> methods and checks the
193 request headers C<If-Match>, C<If-Unmodified-Since>, C<If-None-Match> and
194 C<If-Modified-Since> as well as the response headers C<ETag> and
195 C<Last-Modified>. Sets the status response code to C<304 Not Modified>
196 if those fields indicate, that the data for the resource has not changed
197 since the last request from the same client, so the client will use a
198 locally cache copy of the resource data.
199  
200 =cut
201  
202 21 ▶sub finalize_headers {
Subroutine finalize_headers: called CC=3 SCAR=11.0
Pod documented
203 21 my $c = shift;
204  
205 21 ▶ return if $c->_http_mc_finalized_headers;
Branch: 1 branch
BranchTrueFalseTotal
if $c->_http_mc_finalized_headers 0 21 21
206  
207 21 my $status = $c->_meets_conditions;
208 21 ▶ if ($status) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status) 9 12 21
209 9 $c->response->status($status);
210 9 $c->response->body('');
211 }
212  
213 21 $c->_http_mc_finalized_headers(1); # Kilroy was here
214  
215 21 return $c->next::method(@_);
216 }
217  
218 # code borrowed from apache 2.2.10 modules/http/http_protocol.c
219  
220 21 ▶sub _meets_conditions {
Subroutine _meets_conditions: called CC=28 SCAR=39.1
221 21 my $c = $_[0];
222 21 my $req = $c->request;
223 21 my $headers_in = $req->headers;
224 21 my $res = $c->response;
225 21 my $headers_out = $res->headers;
226 21 ▶ my $status = $res->status || 200;
Condition50%1/2
$res->status || 200
l!l
210
MC/DC0%0/1
$res->status || 200
$res->status
Truth table50%1/2
A
A= $res->status
Aresult
11
00
227  
228 21 ▶ $status < 300 and $status >= 200 or return 0;
Branch: 1 branch
BranchTrueFalseTotal
$status < 300 and $status >= 200 or return 0 21 0 21
Condition33%1/3
$status < 300 and $status >= 200
!ll&&!rl&&r
0021
MC/DC0%0/2
$status < 300 and $status >= 200
$status < 300 $status >= 200
Truth table33%1/3
A and B
A= $status < 300B= $status >= 200
ABresult
0X0
100
111
229  
230 21 my $etag = $headers_out->etag;
231 21 my $now = time;
232 21 ▶ my $mtime = $headers_out->last_modified || $now;
Condition66%2/3
$headers_out->last_modified || $now
l!l&&r!l&&!r
7140
MC/DC0%0/2
$headers_out->last_modified || $now
$headers_out->last_modified $now
Truth table66%2/3
A || B
A= $headers_out->last_modifiedB= $now
ABresult
1X1
011
000
233 21 my (@a, $t);
234  
235 21 ▶ if (@a = $headers_in->if_match) {
Branch: 2 branches
BranchTrueFalseTotal
if (@a = $headers_in->if_match) { } 6 15 21
elsif ($t = $headers_in->if_unmodified_since and $mtime > $t) { } 1 27 28
236 # If an If-Match request-header field was given
237 # AND the field value is not "*" (meaning match anything)
238 # AND if our strong ETag does not match any entity tag in that
239 # field, respond with a status of 412 (Precondition Failed).
240 return 412
241 if $a[0] ne '"*"' and (
242 not defined($etag) or
243 substr($etag, 0, 1) eq 'W' or
244 6 ▶ not (List::Util::first { $etag eq $_ } @a)
Subroutine __ANON__: called CC=1 SCAR=0.1
Branch: 1 branch
BranchTrueFalseTotal
if $a[0] ne "\"*\"" and !defined($etag) || substr($etag, 0, 1) eq "W" || !&List::Util::first(sub { $etag eq $_; } , @a) 3 3 6
Condition66%6/9
$a[0] ne "\"*\"" and !defined($etag) || substr($etag, 0, 1) eq "W" || !&List::Util::first(sub { $etag eq $_; } , @a)
!ll&&!rl&&r
123
not defined $etag or substr($etag, 0, 1) eq "W" or not &List::Util::first(sub { $etag eq $_; } , @a)
l!l&&r!l&&!r
032
not defined $etag or substr($etag, 0, 1) eq "W"
l!l&&r!l&&!r
005
MC/DC50%2/4
$a[0] ne "\"*\"" and !defined($etag) || substr($etag, 0, 1) eq "W" || !&List::Util::first(sub { $etag eq $_; } , @a)
$a[0] ne "\"*\"" not defined $etag substr($etag, 0, 1) eq "W" not &List::Util::first(sub { $etag eq $_; } , @a)
Truth table60%3/5
A and not(B) or C or not(D)
A= $a[0] ne "\"*\""B= not defined $etagC= substr($etag, 0, 1) eq "W"D= not &List::Util::first(sub { $etag eq $_; } , @a)
ABCDresult
0XXX0
10000
11XX1
101X1
10011
245 );
246 }
247 ▶ elsif ($t = $headers_in->if_unmodified_since and $mtime > $t) {
Condition100%3/3
$t = $headers_in->if_unmodified_since and $mtime > $t
!ll&&!rl&&r
1311
MC/DC100%2/2
$t = $headers_in->if_unmodified_since and $mtime > $t
$t = $headers_in->if_unmodified_since $mtime > $t
Truth table100%3/3
A and B
A= $t = $headers_in->if_unmodified_sinceB= $mtime > $t
ABresult
0X0
100
111
248 # Else if a valid If-Unmodified-Since request-header field was
249 # given AND the requested resource has been modified since the
250 # time specified in this field, then the server MUST respond
251 # with a status of 412 (Precondition Failed).
252 # RFC 2616 14.28 does not tell what to do when no Last-Modified
253 # header exists in the response. This implementation treats this
254 # situation as if the resource has been modified now.
255 1 return 412;
256 }
257  
258 17 my $method = uc $req->method;
259 17 my $not_modified;
260  
261 17 ▶ if (@a = $headers_in->if_none_match) {
Branch: 1 branch
BranchTrueFalseTotal
if (@a = $headers_in->if_none_match) 9 8 17
262 # If an If-None-Match request-header field was given
263 # AND the field value is "*" (meaning match anything)
264 # OR our ETag matches any of the entity tags in that field, fail.
265 #
266 # If the request method was GET or HEAD, failure means the server
267 # SHOULD respond with a 304 (Not Modified) response.
268 # For all other request methods, failure means the server MUST
269 # respond with a status of 412 (Precondition Failed).
270 #
271 # GET or HEAD allow weak etag comparison, all other methods require
272 # strong comparison. We can only use weak if it's not a range request.
273 9 ▶ if ($method eq 'GET' or $method eq 'HEAD') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq 'GET' or $method eq 'HEAD') { } 9 0 9
Condition33%1/3
$method eq "GET" or $method eq "HEAD"
l!l&&r!l&&!r
900
MC/DC0%0/2
$method eq "GET" or $method eq "HEAD"
$method eq "GET" $method eq "HEAD"
Truth table33%1/3
A or B
A= $method eq "GET"B= $method eq "HEAD"
ABresult
1X1
011
000
274 9 ▶ if ($a[0] eq '"*"') {
Branch: 2 branches
BranchTrueFalseTotal
if ($a[0] eq '"*"') { } 1 8 9
elsif (defined $etag) { } 8 0 8
275 1 $not_modified = 1;
276 }
277 elsif (defined $etag) {
278 8 ▶ if ($headers_in->header('Range')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers_in->header('Range')) { } 0 8 8
279 $not_modified =
280 substr($etag, 0, 1) ne 'W' &&
281 0 ▶ !!(List::Util::first { $etag eq $_ } @a);
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
substr($etag, 0, 1) ne 'W' && !!&List::Util::first(sub { $etag eq $_; } , @a)
!ll&&!rl&&r
000
MC/DC0%0/2
substr($etag, 0, 1) ne 'W' && !!&List::Util::first(sub { $etag eq $_; } , @a)
substr($etag, 0, 1) ne 'W' !!&List::Util::first(sub { $etag eq $_; } , @a)
Truth table0%0/3
A && B
A= substr($etag, 0, 1) ne 'W'B= !!&List::Util::first(sub { $etag eq $_; } , @a)
ABresult
0X0
100
111
282 }
283 else {
284 8 ▶ $not_modified = !!(List::Util::first { $etag eq $_ } @a);
Subroutine __ANON__: called CC=1 SCAR=0.0
285 }
286 }
287 }
288 else {
289 return 412
290 if $a[0] eq '"*"' or
291 0 ▶ defined($etag) and List::Util::first { $etag eq $_ } @a;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if $a[0] eq "\"*\"" or defined $etag and &List::Util::first(sub { $etag eq $_; } , @a) 0 0 0
Condition0%0/6
$a[0] eq "\"*\"" or defined $etag and &List::Util::first(sub { $etag eq $_; } , @a)
l!l&&r!l&&!r
000
defined $etag and &List::Util::first(sub { $etag eq $_; } , @a)
!ll&&!rl&&r
000
MC/DC0%0/3
$a[0] eq "\"*\"" or defined $etag and &List::Util::first(sub { $etag eq $_; } , @a)
$a[0] eq "\"*\"" defined $etag &List::Util::first(sub { $etag eq $_; } , @a)
Truth table0%0/4
A or B and C
A= $a[0] eq "\"*\""B= defined $etagC= &List::Util::first(sub { $etag eq $_; } , @a)
ABCresult
1XX1
0111
00X0
0100
292 }
293 }
294  
295 17 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "GET" and $not_modified || !@a and $t = $headers_in->if_modified_since) 5 12 17
Condition88%8/9
$method eq "GET" and $not_modified || !@a and $t = $headers_in->if_modified_since
!ll&&!rl&&r
485
$method eq "GET" and $not_modified || !@a
!ll&&!rl&&r
0413
$not_modified or not @a
l!l&&r!l&&!r
584
MC/DC75%3/4
$method eq "GET" and $not_modified || !@a and $t = $headers_in->if_modified_since
$method eq "GET" $not_modified not @a $t = $headers_in->if_modified_since
Truth table83%5/6
A and B or not(C) and D
A= $method eq "GET"B= $not_modifiedC= not @aD= $t = $headers_in->if_modified_since
ABCDresult
0XXX0
100X0
11X00
10100
11X11
10111
296 $method eq 'GET' and
297 ($not_modified or not @a) and
298 $t = $headers_in->if_modified_since
299 ) {
300 # Else if a valid If-Modified-Since request-header field was given
301 # AND it is a GET request
302 # AND the requested resource has not been modified since the time
303 # specified in this field, then the server MUST
304 # respond with a status of 304 (Not Modified).
305 # A date later than the server's current request time is invalid.
306 5 ▶ $not_modified = $t >= $mtime && $t <= $now;
Condition66%2/3
$t >= $mtime && $t <= $now
!ll&&!rl&&r
302
MC/DC50%1/2
$t >= $mtime && $t <= $now
$t >= $mtime $t <= $now
Truth table66%2/3
A && B
A= $t >= $mtimeB= $t <= $now
ABresult
0X0
100
111
307 }
308  
309 17 ▶ return $not_modified ? 304 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$not_modified ? : 5 12 17
310 }
311  
312  
313 2 1;
314  
315 __END__
↑ Summary