blib/lib/Mojolicious/Plugin/Buffer.pm

filter: Statementstmt 98.4% 940 / 955 Branchbran 83.2% 283 / 340 Conditioncond 69.2% 223 / 322 MC/DCmcdc 45.9% 84 / 183 Subroutinesub 99.3% 161 / 162 Podpod 100% 1 / 1 totaltotal 86.1% 1692 / 1963 CC 302 SCAR 18.3
CC
302
Cov
89%
_negotiate_encoding
18.9
_process_response
14.1
_latest_mtime
12.1
CRAP 6.3
↑ Summary blib/lib/Mojolicious/Plugin/Buffer/I18N.pm »
1 package Mojolicious::Plugin::Buffer;
2  
3 37 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 37 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 37 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 37 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Mojo::Base turns on the unicode_strings feature, under which \s matches the
10 # bytes \xA0 and \x85. Those bytes occur inside UTF-8 characters ("a" with a
11 # grave accent is C3 A0), so the white-space squasher would cut characters in
12 # half. Every pattern in this file is about ASCII markup, media types, digits
13 # or HTTP tokens, so make \s, \w and \d ASCII-only throughout.
14 37 ▶use re '/a';
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 37 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 37 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 37 ▶use Mojo::Date;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 37 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 37 ▶use Mojo::Loader qw(load_class);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 37 ▶use Mojo::Util qw(encode gzip md5_sum split_header trim);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 37 ▶use Mojolicious::Plugin::Buffer::I18N qw(i18n);
Subroutine BEGIN: called CC=1 SCAR=0.0
23 37 ▶use Mojolicious::Plugin::Buffer::Lock::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 37 ▶use Params::Get qw(get_params);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 37 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 37 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 37 ▶use Return::Set qw(set_return);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 37 ▶use Scalar::Util qw(looks_like_number refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
29 37 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
30 37 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 37 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 37 ▶use version; our $VERSION = version->declare('0.002.0');
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 # ---------------------------------------------------------------------------
36 # Constants. Nothing below this block should contain a bare number or a
37 # protocol string; if it does, it belongs up here.
38 # ---------------------------------------------------------------------------
39  
40 # HTTP status codes the plugin reasons about
41 37 Readonly::Scalar my $HTTP_MIN_FINAL => 200; # below this, an interim response
42 37 Readonly::Scalar my $HTTP_OK => 200;
43 37 Readonly::Scalar my $HTTP_NOT_MODIFIED => 304;
44 37 Readonly::Scalar my $HTTP_UNAVAILABLE => 503;
45  
46 # No Content, Partial Content and Not Modified carry no entity to rework
47 37 Readonly::Hash my %BODYLESS_STATUS => map { $_ => 1 } (204, 206, 304);
48  
49 # Only these methods are revalidated and cached
50 37 Readonly::Hash my %SAFE_METHODS => map { $_ => 1 } qw(GET HEAD);
51  
52 # Only these media types are rewritten by the HTML optimiser
53 37 Readonly::Hash my %HTML_TYPES => map { $_ => 1 } qw(text/html application/xhtml+xml);
54  
55 # Cache-Control directives that stop a request using, or a response being
56 # stored in, the server-side cache. max-age only counts when it is zero.
57 37 Readonly::Hash my %REQUEST_NO_CACHE => map { $_ => 1 } qw(no-store no-cache private max-age);
58 37 Readonly::Hash my %RESPONSE_NO_STORE => map { $_ => 1 } qw(no-store no-cache private);
59  
60 # Headers that describe one delivery rather than the page, so they are never
61 # stored with a cache entry
62 37 Readonly::Hash my %UNSTORED_HEADERS => map { lc($_) => 1 } qw(
63 Connection Content-Encoding Content-Length Date ETag Keep-Alive
64 Last-Modified Server Set-Cookie Transfer-Encoding X-Cache
65 );
66  
67 # Response header that reports what the cache did
68 37 Readonly::Scalar my $X_CACHE => 'X-Cache';
69 37 Readonly::Scalar my $HIT => 'HIT';
70 37 Readonly::Scalar my $MISS => 'MISS';
71  
72 # Prefixes keep our keys apart from anything else in a shared cache
73 37 Readonly::Scalar my $KEY_PREFIX => 'buffer:';
74 37 Readonly::Scalar my $MTIME_KEY_PREFIX => 'buffer:template-mtime:';
75  
76 # Timings, in seconds
77 37 Readonly::Scalar my $DEFAULT_LOCK_TIMEOUT => 10;
78 37 Readonly::Scalar my $DEFAULT_MTIME_DURATION => 10;
79 37 Readonly::Scalar my $DEFAULT_CACHE_DURATION => '10 minutes';
80 37 Readonly::Scalar my $MIN_WAITER_DELAY => 0.05; # a waiter always gets one tick
81 37 Readonly::Scalar my $SHARED_POLL_INTERVAL => 0.1; # how often a cross-worker waiter looks
82 37 Readonly::Scalar my $RETRY_AFTER => 1;
83  
84 # How deep the template mtime scan goes. It is the loop guard of last
85 # resort: where stat() reports no inode (Windows before Perl 5.38) a
86 # symlink loop can only be told apart by its ever-longer path.
87 37 Readonly::Scalar my $MAX_SCAN_DEPTH => 32;
88  
89 37 Readonly::Scalar my $DEFAULT_MIN_COMPRESS_SIZE => 64;
90 37 Readonly::Scalar my $DEFAULT_MIN_COMPRESS_SAVING => 16; # bytes compression must save to be used
91 37 Readonly::Scalar my $OPTIMISE_AGGRESSIVE => 2; # optimise_content level that touches JavaScript
92  
93 # Stash keys. 'buffer' is the documented per-response override; the
94 # dotted ones are private bookkeeping; mojo.finished belongs to Mojolicious.
95 37 Readonly::Scalar my $STASH_OVERRIDE => 'buffer';
96 37 Readonly::Scalar my $STASH_FLIGHT => 'buffer.flight';
97 37 Readonly::Scalar my $STASH_STORED => 'buffer.stored';
98 37 Readonly::Scalar my $STASH_FROM_CACHE => 'buffer.from_cache';
99 37 Readonly::Scalar my $STASH_WAITER => 'buffer.cache_waiter';
100 37 Readonly::Scalar my $STASH_CHECKED => 'buffer.cache_checked';
101 37 Readonly::Scalar my $STASH_KEY => 'buffer.cache_key';
102 37 Readonly::Scalar my $STASH_MTIME => 'buffer.application_mtime';
103 37 Readonly::Scalar my $STASH_FINISHED => 'mojo.finished';
104  
105 # Content codings: how to produce each one, which optional module it needs,
106 # and the legacy names clients still send
107 Readonly::Hash my %ENCODERS => (
108 61 ▶ gzip => sub { gzip($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
109 1 ▶ br => sub { require IO::Compress::Brotli; IO::Compress::Brotli::bro($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
110 0 ▶ zstd => sub { require Compress::Zstd; Compress::Zstd::compress(\$_[0]) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
111 37 );
112 37 Readonly::Hash my %ENCODING_MODULE => (br => 'IO::Compress::Brotli', zstd => 'Compress::Zstd');
113 37 Readonly::Hash my %ENCODING_ALIAS => ('x-gzip' => 'gzip');
114  
115 # Same-site links rewritten by rewrite_links, as [element, attribute]
116 37 Readonly::Array my @LINK_ATTRIBUTES => (['a', 'href'], ['img', 'src']);
117  
118 # Elements whose content is significant white space or code, which the
119 # white-space squasher must never touch
120 37 Readonly::Scalar my $VERBATIM_OPEN => qr{<(pre|textarea|script|style)\b[^<>]*+>}i;
121  
122 # Server preference order for content codings
123 37 Readonly::Array my @DEFAULT_ENCODINGS => qw(br zstd gzip);
124  
125 # Media types worth compressing
126 37 Readonly::Array my @DEFAULT_COMPRESSIBLE_TYPES => (
127 qr{^text/},
128 qr{^application/(?:ecmascript|javascript|json|ld\+json|xhtml\+xml|xml)$},
129 qr{^image/svg\+xml$},
130 );
131  
132 # Types that must never be buffered and compressed, even though they
133 # match one of the rules above
134 37 Readonly::Array my @DEFAULT_EXCLUDED_TYPES => (qr{^text/event-stream$});
135  
136 # Every option and its default. register() shallow-copies the array
137 # references, because Readonly makes nested data read-only too.
138 37 Readonly::Hash my %DEFAULTS => (
139 compress_content => 1, # compress responses with gzip/br/zstd
140 optimise_content => 0, # 1 = squash HTML, 2 = also be aggressive with JavaScript
141 rewrite_links => 1, # make same-site absolute links relative
142 generate_etag => 1,
143 generate_304 => 1,
144 trust_last_modified => 0, # also answer If-Modified-Since when an ETag exists
145 last_modified => 1, # 0 = off, 1 = newest app/template mtime, epoch, date string or coderef
146 template_mtime_cache => undef, # cache object for the template mtime scan
147 template_mtime_cache_duration => $DEFAULT_MTIME_DURATION,
148 min_compress_size => $DEFAULT_MIN_COMPRESS_SIZE,
149 min_compress_saving => $DEFAULT_MIN_COMPRESS_SAVING,
150 encodings => [@DEFAULT_ENCODINGS],
151 compressible_types => [@DEFAULT_COMPRESSIBLE_TYPES],
152 excluded_types => [@DEFAULT_EXCLUDED_TYPES],
153 cache => undef, # a CHI-like cache object
154 cache_duration => $DEFAULT_CACHE_DURATION,
155 cache_key => undef, # string or coderef, overriding the generated key
156 cache_single_flight => 1, # let one request build a missing entry, others wait
157 cache_lock_timeout => $DEFAULT_LOCK_TIMEOUT, # seconds before waiters give up
158 cache_lock => undef, # pluggable lock backend object
159 cache_lock_dir => undef, # directory of shared lock files, for multiple workers
160 vary_by => ['cookie'], # request headers that become part of the cache key
161 messages => undef, # overrides for the message catalog
162 );
163  
164 # Params::Validate::Strict schema for each option. The keys of this hash
165 # are the complete list of options; anything else is rejected.
166 37 Readonly::Scalar my $FLAG => {type => 'scalar', optional => 1};
167 37 Readonly::Scalar my $DURATION => {type => 'string', min => 1, optional => 1};
168 Readonly::Hash my %OPTION_SCHEMA => (
169 compress_content => $FLAG,
170 optimise_content => {type => 'integer', min => 0, max => $OPTIMISE_AGGRESSIVE, optional => 1},
171 rewrite_links => $FLAG,
172 generate_etag => $FLAG,
173 generate_304 => $FLAG,
174 trust_last_modified => $FLAG,
175 last_modified => [{type => 'scalar'}, {type => 'coderef'}],
176 template_mtime_cache => {type => 'object', can => [qw(get set)], optional => 1},
177 template_mtime_cache_duration => $DURATION,
178 min_compress_size => {type => 'integer', min => 0},
179 min_compress_saving => {type => 'integer', min => 0},
180 encodings => {type => 'arrayref'},
181 compressible_types => {type => 'arrayref'},
182 excluded_types => {type => 'arrayref'},
183 cache => {type => 'object', can => [qw(get set remove)], optional => 1},
184 cache_duration => $DURATION,
185 cache_key => [{type => 'string'}, {type => 'coderef'}],
186 cache_single_flight => $FLAG,
187 cache_lock_timeout => {
188 type => 'number',
189 matches => qr/^\d+(?:\.\d+)?$/,
190 184 ▶ callback => sub { !defined($_[0]) || ($_[0] > 0) }, # undef means the default
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
not defined $_[0] or $_[0] > 0 2 182 184
191 optional => 1,
192 },
193 cache_lock => {type => 'object', can => [qw(acquire release)], optional => 1},
194 cache_lock_dir => {type => 'string', min => 1, optional => 1},
195 vary_by => {
196 type => 'arrayref',
197 20 ▶ callback => sub { !grep { !defined($_) || ref($_) || !length($_) } @{$_[0]} },
Subroutine __ANON__: called CC=3 SCAR=12.0
Condition50%3/6
!defined($_) || ref $_ || !length($_)
l!l&&r!l&&!r
0220
not defined $_ or ref $_
l!l&&r!l&&!r
0022
MC/DC33%1/3
!defined($_) || ref $_ || !length($_)
not defined $_ ref $_ !length($_)
Truth table50%2/4
not(A) or B || not(C)
A= not defined $_B= ref $_C= !length($_)
ABCresult
1XX1
01X1
0011
0000
198 },
199 37 messages => {type => 'hashref', optional => 1},
200 );
201  
202 # Options whose error message is shared; every other option has its own
203 # option_<name> message, falling back to option_invalid
204 37 Readonly::Hash my %OPTION_MESSAGE => map { $_ => 'option_flag' }
205 qw(compress_content rewrite_links generate_etag generate_304 trust_last_modified cache_single_flight);
206  
207 # Options that can be declared for a group of pages, either as a route
208 # default, which lands in the stash,
209 # $r->get('/about' => {trust_last_modified => 1} => sub {...});
210 # $r->under('/docs')->to(optimise_content => 1);
211 # or by the controller itself, which its namespace inherits:
212 # sub buffer_optimise_content { 1 }
213 37 Readonly::Array my @GROUP_OPTIONS => qw(compress_content optimise_content rewrite_links trust_last_modified);
214  
215 # Whether each optional module loads, remembered for the life of the process
216 37 my %AVAILABLE;
217  
218 =head1 NAME
219  
220 Mojolicious::Plugin::Buffer - Optimise, compress and validate Mojolicious responses
221  
222 =head1 VERSION
223  
224 Version 0.002.0
225  
226 =cut
227  
228 =head1 SYNOPSIS
229  
230 =head2 1. The smallest set-up
231  
232 One line gives every page compression, an C<ETag>, a C<Last-Modified>
233 header and C<304 Not Modified> answers:
234  
235 use Mojolicious::Lite;
236  
237 plugin 'Buffer';
238  
239 get '/' => sub {
240 my $c = shift;
241 $c->render(template => 'index');
242 };
243  
244 app->start;
245  
246 =head2 2. Smaller HTML
247  
248 Also remove extra white space from HTML pages. Install L<HTML::Packer> to
249 remove comments and shrink embedded CSS as well:
250  
251 plugin 'Buffer' => {optimise_content => 1};
252  
253 =head2 3. A server-side cache for slow pages
254  
255 Keep finished pages in a cache, so a slow action runs once and later
256 visitors get the stored copy. Call the helper I<first> in the action, but
257 I<after> any check that decides who may see the page:
258  
259 use CHI;
260  
261 plugin 'Buffer' => {cache => CHI->new(driver => 'File', root_dir => '/var/cache/myapp')};
262  
263 get '/report' => sub {
264 my $c = shift;
265  
266 # Access checks come first: a cached page is sent without them
267 return $c->reply->not_found unless $c->session('user');
268  
269 return if $c->buffer_is_cached; # sent from the cache: stop here
270  
271 $c->render(text => slow_report()); # only runs on a miss
272 };
273  
274 =head2 4. Several workers on one machine
275  
276 With L<hypnotoad> there are several worker processes. Share the cache
277 between them, and give them a lock directory, so only one worker builds a
278 missing page:
279  
280 plugin 'Buffer' => {
281 cache => CHI->new(driver => 'File', root_dir => '/var/cache/myapp'),
282 cache_lock_dir => '/var/lib/myapp/buffer-locks',
283 };
284  
285 For workers on several machines, see L</Multiple hosts>.
286  
287 =head2 5. One response is different
288  
289 Put a C<buffer> value in the stash. C<0> leaves the response alone; a hash
290 changes some options for this response only:
291  
292 get '/download' => sub {
293 my $c = shift;
294 $c->stash(buffer => 0); # already compressed: do not touch it
295 $c->render(data => $zip_file, format => 'zip');
296 };
297  
298 get '/raw' => sub {
299 my $c = shift;
300 $c->stash(buffer => {optimise_content => 0});
301 $c->render(template => 'raw');
302 };
303  
304 =head2 6. A whole section is different
305  
306 Some options can be set once for a group of routes:
307  
308 my $docs = app->routes->under('/docs')->to(optimise_content => 1);
309 $docs->get('/intro' => sub { shift->render(template => 'docs/intro') });
310  
311 =head2 7. Pages in several languages
312  
313 Add C<Accept-Language> to the cache key, so each language is stored
314 separately:
315  
316 plugin 'Buffer' => {
317 cache => $cache,
318 vary_by => ['cookie', 'accept-language'],
319 };
320  
321 =head2 8. Translate the "busy" message
322  
323 While one request builds a page, a request that waits too long gets
324 C<503 Service Unavailable> with a short text. Change the text with
325 C<messages>:
326  
327 plugin 'Buffer' => {
328 cache => $cache,
329 messages => {retry_later => "Bitte versuchen Sie es gleich noch einmal.\n"},
330 };
331  
332 =head2 9. A full application
333  
334 package MyApp;
335 use Mojo::Base 'Mojolicious';
336 use CHI;
337  
338 sub startup {
339 my $self = shift;
340  
341 $self->plugin('Buffer', {
342 optimise_content => 1,
343 cache => CHI->new(driver => 'File', root_dir => '/var/cache/myapp'),
344 cache_lock_dir => '/var/lib/myapp/buffer-locks',
345 cache_duration => '10 minutes',
346 vary_by => [], # these pages are the same for everyone
347 });
348  
349 $self->routes->get('/')->to('pages#home');
350 }
351  
352 1;
353  
354 =head1 DESCRIPTION
355  
356 C<Mojolicious::Plugin::Buffer> makes the pages of a L<Mojolicious>
357 application smaller and faster to deliver, without changes to your actions.
358 It is the Mojolicious version of L<CGI::Buffer> and L<FCGI::Buffer>.
359  
360 =head2 What it does
361  
362 After your action has made a page, and before the page is sent, the plugin
363 can:
364  
365 =over 4
366  
367 =item * B<make HTML smaller> by removing extra white space and, with
368 L<HTML::Packer>, comments and extra characters in embedded CSS and
369 JavaScript. It also shortens links to your own site;
370  
371 =item * B<compress the page> with Brotli, Zstandard or gzip, whichever the
372 browser accepts and the server has installed;
373  
374 =item * B<add headers that let browsers reuse a copy they already have>
375 (C<ETag> and C<Last-Modified>), and answer "you already have this" with a
376 short C<304 Not Modified> reply instead of the whole page;
377  
378 =item * B<set the correct C<Content-Length>> after all of these changes;
379  
380 =item * B<keep finished pages in a server-side cache>, if you ask it to, so
381 that a slow action does not have to run again for the next visitor (see
382 L</buffer_is_cached>).
383  
384 =back
385  
386 =head2 How it works, in plain words
387  
388 =over 4
389  
390 =item 1. When the application starts, L</register> checks your options and
391 installs a I<hook>: a small function that Mojolicious calls for every
392 response, after the action has finished (C<after_dispatch>).
393  
394 =item 2. A request arrives and your action runs. If the action calls
395 L</buffer_is_cached> and a fresh copy of the page is in the cache, the copy
396 is sent and the action stops early.
397  
398 =item 3. Otherwise the action makes the page as usual.
399  
400 =item 4. The hook looks at the finished response. It leaves alone anything
401 it should not touch: streamed responses, static files, empty bodies,
402 statuses that have no body (1xx, 204, 206, 304), responses that are already
403 compressed, and media types listed in L</excluded_types>.
404  
405 =item 5. For an HTML page it removes white space, if L</optimise_content>
406 is on.
407  
408 =item 6. It compresses the page for this browser, if the media type is in
409 L</compressible_types>.
410  
411 =item 7. It stores the I<uncompressed> page in the cache, if the action
412 called L</buffer_is_cached> and the page may be stored.
413  
414 =item 8. It adds the C<ETag> and C<Last-Modified> headers. If the browser
415 already has this version, it sends C<304 Not Modified> with no body and
416 stops.
417  
418 =item 9. Otherwise it puts the compressed (or plain) page into the
419 response, sets C<Content-Length>, and the page is sent.
420  
421 =back
422  
423 Error pages such as C<404> go through the same steps, but only C<200>
424 responses get an C<ETag> or are stored in the cache.
425  
426 The plugin works through a hook, so it also sees responses built with
427 C<< $c->res->body >> rather than C<< $c->render >>. Unlike the CGI modules
428 it needs no source filter and no C<END> block.
429  
430 =head2 Words used in this document
431  
432 =over 4
433  
434 =item cache
435  
436 A store that keeps finished pages for a while, for example L<CHI>. The
437 plugin needs an object with C<get>, C<set> and C<remove> methods.
438  
439 =item cache key
440  
441 The name under which a page is kept in the cache. By default it is made
442 from the host, path, query string and the request headers listed in
443 L</vary_by>.
444  
445 =item ETag
446  
447 A short fingerprint of the page, sent in a header. A browser that has a
448 copy sends the fingerprint back; if it still matches, the server answers
449 C<304>.
450  
451 =item 304 Not Modified
452  
453 A reply with no body that means "the copy you have is still correct".
454  
455 =item content coding
456  
457 The compression method of a response, such as C<gzip> or C<br> (Brotli).
458 The browser lists what it accepts in C<Accept-Encoding>.
459  
460 =item worker
461  
462 One of several copies of the application that a server such as
463 L<hypnotoad> runs at the same time. Workers do not share memory.
464  
465 =item single-flight
466  
467 When many requests ask for the same missing page at once, only one of them
468 builds it; the others wait and then get the result.
469  
470 =item stash
471  
472 Mojolicious's per-request hash of values, C<< $c->stash >>. The plugin
473 reads its per-response options from C<< $c->stash('buffer') >>.
474  
475 =back
476  
477 =head1 OPTIONS
478  
479 All options can be given to C<plugin()> and, except where noted, overridden
480 per request through the C<buffer> stash value. Options given to C<plugin()>
481 are validated when the plugin is registered; values in the C<buffer> stash
482 are not, and an unusable one falls back to its default where that is safe.
483 A few options describe a section of a site rather than one page and can be
484 declared once for it; see L</Declaring options for a group of pages>.
485  
486 =head2 Declaring options for a group of pages
487  
488 # one route
489 $r->get('/about' => {optimise_content => 1} => sub {...});
490  
491 # everything beneath an under route
492 my $docs = $r->under('/docs')->to(optimise_content => 1);
493 $docs->get('/intro' => sub {...});
494  
495 # a controller, and through a base class its whole namespace
496 package MyApp::Controller::Docs;
497 use Mojo::Base 'Mojolicious::Controller';
498 has buffer_optimise_content => 1;
499  
500 A route default is an ordinary stash value, so C<< $app->defaults(...) >> and
501 a C<before_action> that sets one work as well. The controller form is a
502 method named C<buffer_> followed by the option name, and is only consulted
503 when the stash says nothing: C<has> is the declarative way to write it, and a
504 plain C<sub buffer_optimise_content { 1 }> covers a value that depends on the
505 request. A controller method that dies is logged at debug level and
506 ignored, so the plugin option stays in force.
507  
508 The most specific declaration wins:
509  
510 =over 4
511  
512 =item 1. the C<buffer> stash, for a single response
513  
514 =item 2. a route default, which includes one an C<under> route sets
515  
516 =item 3. the controller declaration
517  
518 =item 4. the plugin option
519  
520 =back
521  
522 A route default of C<0> therefore opts one page back out of a group that has
523 the option on, and the C<buffer> stash overrides both.
524  
525 Only the options that describe the content of a section are declarable:
526  
527 =over 4
528  
529 =item L</compress_content> - a section serving files that are already
530 compressed
531  
532 =item L</optimise_content> - a static section that is always minified
533  
534 =item L</rewrite_links> - a section whose HTML is used elsewhere, so its
535 absolute links must survive
536  
537 =item L</trust_last_modified> - a section that renders templates and nothing
538 else
539  
540 =back
541  
542 Everything else, including L</generate_etag> and L</generate_304>, stays a
543 per-response or per-application decision; those sections say why. Any option
544 can still be set for one response through the C<buffer> stash.
545  
546 F<examples/grouped-sections> is a runnable site with one section declared on
547 an C<under> route and one declared in a controller.
548  
549 =head2 compress_content
550  
551 Compress eligible responses, defaults to 1. Set to 0 to only optimise (and
552 remember that the plugin turns off L<Mojolicious::Renderer/compress>, so a
553 response will then not be compressed at all). The encodings offered to
554 clients are controlled by L</encodings>.
555  
556 It can be declared for a group of pages (see
557 L</Declaring options for a group of pages>), which is the point of a section
558 that serves files it has already compressed.
559  
560 =head2 optimise_content
561  
562 How hard to optimise HTML, defaults to 0 (off). Registration rejects any
563 value other than 0, 1 or 2:
564  
565 =over 4
566  
567 =item 0 - leave the HTML alone
568  
569 =item 1 - remove superfluous white space, rewrite same-site links and, when
570 L<HTML::Packer> is installed, remove comments and minify embedded CSS
571  
572 =item 2 - as 1, plus aggressive JavaScript minification when L<HTML::Packer>
573 is installed, which can break scripts that rely on the
574 C<E<lt>!-- ... --E<gt>> hiding technique
575  
576 =back
577  
578 Optimisation only applies to C<text/html> and C<application/xhtml+xml>
579 responses. The content of C<E<lt>preE<gt>>, C<E<lt>textareaE<gt>>,
580 C<E<lt>scriptE<gt>> and C<E<lt>styleE<gt>> elements is never touched by the
581 white-space squashing, because white space there is significant. A
582 space between two inline elements, as in C<Hello E<lt>bE<gt>worldE<lt>/bE<gt>>,
583 is kept. At level 2, consecutive C<document.write> calls are merged only
584 inside one C<E<lt>script type="text/javascript"E<gt>> element, so scripts
585 of other types, such as templates, are left alone.
586 L<HTML::Packer> is optional: without it the white-space squashing and link
587 rewriting still run, but comments and embedded CSS and JavaScript are left
588 alone, as they are by L<CGI::Buffer> and L<FCGI::Buffer>. Install
589 L<HTML::Packer> for the full effect.
590  
591 It can be declared for a group of pages (see
592 L</Declaring options for a group of pages>), for a static section that is
593 always minified.
594  
595 =head2 rewrite_links
596  
597 When optimising, rewrite C<E<lt>a hrefE<gt>> and C<E<lt>img srcE<gt>> links that
598 point at the current site as absolute URLs into root-relative links, and
599 links to the current script with a query string into just the query string.
600 Defaults to 1. Has no effect unless L</optimise_content> is enabled. Only
601 double-quoted attribute values are recognised.
602  
603 It can be declared for a group of pages (see
604 L</Declaring options for a group of pages>), which matters for a section
605 whose HTML is not used in place: a preview of a newsletter or a page rendered
606 for another site needs its absolute URLs kept while still being optimised
607 elsewhere.
608  
609 =head2 generate_etag
610  
611 Add an C<ETag> header to C<200> responses to C<GET> and C<HEAD> requests,
612 defaults to 1. The tag is the MD5 of the response body before compression,
613 with a suffix for the content coding, so a gzip and an identity
614 representation of the same page have different tags. An C<ETag> set by the
615 action is kept.
616  
617 It is not declarable for a group of pages (see
618 L</Declaring options for a group of pages>): whether a digest is worth
619 computing is a decision for one endpoint, not a policy for a section. Skip
620 the digest for one response with C<< $c->stash(buffer => {generate_etag => 0})
621 >>, or for the whole application with the plugin option.
622  
623 =head2 generate_304
624  
625 Answer "you already have this page" with C<304 Not Modified>, defaults to
626 1. A browser that has a copy of a page asks the server whether its copy is
627 still correct. It can ask in two ways:
628  
629 =over 4
630  
631 =item * C<If-None-Match>: "my copy has this C<ETag>". This is exact,
632 because the C<ETag> is a fingerprint of the page itself.
633  
634 =item * C<If-Modified-Since>: "my copy is from this date". This is only a
635 guess, because the date (see L</last_modified>) describes your I<code and
636 templates>, not the data shown on the page.
637  
638 =back
639  
640 The plugin uses them like this:
641  
642 =over 4
643  
644 =item 1. If the request has C<If-None-Match>, only the C<ETag> decides. The
645 date is ignored, as RFC 7232 requires.
646  
647 =item 2. If the page has an C<ETag> (L</generate_etag> is on, the default),
648 C<If-Modified-Since> alone is I<not> trusted. A database row can change
649 while the template stays the same, and a C<304> would then keep showing the
650 browser old data. Browsers send C<If-None-Match> once they have seen an
651 C<ETag>, so they are not affected.
652  
653 =item 3. If the page has no C<ETag>, or L</trust_last_modified> is on, the
654 date is used.
655  
656 =back
657  
658 It is not declarable for a group of pages (see
659 L</Declaring options for a group of pages>). It decides whether a browser is
660 told that its copy is correct, and a section that could also turn it off
661 would contradict L</trust_last_modified>. Use
662 C<< $c->stash(buffer => {generate_304 => 0}) >> where one endpoint must always
663 send a body.
664  
665 =head2 last_modified
666  
667 Add a C<Last-Modified> header, defaults to 1. The header says when the page
668 last changed. The value may be:
669  
670 =over 4
671  
672 =item 0 - do not add the header
673  
674 =item 1 - the newest modification time of the application script (C<$0>)
675 and of every file and directory under the renderer's template paths.
676 Symbolic links are followed, each directory is read once, and the scan
677 stops 32 directories below a template path, which also ends a symbolic
678 link that points back up the tree.
679  
680 =item a number - a Unix epoch (seconds since 1970)
681  
682 =item a date string - anything L<Mojo::Date> can read, such as
683 C<'Sun, 06 Nov 1994 08:49:37 GMT'>
684  
685 =item a code reference - called with the controller; it returns one of the
686 values above (a code reference that returns another code reference counts
687 as 0)
688  
689 =back
690  
691 Some rules:
692  
693 =over 4
694  
695 =item * The header is only added to C<200> responses to C<GET> and C<HEAD>.
696 A C<Last-Modified> header that the action set itself is kept.
697  
698 =item * With the default (1), editing a template changes the date.
699 (Separately, and whatever this option says, the server-side cache throws
700 away entries built before the newest change to the script or a template;
701 see L</buffer_is_cached>.)
702  
703 =item * The date describes the I<code>, not your data. A change in the
704 database does not move it. For pages built from data, use a code reference
705 that returns the data's own date, or set C<last_modified =E<gt> 0> and rely
706 on the C<ETag> (see L</generate_304> for why that is safe).
707  
708 =item * The default looks at every template file on every request, unless
709 L</template_mtime_cache> is set. For a large template tree, or an
710 application without templates, an epoch or a code reference is cheaper.
711 A server-side cache lookup also looks at the template files, whatever this
712 option says; see L</Last-Modified performance>.
713  
714 =item * C<morbo> and C<hypnotoad> set C<$0> to your application script.
715 Under PSGI or another wrapper, C<$0> may be the wrapper instead; pass an
716 epoch or a code reference there.
717  
718 =back
719  
720 =head2 trust_last_modified
721  
722 Also answer C<If-Modified-Since> when the page has an C<ETag>, defaults to 0.
723  
724 By default the plugin does not trust the date when it has a fingerprint
725 (see L</generate_304>). Turn this on only for pages that are built from the
726 application and its templates I<and nothing else>: no database, no session,
727 no other input that can change while the templates stay the same. Then the
728 date is accurate, and clients that only send C<If-Modified-Since> can get a
729 C<304> too. C<If-None-Match> still comes first, so a browser that sends the
730 C<ETag> is always answered correctly.
731  
732 plugin 'Buffer' => {
733 trust_last_modified => 1, # this application only renders templates
734 };
735  
736 Use it for one response with
737 C<< $c->stash(buffer => {trust_last_modified => 1}) >>, or declare it for a
738 group of pages (see L</Declaring options for a group of pages>), for a
739 section that renders templates and nothing else. It has no effect when
740 L</generate_304> is off. It cannot make a page safe; it only tells the
741 plugin that the templates really are the only input.
742  
743 =head2 Last-Modified performance
744  
745 The scan costs one C<stat()> per file and directory under the renderer's
746 paths. On a tree of 10,000 templates in 100 directories, a request using the
747 default scan took about 40 milliseconds of CPU on the machine used for these
748 measurements, against about 1 millisecond for the same request with an
749 explicit epoch; that is roughly 4 microseconds per tree entry. With
750 L</template_mtime_cache> in front of it, the same request also took about 1
751 millisecond, the cache lookup adding only a few tens of microseconds, so the
752 middle ground gives up roughly 2% of the scan's cost to keep template
753 awareness. The numbers are indicative, not a promise, and a faster or slower
754 filesystem will move them. Run F<benchmarks/last_modified.pl> with your own
755 tree size to measure all three variants.
756  
757 Use an explicit epoch or a coderef when template changes do not need to move
758 C<Last-Modified>. This removes the scan from ordinary responses, but not
759 from server-side cache lookups: L</buffer_is_cached> still scans, so that an
760 entry built from an old template is thrown away. Use
761 L</template_mtime_cache> when you need template awareness but not a scan on
762 every request: it costs one cache lookup per request, covers both uses, and
763 bounds how long a template edit can be missed by its duration.
764  
765 =head2 template_mtime_cache
766  
767 An optional cache object understanding C<get()> and C<set()>, such as a
768 L<CHI> instance, used to remember the result of the template mtime scan.
769 Defaults to undef, which scans the renderer's template paths on every
770 request. A per-worker cache avoids the scan without sharing anything:
771  
772 use CHI;
773 plugin 'Buffer' => {
774 template_mtime_cache => CHI->new(driver => 'Memory', datastore => {}),
775 };
776  
777 A shared cache, such as CHI's File or Memcached driver, also avoids the scan
778 for every worker. Entries are keyed by the application class, the
779 application script and its mtime, and the renderer's template paths, and are
780 stored with L</template_mtime_cache_duration>. A cache failure is logged at
781 debug level and the scan runs as usual, so a broken cache cannot stop a
782 response.
783  
784 For a large tree this is the middle ground: it avoids the per-request scan
785 described under L</Last-Modified performance> while still noticing template
786 changes, at the cost of up to one duration of staleness.
787  
788 The cached value is only refreshed when the entry expires. A template edit
789 therefore is not noticed until then, and neither C<Last-Modified> nor the
790 cache invalidation described under L</last_modified> sees it immediately.
791 Keep L</template_mtime_cache_duration> short if templates change often.
792  
793 This option and L</template_mtime_cache_duration> are read when the plugin is
794 registered; they cannot be overridden through the C<buffer> stash.
795  
796 =head2 template_mtime_cache_duration
797  
798 How long a template mtime is kept, defaults to 10 seconds. It is passed to
799 the cache's C<set()>, so for L<CHI> it may be a number of seconds or a
800 human-readable duration.
801  
802 =head2 min_compress_size
803  
804 Do not compress bodies smaller than this many bytes, defaults to 64. Must be
805 a non-negative integer. See also L</min_compress_saving>.
806  
807 =head2 min_compress_saving
808  
809 Do not compress a body if compression would save fewer than this many
810 bytes, defaults to 16. Must be a non-negative integer. A small saving is
811 not worth the C<Content-Encoding> header and the client's work to decode
812 the body. Compression is always skipped if it would not make the body
813 smaller, even when this is 0.
814  
815 =head2 encodings
816  
817 An arrayref of the content codings to offer, in server preference order.
818 Defaults to C<[qw(br zstd gzip)]>. C<br> is only offered if
819 L<IO::Compress::Brotli> is installed and C<zstd> only if L<Compress::Zstd>
820 is installed; gzip is always available. C<x-gzip> is accepted as a synonym
821 for C<gzip>. Clients pick with the usual quality values, and C<identity> is
822 used when nothing acceptable is offered.
823  
824 =head2 compressible_types
825  
826 An arrayref of media types to compress, defaults to C<text/*>,
827 C<application/json>, C<application/javascript>, C<application/xml>,
828 C<application/xhtml+xml>, C<image/svg+xml> and a few close relatives.
829 Entries may be strings (matched exactly, case-insensitively) or regular
830 expressions.
831  
832 =head2 excluded_types
833  
834 An arrayref of media types that are never buffered, defaults to
835 C<text/event-stream>. Entries may be strings or regular expressions.
836  
837 =head2 cache
838  
839 An optional cache object understanding C<get()>, C<set()> and C<remove()>,
840 such as a L<CHI> instance. Defaults to undef, which disables the
841 server-side cache. See L</buffer_is_cached> for the rules about what is
842 cached and how keys are made.
843  
844 =head2 cache_duration
845  
846 How long entries are kept in the cache, defaults to C<'10 minutes'>. It is
847 passed to the cache's C<set()>, so for L<CHI> it may be a number of seconds
848 or a human-readable duration.
849  
850 =head2 cache_key
851  
852 A string, or a coderef called with the controller, that overrides the
853 generated cache key. Useful when several URLs should share one entry, or
854 when the response depends on something the default key does not cover. An
855 empty string, or a coderef returning nothing, falls back to the generated
856 key.
857  
858 =head2 cache_single_flight
859  
860 Only let one request at a time build a missing entry, defaults to 1. When a
861 request misses the cache while another request in the same worker is already
862 building the same key, the second request waits for the first one to finish
863 and is then served the finished entry, without running the action. This
864 matters for asynchronous actions: a synchronous action runs to completion
865 without the event loop doing anything else, so it cannot overlap with
866 another request in the same worker.
867  
868 If the first request fails, produces a response that cannot be cached (for
869 example one that sets a cookie), or takes longer than L</cache_lock_timeout>,
870 the waiting request is answered with C<503 Service Unavailable> and
871 C<Retry-After: 1> rather than running the action itself. Set to 0 to let
872 every concurrent miss run the action independently.
873  
874 By default the in-flight table is per worker process, so with N L<hypnotoad>
875 workers a cold entry can still be built up to N times. Set L</cache_lock> or
876 L</cache_lock_dir> to elect a single builder across processes instead.
877  
878 =head2 cache_lock
879  
880 An optional object that elects one process to build a missing entry, for
881 workers that cannot share a directory. It must implement:
882  
883 =over 4
884  
885 =item acquire
886  
887 my ($guard, $error) = $lock->acquire($key);
888  
889 Return a truthy guard if the lock was acquired, C<(undef, undef)> if another
890 process holds it, and C<(undef, $error)> if the backend failed. On an error
891 the plugin logs the message and continues with a per-worker flight, so a
892 cache miss is still built. An exception thrown by C<acquire> is treated as
893 an error.
894  
895 The call is synchronous and runs before the action is allowed to continue.
896 A backend must therefore be quick and must not depend on the event loop; an
897 asynchronous Redis client is not suitable.
898  
899 =item release
900  
901 $lock->release($guard);
902  
903 Release a guard returned by C<acquire>. The guard is opaque to the plugin.
904 Releasing a lock that has already expired is allowed. If release fails, the
905 lock should expire on its own; the backend can return C<(0, $error)> so the
906 failure is logged. A backend that returns nothing is treated as having
907 released the lock.
908  
909 =back
910  
911 The cache itself must still be shared between the workers. The built-in
912 backends are L<Mojolicious::Plugin::Buffer::Lock::File>, selected with
913 L</cache_lock_dir>, and L<Mojolicious::Plugin::Buffer::Lock::Redis>.
914 C<cache_lock> cannot be combined with L</cache_lock_dir>, and is read when
915 the plugin is registered rather than per response.
916  
917 =head2 cache_lock_timeout
918  
919 How long a request may wait for another request, in this worker or another
920 one, to build the same entry. Defaults to 10 seconds. It also bounds how
921 long a key is considered to be in flight when the request building it never
922 finishes. Fractional seconds are allowed, so C<0.5> is valid; zero and
923 negative values are rejected.
924  
925 =head2 cache_lock_dir
926  
927 A directory in which to keep lock files used to coalesce cache misses across
928 worker processes, defaults to undef, which limits single-flight to one worker.
929 This selects the built-in L<Mojolicious::Plugin::Buffer::Lock::File> backend
930 and is a shorthand for C<cache_lock =E<gt>
931 Mojolicious::Plugin::Buffer::Lock::File-E<gt>new(dir =E<gt> $dir)>. The
932 plugin creates the directory if necessary. It cannot be combined with
933 L</cache_lock>.
934  
935 The workers must share this directory and the cache itself. A per-worker
936 cache such as CHI's C<Memory> driver cannot be used, because a request in one
937 worker cannot see the entry built in another; disable any per-worker C<L1>
938 cache in front of a shared cache for the same reason. Locks are non-blocking
939 C<flock>s on one small, empty file per cache key, so they are released
940 automatically if a worker dies. The files are not removed, although they are
941 tiny and can be deleted while the application is stopped. Use a private
942 directory.
943  
944 This works for L<hypnotoad> workers on the same host, or on a shared
945 filesystem that implements C<flock> reliably. For workers on different
946 hosts, use L</cache_lock> with
947 L<Mojolicious::Plugin::Buffer::Lock::Redis> instead. It is read when the
948 plugin is registered, not per response.
949  
950 =head2 vary_by
951  
952 An arrayref of request header names that become part of the generated cache
953 key. Defaults to C<['cookie']>, which keeps one client's session from being
954 served to another. Set it to C<[]> for URL-only caching of pages that are
955 identical for every visitor, or add e.g. C<'accept-language'> when the
956 response varies by language. Header names are case-insensitive. Headers
957 listed here may also appear in the response's C<Vary> header; a response
958 that varies on anything else is not stored.
959  
960 =head2 messages
961  
962 A hash reference of message overrides, keyed by message key, used for every
963 error, log line and client-facing text the plugin produces, including the
964 body of the C<503> sent to a request that gave up waiting. See
965 L<Mojolicious::Plugin::Buffer::I18N> for the keys, the placeholder syntax
966 and plural and gender variants:
967  
968 plugin 'Buffer' => {
969 messages => {
970 retry_later => "Die Seite wird gerade erstellt, bitte versuchen Sie es gleich noch einmal.\n",
971 },
972 };
973  
974 It is passed to the lock backend built from L</cache_lock_dir>. It is read
975 when the plugin is registered, not per response.
976  
977 =head1 METHODS
978  
979 C<Mojolicious::Plugin::Buffer> inherits all methods from
980 L<Mojolicious::Plugin> and implements the following new ones. It also adds
981 the L</buffer_is_cached> helper to the application.
982  
983 =head2 register
984  
985 $plugin->register(Mojolicious->new, {optimise_content => 1});
986  
987 =head3 Purpose
988  
989 Validate the options, install the C<after_dispatch> hook that reworks every
990 response, and add the L</buffer_is_cached> helper. It is normally called for
991 you by C<< $app->plugin('Buffer', ...) >>.
992  
993 =head3 Arguments
994  
995 =over 4
996  
997 =item C<$app> (positional, required)
998  
999 The L<Mojolicious> application.
1000  
1001 =item C<\%options> (positional, optional)
1002  
1003 The options described under L</OPTIONS>, as a hash reference or a flat list.
1004  
1005 =back
1006  
1007 =head3 Returns
1008  
1009 The plugin object, so calls can be chained.
1010  
1011 =head3 Side effects
1012  
1013 =over 4
1014  
1015 =item * Turns off L<Mojolicious::Renderer/compress>, because this plugin does
1016 the compression; see L</Interaction with the renderer>.
1017  
1018 =item * Adds an C<after_dispatch> hook and a C<buffer_is_cached> helper.
1019  
1020 =item * Creates L</cache_lock_dir> if it is given and missing.
1021  
1022 =item * Loads the optional compression modules named by L</encodings>, and
1023 logs at debug level when L</optimise_content> is on without L<HTML::Packer>.
1024  
1025 =back
1026  
1027 =head3 Example
1028  
1029 use Mojolicious::Lite;
1030 use CHI;
1031  
1032 plugin 'Buffer' => {
1033 optimise_content => 1,
1034 cache => CHI->new(driver => 'File', root_dir => '/var/cache/myapp'),
1035 cache_lock_dir => '/var/lib/myapp/buffer-locks',
1036 vary_by => [], # pages are the same for everyone
1037 };
1038  
1039 get '/' => sub {
1040 my $c = shift;
1041 return if $c->buffer_is_cached;
1042 $c->render(text => 'Hello');
1043 };
1044  
1045 app->start;
1046  
1047 =head3 API SPECIFICATION
1048  
1049 =head4 Input
1050  
1051 # Params::Get::get_params(undef, @_) after $app, then one
1052 # Params::Validate::Strict::validate_strict call per option
1053 {
1054 app => { type => 'object', can => [qw(hook helper renderer log)] },
1055 compress_content => { type => 'scalar', optional => 1 },
1056 optimise_content => { type => 'integer', min => 0, max => 2, optional => 1 },
1057 rewrite_links => { type => 'scalar', optional => 1 },
1058 generate_etag => { type => 'scalar', optional => 1 },
1059 generate_304 => { type => 'scalar', optional => 1 },
1060 trust_last_modified => { type => 'scalar', optional => 1 },
1061 last_modified => [ { type => 'scalar' }, { type => 'coderef' } ],
1062 template_mtime_cache => { type => 'object', can => [qw(get set)], optional => 1 },
1063 template_mtime_cache_duration => { type => 'string', min => 1, optional => 1 },
1064 min_compress_size => { type => 'integer', min => 0 },
1065 min_compress_saving => { type => 'integer', min => 0 },
1066 encodings => { type => 'arrayref' }, # of br|zstd|gzip|x-gzip
1067 compressible_types => { type => 'arrayref' }, # of strings or qr//
1068 excluded_types => { type => 'arrayref' }, # of strings or qr//
1069 cache => { type => 'object', can => [qw(get set remove)], optional => 1 },
1070 cache_duration => { type => 'string', min => 1, optional => 1 },
1071 cache_key => [ { type => 'string' }, { type => 'coderef' } ],
1072 cache_single_flight => { type => 'scalar', optional => 1 },
1073 cache_lock_timeout => { type => 'number', optional => 1 }, # > 0
1074 cache_lock => { type => 'object', can => [qw(acquire release)], optional => 1 },
1075 cache_lock_dir => { type => 'string', min => 1, optional => 1 },
1076 vary_by => { type => 'arrayref' }, # of non-empty strings
1077 messages => { type => 'hashref', optional => 1 },
1078 }
1079  
1080 =head4 Output
1081  
1082 # Return::Set schema
1083 { type => 'object', isa => 'Mojolicious::Plugin::Buffer' }
1084  
1085 =head3 MESSAGES
1086  
1087 Every message croaks, from the caller's point of view. The key is the
1088 L<Mojolicious::Plugin::Buffer::I18N> key that can be overridden.
1089  
1090 When several options are wrong, only one is reported: the first one when
1091 the option names are sorted in ASCII order (for example C<cache> comes
1092 before C<encodings>, and C<generate_304> before C<generate_etag>). An
1093 unknown option name is reported in the same way, at its place in that
1094 order. Fix it and register again to see the next problem. The order is
1095 fixed, so the same mistake always gives the same message. The checks
1096 that look at more than one option (C<cache_lock> together with
1097 C<cache_lock_dir>, and unknown C<encodings> names) come after all of
1098 these.
1099  
1100 Key Message (after "Mojolicious::Plugin::Buffer: ") Resolution
1101 ------------------------------ -------------------------------------------------- ---------------------------------
1102 options_not_hash options must be a hash reference Pass {...} or a key/value list
1103 unknown_option unknown option 'NAME' Check the spelling in OPTIONS
1104 option_flag NAME must be a true or false value Pass 0 or 1, not a reference
1105 option_optimise_content optimise_content must be 0, 1 or 2 Use one of the documented levels
1106 option_last_modified last_modified must be 0, 1, an epoch, a date Pass a scalar or a coderef
1107 string or a code reference
1108 option_min_compress_size min_compress_size must be a non-negative integer Pass e.g. 64
1109 option_min_compress_saving min_compress_saving must be a non-negative integer Pass e.g. 16
1110 option_encodings encodings must be an array reference Pass [qw(br gzip)]
1111 unknown_encoding unknown encoding 'NAME' Use br, zstd, gzip or x-gzip
1112 option_compressible_types compressible_types must be an array reference Pass [qr{^text/}, ...]
1113 option_excluded_types excluded_types must be an array reference Pass [qr{^text/event-stream$}]
1114 option_vary_by vary_by must be an array reference of header names Pass e.g. ['cookie']
1115 option_cache_key cache_key must be a string or a code reference Pass a string or sub
1116 option_cache cache must be an object understanding get(), set() Pass a CHI object
1117 and remove()
1118 option_cache_duration cache_duration must be a duration Pass e.g. '10 minutes'
1119 option_template_mtime_cache template_mtime_cache must be an object Pass a CHI object
1120 understanding get() and set()
1121 option_template_mtime_cache_duration
1122 template_mtime_cache_duration must be a duration Pass e.g. 10
1123 option_cache_lock_timeout cache_lock_timeout must be a positive number of Pass e.g. 10 or 0.5
1124 seconds
1125 option_cache_lock cache_lock must be an object with acquire() and See cache_lock
1126 release() methods
1127 option_cache_lock_dir cache_lock_dir must be a directory path Pass a non-empty string
1128 lock_options_combined cache_lock and cache_lock_dir cannot be combined Use one of the two
1129 option_messages messages must be a hash reference Pass {key => 'text'}
1130 lock_dir_create_failed cannot create cache_lock_dir 'DIR': OS ERROR See Lock::File
1131 lock_dir_not_writable cache_lock_dir 'DIR' is not a writable directory See Lock::File
1132  
1133 A failure to validate C<$app> itself is reported by L<Params::Validate::Strict>
1134 and is not translated.
1135  
1136 =head3 PSEUDOCODE
1137  
1138 accept the options as a hash reference or a key/value list
1139 check the application object
1140 adopt the messages option first, so later errors can be reworded
1141 start from the defaults
1142 for each option given, in sorted order:
1143 croak if it is unknown
1144 croak with its own message if its value does not fit its schema
1145 croak if both cache_lock and cache_lock_dir were given
1146 build the lock backend: the given object, or a file backend for the dir
1147 canonicalise encodings, croak on unknown ones, drop unavailable ones
1148 log once if optimisation is on without HTML::Packer
1149 turn off the renderer's own compression
1150 hook after_dispatch to rework every response
1151 add the buffer_is_cached helper
1152 return the plugin
1153  
1154 =cut
1155  
1156 333 ▶sub register {
Subroutine register: called CC=9 SCAR=22.0
Pod documented
1157 333 my ($self, $app, @conf) = @_;
1158  
1159 # Mojolicious passes a hash reference; Params::Get also accepts a list
1160 333 ▶ my $conf = @conf ? eval { get_params(undef, @conf) } : {};
Branch: 1 branch
BranchTrueFalseTotal
@conf ? : 333 0 333
1161 333 ▶ croak $self->i18n('options_not_hash') unless ref($conf) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conf eq "HASH" 0 333 333
1162 333 validate_strict(
1163 schema => {app => {type => 'object', can => [qw(hook helper renderer log)]}},
1164 input => {app => $app},
1165 );
1166  
1167 # Messages first, so every later error can already be reworded
1168 333 ▶ $self->{messages} = $conf->{messages} if ref($conf->{messages}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $conf->{"messages"} eq "HASH" 4 329 333
1169  
1170 # Sorted, so the same bad configuration always reports the same error
1171 333 my %options = map { $_ => _copy_default($DEFAULTS{$_}) } keys %DEFAULTS;
1172 333 for my $name (sort keys %$conf) {
1173 436 ▶ croak $self->i18n('unknown_option', {option => $name}) unless exists($OPTION_SCHEMA{$name});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $OPTION_SCHEMA{$name} 4 432 436
1174 432 ▶ croak $self->i18n(_option_message($name), {option => $name}) unless _option_valid($name, $conf->{$name});
Branch: 1 branch
BranchTrueFalseTotal
unless _option_valid($name, $conf->{$name}) 80 352 432
1175 352 $options{$name} = $conf->{$name};
1176 }
1177  
1178 249 $self->{options} = \%options;
1179 249 $self->{inflight} = {};
1180 249 $self->{lock} = $self->_build_lock(\%options);
1181 239 $options{encodings} = $self->_supported_encodings($options{encodings});
1182  
1183 # HTML::Packer is optional: without it the white-space squashing and link
1184 # rewriting still run, as they do in CGI::Buffer and FCGI::Buffer
1185 $self->_log($app, debug => 'log_no_packer')
1186 237 ▶ if $options{optimise_content} && !_module_available('HTML::Packer');
Branch: 1 branch
BranchTrueFalseTotal
if $options{"optimise_content"} and not _module_available("HTML::Packer") 15 222 237
Condition100%3/3
$options{"optimise_content"} and not _module_available("HTML::Packer")
!ll&&!rl&&r
2061615
MC/DC100%2/2
$options{"optimise_content"} and not _module_available("HTML::Packer")
$options{"optimise_content"} not _module_available("HTML::Packer")
Truth table100%3/3
A and not(B)
A= $options{"optimise_content"}B= not _module_available("HTML::Packer")
ABresult
0X0
100
111
1187  
1188 # Mojolicious::Renderer gzips rendered output by default, before this
1189 # plugin ever sees it, which would stop optimisation and ETag generation
1190 # from working on anything bigger than 860 bytes. Take over that job.
1191 237 $app->renderer->compress(0);
1192  
1193 237 ▶ $app->hook(after_dispatch => sub { $self->_process(shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1194  
1195 # Opt-in server-side page cache, used from an action like this:
1196 # return if $c->buffer_is_cached;
1197 237 ▶ $app->helper(buffer_is_cached => sub { $self->_is_cached(shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1198  
1199 237 return set_return($self, {type => 'object'});
1200 }
1201  
1202 =head2 buffer_is_cached
1203  
1204 get '/expensive' => sub {
1205 my $c = shift;
1206 return if $c->buffer_is_cached;
1207 # ... expensive work ...
1208 $c->render(template => 'expensive');
1209 };
1210  
1211 =head3 Purpose
1212  
1213 A helper, added to the application by L</register>, that lets an action skip
1214 its work when a finished copy of the page is already cached, or when another
1215 request is already building it.
1216  
1217 Look for a cached response and, if there is one, replay its status, headers
1218 and body, add C<X-Cache: HIT>, finish the response and return true. The
1219 action only has to return; no rendering is needed on a hit. On a miss it
1220 adds C<X-Cache: MISS>, returns false, and the response is stored when it is
1221 complete.
1222  
1223 Only C<200> responses to C<GET> and C<HEAD> requests are cached. Requests
1224 with an C<Authorization> header or a C<Cache-Control> header containing
1225 C<no-store>, C<no-cache>, C<private> or C<max-age=0> bypass the cache, as do
1226 requests made while the C<NO_CACHE> or C<NO_STORE> environment variable is
1227 set. Responses that set a cookie, that are marked C<no-store>,
1228 C<no-cache> or C<private>, or that vary on something not listed in L</vary_by>, are not
1229 stored. Entries created before the application script or any template file
1230 or directory was last modified are treated as misses and removed.
1231  
1232 The stored body is the optimised but uncompressed entity, so every hit is
1233 compressed for the requesting client, gets its own C<ETag> and can still be
1234 answered with C<304 Not Modified>. The cache key is a digest of the
1235 application class, host, path, query string and the values of the headers
1236 listed in L</vary_by>; use L</cache_key> to replace it. Query argument order
1237 is significant.
1238  
1239 Concurrent misses for the same key are coalesced within a worker, or across
1240 workers when L</cache_lock> or L</cache_lock_dir> is set: while one request
1241 is building an entry, later requests wait for it and replay the result
1242 instead of running the action again. The waiting requests are held
1243 asynchronously, so this works for actions that themselves use the event
1244 loop. See L</cache_single_flight> for the failure and timeout behaviour.
1245  
1246 Calling the helper more than once is harmless, but only the first call can
1247 hit. To disable the cache for one response, use
1248 C<< $c->stash(buffer => {cache => undef}) >> before calling it.
1249  
1250 =head3 Arguments
1251  
1252 =over 4
1253  
1254 =item C<$c> (implicit)
1255  
1256 The controller the helper is called on.
1257  
1258 =back
1259  
1260 =head3 Returns
1261  
1262 True when the response has been, or will be, sent by the plugin: a cache
1263 hit, or a request now waiting for another one to build the entry. False
1264 when the action must do its work: a miss, a bypassed request, no cache, or a
1265 cache that failed.
1266  
1267 =head3 Side effects
1268  
1269 =over 4
1270  
1271 =item * On a hit: sets the status, headers and body and finishes the
1272 response.
1273  
1274 =item * On a miss: sets C<X-Cache: MISS>, and the response is stored in the
1275 cache when it is complete.
1276  
1277 =item * When waiting: calls C<render_later>; the response is finished later
1278 from the event loop, with the entry or with C<503 Service Unavailable>.
1279  
1280 =item * May take a shared lock through L</cache_lock>, released when the
1281 response is complete or after L</cache_lock_timeout>.
1282  
1283 =back
1284  
1285 =head3 Example
1286  
1287 use Mojolicious::Lite;
1288 use CHI;
1289  
1290 plugin 'Buffer' => {cache => CHI->new(driver => 'Memory', global => 1)};
1291  
1292 get '/report' => sub {
1293 my $c = shift;
1294 return if $c->buffer_is_cached;
1295  
1296 # Only reached on a miss
1297 $c->render(text => expensive_report());
1298 };
1299  
1300 =head3 API SPECIFICATION
1301  
1302 =head4 Input
1303  
1304 { c => { type => 'object', isa => 'Mojolicious::Controller' } }
1305  
1306 =head4 Output
1307  
1308 # Return::Set schema
1309 { type => 'boolean' }
1310  
1311 =head3 MESSAGES
1312  
1313 The helper never croaks. It logs:
1314  
1315 Key Level Meaning
1316 ---------------------- ----- -------------------------------------------------
1317 log_cache_hit debug The response was replayed from the cache
1318 log_cache_get_failed error The cache's get() died; the action runs normally
1319 log_stale_entry debug The entry predates the application or a template
1320 log_building debug This request will build the entry
1321 log_waiting debug This request waits for another one in the worker
1322 log_waiting_worker debug This request waits for another worker
1323 log_lock_failed error The lock backend failed; a local flight is used
1324 log_gave_up debug The wait timed out; a 503 was sent
1325 log_finish_waiter_failed error Replaying to a waiting request failed
1326  
1327 =head3 PSEUDOCODE
1328  
1329 if the plugin is off for this response, return false
1330 if this request was already replayed or is already waiting, return true
1331 if this request is already building an entry, return false
1332 if there is no cache or the request may not use it, return false
1333 mark the request so the finished response is stored
1334 work out the key and look the entry up
1335 if the cache failed, return false
1336 if there is no fresh entry:
1337 set X-Cache: MISS
1338 if single-flight is off, return false
1339 if this worker is already building the key, wait for it, return true
1340 if a lock backend says another worker is building it, poll, return true
1341 start a flight for the key (holding the lock if one was taken)
1342 return false
1343 replay the entry and return true
1344  
1345 =head2 i18n
1346  
1347 my $text = $plugin->i18n('retry_later');
1348  
1349 =head3 Purpose
1350  
1351 Look a message up in the catalog, applying the L</messages> option. It is
1352 the method from L<Mojolicious::Plugin::Buffer::I18N>, imported so that the
1353 plugin and its backends share one implementation; that module documents it
1354 in full.
1355  
1356 =head3 Arguments
1357  
1358 C<$key>, a message key, and an optional hash of placeholder values.
1359  
1360 =head3 Returns
1361  
1362 The text of the message, or the key itself if it is unknown.
1363  
1364 =head3 Side effects
1365  
1366 None.
1367  
1368 =head3 Example
1369  
1370 my $plugin = $app->plugin('Buffer', messages => {log_cache_hit => 'HIT %{key}'});
1371 say $plugin->i18n('log_cache_hit', {key => 'buffer:abc'}); # HIT buffer:abc
1372  
1373 =head3 API SPECIFICATION
1374  
1375 =head4 Input
1376  
1377 {
1378 key => { type => 'string', min => 1 },
1379 args => { type => 'hashref', optional => 1 },
1380 }
1381  
1382 =head4 Output
1383  
1384 # Return::Set schema
1385 { type => 'string' }
1386  
1387 =head3 MESSAGES
1388  
1389 See L<Mojolicious::Plugin::Buffer::I18N/i18n>.
1390  
1391 =cut
1392  
1393 # ---------------------------------------------------------------------------
1394 # Registration helpers
1395 # ---------------------------------------------------------------------------
1396  
1397 # Purpose: Give register() its own copy of a default value.
1398 # Entry criteria: Any value from %DEFAULTS.
1399 # Exit status: An unshared, writable array reference for an array
1400 # reference; anything else unchanged.
1401 # Side effects: None.
1402 7659 ▶sub _copy_default :Private {
Subroutine _copy_default: called CC=2 SCAR=6.9
1403 7659 my $value = shift;
1404  
1405 7659 ▶ return (ref($value) eq 'ARRAY') ? [@$value] : $value;
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 1332 6327 7659
1406 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1407  
1408 # Purpose: Check one option value against its schema.
1409 # Entry criteria: $name is a key of %OPTION_SCHEMA.
1410 # Exit status: 1 if the value is acceptable, 0 otherwise. undef is
1411 # only acceptable for options marked optional, or offered
1412 # a choice of types (last_modified, cache_key).
1413 # Side effects: None; the validator's exception is discarded because
1414 # the caller reports a catalogued message instead.
1415 581 ▶sub _option_valid :Private {
Subroutine _option_valid: called CC=5 SCAR=16.1
1416 581 my ($name, $value) = @_;
1417  
1418 # Params::Validate::Strict lets undef through even for a required type,
1419 # which would let e.g. vary_by => undef drop the Cookie header from the
1420 # cache key without a word, so undef is decided here
1421 581 my $schema = $OPTION_SCHEMA{$name};
1422 581 ▶ my $may_be_undef = (ref($schema) eq 'ARRAY') || $schema->{optional};
Condition100%3/3
ref $schema eq 'ARRAY' || $schema->{'optional'}
l!l&&r!l&&!r
4846568
MC/DC100%2/2
ref $schema eq 'ARRAY' || $schema->{'optional'}
ref $schema eq 'ARRAY' $schema->{'optional'}
Truth table100%3/3
A || B
A= ref $schema eq 'ARRAY'B= $schema->{'optional'}
ABresult
1X1
011
000
1423  
1424 return ((defined($value) || $may_be_undef)
1425 581 ▶ && eval { validate_strict(schema => {$name => $schema}, input => {$name => $value}); 1 }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
(defined $value || $may_be_undef) && eval { do { validate_strict('schema', {$name, $schema}, 'input', {$name, $value}); 1 } } ? : 501 80 581
Condition100%6/6
defined $value || $may_be_undef and eval { do { validate_strict("schema", {$name, $schema}, "input", {$name, $value}); 1 } }
!ll&&!rl&&r
1268501
defined $value or $may_be_undef
l!l&&r!l&&!r
5551412
MC/DC100%3/3
defined $value || $may_be_undef and eval { do { validate_strict("schema", {$name, $schema}, "input", {$name, $value}); 1 } }
defined $value $may_be_undef eval { do { validate_strict("schema", {$name, $schema}, "input", {$name, $value}); 1 } }
Truth table80%4/5
A or B and C
A= defined $valueB= $may_be_undefC= eval { do { validate_strict("schema", {$name, $schema}, "input", {$name, $value}); 1 } }
ABCresult
00X0
1X00
0100
1X11
0111
1426 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1427  
1428 # Purpose: Find the catalog key that explains a bad option value.
1429 # Entry criteria: $name is a known option.
1430 # Exit status: A message key that exists in the catalog.
1431 # Side effects: None.
1432 80 ▶sub _option_message :Private {
Subroutine _option_message: called CC=3 SCAR=11.1
1433 80 my $name = shift;
1434  
1435 80 ▶ my $key = $OPTION_MESSAGE{$name} // "option_$name";
Condition100%2/2
$OPTION_MESSAGE{$name} // "option_$name"
l!l
1268
MC/DC100%1/1
$OPTION_MESSAGE{$name} // "option_$name"
$OPTION_MESSAGE{$name}
Truth table100%2/2
A
A= $OPTION_MESSAGE{$name}
Aresult
11
00
1436 80 ▶ return exists(Mojolicious::Plugin::Buffer::I18N->catalog->{$key}) ? $key : 'option_invalid';
Branch: 1 branch
BranchTrueFalseTotal
exists 'Mojolicious::Plugin::Buffer::I18N'->catalog->{$key} ? : 80 0 80
1437 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1438  
1439 # Purpose: Choose the lock backend that makes single-flight span
1440 # worker processes.
1441 # Entry criteria: $options holds validated cache_lock/cache_lock_dir.
1442 # Exit status: The backend object, or undef for per-worker flights.
1443 # Side effects: Croaks if both were given; creates the lock directory.
1444 249 ▶sub _build_lock :Private {
Subroutine _build_lock: called CC=5 SCAR=16.1
1445 249 my ($self, $options) = @_;
1446  
1447 249 my ($backend, $dir) = @{$options}{qw(cache_lock cache_lock_dir)};
1448 249 ▶ croak $self->i18n('lock_options_combined') if defined($backend) && defined($dir);
Branch: 1 branch
BranchTrueFalseTotal
if defined $backend and defined $dir 2 247 249
Condition100%3/3
defined $backend and defined $dir
!ll&&!rl&&r
24162
MC/DC100%2/2
defined $backend and defined $dir
defined $backend defined $dir
Truth table100%3/3
A and B
A= defined $backendB= defined $dir
ABresult
0X0
100
111
1449  
1450 # cache_lock_dir is a shorthand for the built-in file backend
1451 return $backend // (defined($dir)
1452 ? Mojolicious::Plugin::Buffer::Lock::File->new(dir => $dir, messages => $self->{messages})
1453 247 ▶ : undef);
Branch: 1 branch
BranchTrueFalseTotal
defined $dir ? : 25 216 241
Condition100%3/3
$backend // (defined $dir ? "Mojolicious::Plugin::Buffer::Lock::File"->new("dir", $dir, "messages", $self->{"messages"}) : undef)
l!l&&r!l&&!r
617224
MC/DC100%2/2
$backend // (defined $dir ? "Mojolicious::Plugin::Buffer::Lock::File"->new("dir", $dir, "messages", $self->{"messages"}) : undef)
$backend (defined $dir ? "Mojolicious::Plugin::Buffer::Lock::File"->new("dir", $dir, "messages", $self->{"messages"}) : undef)
Truth table100%3/3
A // B
A= $backendB= (defined $dir ? "Mojolicious::Plugin::Buffer::Lock::File"->new("dir", $dir, "messages", $self->{"messages"}) : undef)
ABresult
1X1
011
000
1454 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1455  
1456 # Purpose: Turn the encodings option into the list actually offered.
1457 # Entry criteria: $requested is an array reference.
1458 # Exit status: An array reference of canonical, unique, available codings
1459 # in the order given.
1460 # Side effects: Croaks on an unknown coding; loads optional modules.
1461 239 ▶sub _supported_encodings :Private {
Subroutine _supported_encodings: called CC=7 SCAR=19.5
1462 239 my ($self, $requested) = @_;
1463  
1464 239 my (@encodings, %seen);
1465 239 for my $encoding (@$requested) {
1466 689 my $name = _canonical_encoding($encoding);
1467 689 ▶ croak $self->i18n('unknown_encoding', {encoding => $encoding // ''}) unless $ENCODERS{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $ENCODERS{$name} 2 687 689
Condition50%1/2
$encoding // ""
l!l
20
MC/DC0%0/1
$encoding // ""
$encoding
Truth table50%1/2
A
A= $encoding
Aresult
11
00
1468  
1469 # Keep the first mention, and skip codings whose module is missing
1470 687 ▶ next if $seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$name}++ 0 687 687
1471 687 ▶ next if $ENCODING_MODULE{$name} && !_module_available($ENCODING_MODULE{$name});
Branch: 1 branch
BranchTrueFalseTotal
if $ENCODING_MODULE{$name} and not _module_available($ENCODING_MODULE{$name}) 220 467 687
Condition100%3/3
$ENCODING_MODULE{$name} and not _module_available($ENCODING_MODULE{$name})
!ll&&!rl&&r
237230220
MC/DC100%2/2
$ENCODING_MODULE{$name} and not _module_available($ENCODING_MODULE{$name})
$ENCODING_MODULE{$name} not _module_available($ENCODING_MODULE{$name})
Truth table100%3/3
A and not(B)
A= $ENCODING_MODULE{$name}B= not _module_available($ENCODING_MODULE{$name})
ABresult
0X0
100
111
1472 467 push @encodings, $name;
1473 }
1474  
1475 237 return \@encodings;
1476 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1477  
1478 # Purpose: Report whether an optional module can be loaded.
1479 # Entry criteria: $module is a package name.
1480 # Exit status: 1 if it loads, 0 if it is missing or fails to compile.
1481 # Side effects: Loads the module; caches the answer for the process.
1482 535 ▶sub _module_available :Private {
Subroutine _module_available: called CC=3 SCAR=11.0
1483 535 my $module = shift;
1484  
1485 # An ambient $SIG{__DIE__} handler can swallow the die from an @INC hook
1486 # (Test::Without::Module uses one), which makes a hidden module look
1487 # loadable. Probe with the default handler so the load decides.
1488 535 local $SIG{__DIE__};
1489  
1490 # load_class returns undef on success, 1 if missing, or an exception
1491 535 ▶ return $AVAILABLE{$module} //= load_class($module) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
load_class($module) ? : 34 41 75
Condition100%2/2
$AVAILABLE{$module} //= load_class($module) ? 0 : 1
l!l
46075
MC/DC100%1/1
$AVAILABLE{$module} //= load_class($module) ? 0 : 1
$AVAILABLE{$module}
Truth table100%2/2
A
A= $AVAILABLE{$module}
Aresult
11
00
1492 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1493  
1494 # Purpose: Write one catalogued line to the application log.
1495 # Entry criteria: $level is a Mojo::Log level; $key is a catalog key.
1496 # Exit status: $self, for chaining.
1497 # Side effects: Logs. The message is built lazily, only if the level is
1498 # enabled, so debug lines cost nothing in production.
1499 556 ▶sub _log :Private {
Subroutine _log: called CC=3 SCAR=11.0
1500 556 my ($self, $app, $level, $key, $args) = @_;
1501  
1502 # Exceptions arrive with a trailing newline that would split the line
1503 556 ▶ my %args = %{$args // {}};
Condition100%2/2
$args // {}
l!l
50353
MC/DC100%1/1
$args // {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
1504 556 ▶ $args{error} = trim("$args{error}") if defined($args{error});
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"error"} 8 548 556
1505  
1506 556 ▶ $app->log->$level(sub { $self->i18n($key, \%args) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1507  
1508 556 return $self;
1509 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1510  
1511 # ---------------------------------------------------------------------------
1512 # Per-response options
1513 # ---------------------------------------------------------------------------
1514  
1515 # Purpose: Work out the options that apply to this response.
1516 # Entry criteria: $c is the current controller.
1517 # Exit status: A new hash reference of options, or undef when the
1518 # buffer stash is a false scalar (plugin off).
1519 # Side effects: Calls buffer_<name> controller methods.
1520 880 ▶sub _options_for :Private {
Subroutine _options_for: called CC=9 SCAR=22.0
1521 880 my ($self, $c) = @_;
1522  
1523 880 my $override = $c->stash->{$STASH_OVERRIDE};
1524 880 ▶ return undef if defined($override) && !ref($override) && !$override;
Branch: 1 branch
BranchTrueFalseTotal
if defined $override and not ref $override and not $override 10 870 880
Condition83%5/6
defined $override and not ref $override and not $override
!ll&&!rl&&r
870010
defined $override and not ref $override
!ll&&!rl&&r
8026810
MC/DC66%2/3
defined $override and not ref $override and not $override
defined $override not ref $override not $override
Truth table75%3/4
A and not(B) and not(C)
A= defined $overrideB= not ref $overrideC= not $override
ABCresult
0XX0
10X0
1100
1111
1525  
1526 870 my %options = %{$self->{options}};
1527 870 ▶ %options = (%options, %$override) if ref($override) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $override eq "HASH" 68 802 870
1528  
1529 # A route default or a controller class can declare these for a whole
1530 # group of pages, with the buffer stash still the most specific place to
1531 # say otherwise
1532 870 for my $name (@GROUP_OPTIONS) {
1533 3480 ▶ next if (ref($override) eq 'HASH') && exists($override->{$name});
Branch: 1 branch
BranchTrueFalseTotal
if ref $override eq "HASH" and exists $override->{$name} 12 3468 3480
Condition100%3/3
ref $override eq "HASH" and exists $override->{$name}
!ll&&!rl&&r
320826012
MC/DC100%2/2
ref $override eq "HASH" and exists $override->{$name}
ref $override eq "HASH" exists $override->{$name}
Truth table100%3/3
A and B
A= ref $override eq "HASH"B= exists $override->{$name}
ABresult
0X0
100
111
1534 3468 my $declared = $self->_declared_option($c, $name);
1535 3468 ▶ $options{$name} = $declared if defined($declared);
Branch: 1 branch
BranchTrueFalseTotal
if defined $declared 64 3404 3468
1536 }
1537  
1538 870 return \%options;
1539 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1540  
1541 # Purpose: Read a group-level declaration for one option.
1542 # Entry criteria: $name is one of @GROUP_OPTIONS.
1543 # Exit status: The declared scalar, or undef if nothing usable was
1544 # declared.
1545 # Side effects: Calls the controller method; logs if it dies.
1546 3468 ▶sub _declared_option :Private {
Subroutine _declared_option: called CC=6 SCAR=18.6
1547 3468 my ($self, $c, $name) = @_;
1548  
1549 # Route defaults and under routes land in the stash
1550 3468 my $stashed = $c->stash->{$name};
1551 3468 ▶ return $stashed if defined($stashed) && !ref($stashed);
Branch: 1 branch
BranchTrueFalseTotal
if defined $stashed and not ref $stashed 50 3418 3468
Condition66%2/3
defined $stashed and not ref $stashed
!ll&&!rl&&r
3418050
MC/DC50%1/2
defined $stashed and not ref $stashed
defined $stashed not ref $stashed
Truth table66%2/3
A and not(B)
A= defined $stashedB= not ref $stashed
ABresult
0X0
100
111
1552  
1553 3418 my $method = "buffer_$name";
1554 3418 ▶ return undef unless $c->can($method);
Branch: 1 branch
BranchTrueFalseTotal
unless $c->can($method) 3404 14 3418
1555  
1556 14 my $declared = eval { $c->$method };
1557 14 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 14 14
1558 # A broken declaration must not take the response down with it; the
1559 # plugin option stays in force instead
1560 0 $self->_log($c->app, debug => 'log_declaration_failed', {method => $method, error => $error});
1561 0 return undef;
1562 }
1563  
1564 14 ▶ return ref($declared) ? undef : $declared;
Branch: 1 branch
BranchTrueFalseTotal
ref $declared ? : 0 14 14
1565 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1566  
1567 # ---------------------------------------------------------------------------
1568 # The after_dispatch pipeline
1569 # ---------------------------------------------------------------------------
1570  
1571 # Purpose: The after_dispatch hook. Wraps the response pipeline so
1572 # that a request which was building a cache entry always
1573 # releases the requests waiting for it, whether it
1574 # succeeded, failed, or produced something uncacheable.
1575 # Entry criteria: $c is the finished controller.
1576 # Exit status: $self. Re-throws any pipeline exception.
1577 # Side effects: Rewrites the response; answers waiting requests.
1578 # Protected so a subclass can wrap it.
1579 583 ▶sub _process :Protected {
Subroutine _process: called CC=4 SCAR=13.9
1580 583 my ($self, $c) = @_;
1581  
1582 583 my $flight = $c->stash->{$STASH_FLIGHT};
1583 583 my $ok = eval { $self->_process_response($c); 1 };
1584 583 my $error = $@;
1585  
1586 583 ▶ if ($flight) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flight) 139 444 583
1587 139 ▶ eval { $self->_release_flight($c->app, $flight, $c->stash->{$STASH_STORED}); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_release_flight($c->app, $flight, $c->stash->{$STASH_STORED}); 1 } } or $self->_log($c->app, "error", "log_release_failed", {"error", $@}) 139 0 139
1588 or $self->_log($c->app, error => 'log_release_failed', {error => $@});
1589 }
1590  
1591 # Re-throw unchanged. croak() is deliberately not used: it would append
1592 # a second "at FILE line N" to a message that already has one.
1593 583 ▶ die $error unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 583 583
1594  
1595 583 return $self;
1596 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1597  
1598 # Purpose: Optimise, compress, cache and validate one response.
1599 # Entry criteria: $c is the finished controller.
1600 # Exit status: $self.
1601 # Side effects: May replace the body and set Content-Encoding, Vary,
1602 # ETag, Last-Modified and Content-Length; may store the
1603 # response in the cache; may turn it into a 304.
1604 583 ▶sub _process_response :Private {
Subroutine _process_response: called CC=14 SCAR=26.5
1605 583 my ($self, $c) = @_;
1606  
1607 583 ▶ my $options = $self->_options_for($c) or return $self;
Branch: 1 branch
BranchTrueFalseTotal
my $options = $self->_options_for($c) or return $self 577 6 583
1608 577 my $res = $c->res;
1609  
1610 # Only an in-memory, unencoded body with a known media type is ours
1611 577 ▶ my $body = _buffered_body($res) // return $self;
Condition100%2/2
_buffered_body($res) // (return $self)
l!l
56512
MC/DC100%1/1
_buffered_body($res) // (return $self)
_buffered_body($res)
Truth table100%2/2
A
A= _buffered_body($res)
Aresult
11
00
1612 565 my $type = _mime_type($res->headers->content_type);
1613 565 ▶ return $self if !defined($type) || _matches($type, $options->{excluded_types});
Branch: 1 branch
BranchTrueFalseTotal
if not defined $type or _matches($type, $options->{"excluded_types"}) 2 563 565
Condition66%2/3
not defined $type or _matches($type, $options->{"excluded_types"})
l!l&&r!l&&!r
02563
MC/DC50%1/2
not defined $type or _matches($type, $options->{"excluded_types"})
not defined $type _matches($type, $options->{"excluded_types"})
Truth table66%2/3
not(A) or B
A= not defined $typeB= _matches($type, $options->{"excluded_types"})
ABresult
1X1
011
000
1614  
1615 # A replayed entry was optimised before it was stored
1616 563 my $from_cache = $c->stash->{$STASH_FROM_CACHE};
1617 563 ▶ $body = $self->_optimise_html($c, $options, $type, $body) unless $from_cache;
Branch: 1 branch
BranchTrueFalseTotal
unless $from_cache 486 77 563
1618  
1619 # The ETag is calculated from the unencoded entity plus the content coding,
1620 # so gzip's changing timestamp can never alter it
1621 563 my $entity = $body;
1622 563 ▶ utf8::encode($entity) if utf8::is_utf8($entity);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($entity) 0 563 563
1623  
1624 my $encoded = _matches($type, $options->{compressible_types})
1625 563 ▶ ? $self->_compress($c, $options, $entity)
Branch: 1 branch
BranchTrueFalseTotal
_matches($type, $options->{'compressible_types'}) ? : 559 4 563
1626 : undef;
1627  
1628 # Populate the server-side cache with the unencoded entity, so that each
1629 # client still gets its own content coding and conditional response
1630 563 ▶ my $code = $res->code || 0;
Condition50%1/2
$res->code || 0
l!l
5630
MC/DC0%0/1
$res->code || 0
$res->code
Truth table50%1/2
A
A= $res->code
Aresult
11
00
1631 $self->_store_in_cache($c, $options, $entity, $code)
1632 563 ▶ if !$from_cache && $c->stash->{$STASH_CHECKED};
Branch: 1 branch
BranchTrueFalseTotal
if not $from_cache and $c->stash->{$STASH_CHECKED} 151 412 563
Condition100%3/3
not $from_cache and $c->stash->{$STASH_CHECKED}
!ll&&!rl&&r
77335151
MC/DC100%2/2
not $from_cache and $c->stash->{$STASH_CHECKED}
not $from_cache $c->stash->{$STASH_CHECKED}
Truth table100%3/3
not(A) and B
A= not $from_cacheB= $c->stash->{$STASH_CHECKED}
ABresult
0X0
100
111
1633  
1634 563 ▶ return $self if $self->_answer_not_modified($c, $options, $entity, $encoded && $encoded->{encoding}, $code);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_answer_not_modified($c, $options, $entity, $encoded && $encoded->{"encoding"}, $code) 48 515 563
Condition66%2/3
$encoded && $encoded->{'encoding'}
!ll&&!rl&&r
507056
MC/DC50%1/2
$encoded && $encoded->{'encoding'}
$encoded $encoded->{'encoding'}
Truth table66%2/3
A && B
A= $encodedB= $encoded->{'encoding'}
ABresult
0X0
100
111
1635  
1636 # Both branches are bytes, so length() is the Content-Length
1637 515 ▶ my $final = $encoded ? $encoded->{body} : $entity;
Branch: 1 branch
BranchTrueFalseTotal
$encoded ? : 54 461 515
1638 515 $res->body($final);
1639 515 $res->headers->content_length(length($final));
1640  
1641 515 return $self;
1642 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1643  
1644 # Purpose: Decide whether a response is one the plugin may rework,
1645 # and fetch its body if so.
1646 # Entry criteria: $res is a Mojo::Message::Response.
1647 # Exit status: The body, or undef for interim and bodyless statuses,
1648 # bodies already encoded (e.g. by the renderer), multipart
1649 # and streamed content, files on disk and empty bodies.
1650 # Side effects: None.
1651 577 ▶sub _buffered_body :Private {
Subroutine _buffered_body: called CC=11 SCAR=24.4
1652 577 my $res = shift;
1653  
1654 577 ▶ my $code = $res->code || 0;
Condition50%1/2
$res->code || 0
l!l
5770
MC/DC0%0/1
$res->code || 0
$res->code
Truth table50%1/2
A
A= $res->code
Aresult
11
00
1655 577 my $content = $res->content;
1656  
1657 # Short-circuit order matters: a multipart body has no asset()
1658 577 ▶ my $ours = !($code && (($code < $HTTP_MIN_FINAL) || $BODYLESS_STATUS{$code}))
Condition77%14/18
$code && ($code < $HTTP_MIN_FINAL || $BODYLESS_STATUS{$code}) || $res->headers->content_encoding || $content->is_multipart || $content->is_dynamic || $content->asset->is_file
l!l&&r!l&&!r
62569
$code and $code < $HTTP_MIN_FINAL || $BODYLESS_STATUS{$code} or $res->headers->content_encoding or $content->is_multipart or $content->is_dynamic
l!l&&r!l&&!r
60571
$code and $code < $HTTP_MIN_FINAL || $BODYLESS_STATUS{$code} or $res->headers->content_encoding or $content->is_multipart
l!l&&r!l&&!r
60571
$code and $code < $HTTP_MIN_FINAL || $BODYLESS_STATUS{$code} or $res->headers->content_encoding
l!l&&r!l&&!r
42571
$code and $code < $HTTP_MIN_FINAL || $BODYLESS_STATUS{$code}
!ll&&!rl&&r
05734
$code < $HTTP_MIN_FINAL or $BODYLESS_STATUS{$code}
l!l&&r!l&&!r
04573
MC/DC42%3/7
$code && ($code < $HTTP_MIN_FINAL || $BODYLESS_STATUS{$code}) || $res->headers->content_encoding || $content->is_multipart || $content->is_dynamic || $content->asset->is_file
$code $code < $HTTP_MIN_FINAL $BODYLESS_STATUS{$code} $res->headers->content_encoding $content->is_multipart $content->is_dynamic $content->asset->is_file
Truth table33%4/12
A and B or C or D or E or F || G
A= $codeB= $code < $HTTP_MIN_FINALC= $BODYLESS_STATUS{$code}D= $res->headers->content_encodingE= $content->is_multipartF= $content->is_dynamicG= $content->asset->is_file
ABCDEFGresult
11XXXXX1
101XXXX1
0XX1XXX1
1001XXX1
0XX01XX1
10001XX1
0XX001X1
100001X1
0XX00011
10000011
0XX00000
10000000
1659 && !$res->headers->content_encoding
1660 && !$content->is_multipart
1661 && !$content->is_dynamic
1662 && !$content->asset->is_file;
1663  
1664 577 ▶ my $body = $ours ? $content->asset->slurp : undef;
Branch: 1 branch
BranchTrueFalseTotal
$ours ? : 569 8 577
1665 577 ▶ return (defined($body) && length($body)) ? $body : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $body && length $body ? : 565 12 577
Condition100%3/3
defined $body and length $body
!ll&&!rl&&r
84565
MC/DC100%2/2
defined $body and length $body
defined $body length $body
Truth table100%3/3
A and B
A= defined $bodyB= length $body
ABresult
0X0
100
111
1666 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1667  
1668 # Purpose: Apply optimise_content to HTML responses.
1669 # Entry criteria: $type is the lower-cased media type.
1670 # Exit status: The optimised body if it is smaller, else the original.
1671 # Side effects: Logs the saving at debug level.
1672 486 ▶sub _optimise_html :Private {
Subroutine _optimise_html: called CC=5 SCAR=16.1
1673 486 my ($self, $c, $options, $type, $body) = @_;
1674  
1675 486 ▶ my $optimised = ($options->{optimise_content} && $HTML_TYPES{$type})
Branch: 1 branch
BranchTrueFalseTotal
$options->{'optimise_content'} && $HTML_TYPES{$type} ? : 54 432 486
Condition100%3/3
$options->{"optimise_content"} and $HTML_TYPES{$type}
!ll&&!rl&&r
430254
MC/DC100%2/2
$options->{"optimise_content"} and $HTML_TYPES{$type}
$options->{"optimise_content"} $HTML_TYPES{$type}
Truth table100%3/3
A and B
A= $options->{"optimise_content"}B= $HTML_TYPES{$type}
ABresult
0X0
100
111
1676 ? $self->_optimise($body, $c, $options)
1677 : undef;
1678  
1679 # Keep the optimised body only if it really is smaller
1680 486 ▶ if (defined($optimised) && (length($optimised) < length($body))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $optimised and length $optimised < length $body) 52 434 486
Condition100%3/3
defined $optimised and length $optimised < length $body
!ll&&!rl&&r
432252
MC/DC100%2/2
defined $optimised and length $optimised < length $body
defined $optimised length $optimised < length $body
Truth table100%3/3
A and B
A= defined $optimisedB= length $optimised < length $body
ABresult
0X0
100
111
1681 52 $self->_log($c->app, debug => 'log_optimised',
1682 {from => length($body), to => length($optimised), count => length($optimised)});
1683 52 $body = $optimised;
1684 }
1685  
1686 486 return $body;
1687 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1688  
1689 # Purpose: Compress the entity with the best coding the client
1690 # accepts.
1691 # Entry criteria: $entity is bytes of a compressible type.
1692 # Exit status: {encoding, body} when compression was used, else undef.
1693 # Side effects: Adds Vary: Accept-Encoding whenever compression is on, as
1694 # the choice of representation depends on it even when
1695 # identity wins; sets Content-Encoding when used; logs.
1696 559 ▶sub _compress :Private {
Subroutine _compress: called CC=10 SCAR=23.7
1697 559 my ($self, $c, $options, $entity) = @_;
1698  
1699 559 ▶ return undef unless $options->{compress_content};
Branch: 1 branch
BranchTrueFalseTotal
unless $options->{"compress_content"} 27 532 559
1700  
1701 532 my $headers = $c->res->headers;
1702 532 _add_vary($headers);
1703  
1704 532 my $wanted = _negotiate_encoding($c->req->headers->accept_encoding, $options->{encodings});
1705 532 ▶ return undef unless defined($wanted) && (length($entity) >= ($options->{min_compress_size} // 0));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wanted and length $entity >= ($options->{"min_compress_size"} // 0) 470 62 532
Condition80%4/5
defined $wanted and length $entity >= ($options->{"min_compress_size"} // 0)
!ll&&!rl&&r
34013062
$options->{"min_compress_size"} // 0
l!l
1920
MC/DC100%2/2
defined $wanted and length $entity >= ($options->{"min_compress_size"} // 0)
defined $wanted length $entity >= ($options->{"min_compress_size"} // 0)
MC/DC0%0/1
$options->{"min_compress_size"} // 0
$options->{"min_compress_size"}
Truth table100%3/3
A and B
A= defined $wantedB= length $entity >= ($options->{"min_compress_size"} // 0)
ABresult
0X0
100
111
Truth table50%1/2
A
A= $options->{"min_compress_size"}
Aresult
11
00
1706  
1707 62 my $result = _encode_body($wanted, $entity);
1708 62 ▶ if (defined($result->{error})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result->{"error"}) 0 62 62
1709 0 $self->_log($c->app, error => 'log_compress_failed', {encoding => $wanted, error => $result->{error}});
1710 0 return undef;
1711 }
1712  
1713 # Compression that saves less than min_compress_saving bytes is not
1714 # worth the header and the client's work to decode it; it must always
1715 # save something
1716 62 ▶ return undef unless defined($result->{body});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $result->{"body"} 0 62 62
1717 62 my $saving = length($entity) - length($result->{body});
1718 62 ▶ return undef unless ($saving > 0) && ($saving >= ($options->{min_compress_saving} // 0));
Branch: 1 branch
BranchTrueFalseTotal
unless $saving > 0 and $saving >= ($options->{"min_compress_saving"} // 0) 6 56 62
Condition60%3/5
$saving > 0 and $saving >= ($options->{"min_compress_saving"} // 0)
!ll&&!rl&&r
0656
$options->{"min_compress_saving"} // 0
l!l
620
MC/DC50%1/2
$saving > 0 and $saving >= ($options->{"min_compress_saving"} // 0)
$saving > 0 $saving >= ($options->{"min_compress_saving"} // 0)
MC/DC0%0/1
$options->{"min_compress_saving"} // 0
$options->{"min_compress_saving"}
Truth table66%2/3
A and B
A= $saving > 0B= $saving >= ($options->{"min_compress_saving"} // 0)
ABresult
0X0
100
111
Truth table50%1/2
A
A= $options->{"min_compress_saving"}
Aresult
11
00
1719  
1720 56 $headers->content_encoding($wanted);
1721 $self->_log($c->app, debug => 'log_compressed',
1722 56 {encoding => $wanted, from => length($entity), to => length($result->{body}), count => length($result->{body})});
1723  
1724 56 return {encoding => $wanted, body => $result->{body}};
1725 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1726  
1727 # Purpose: Add the validators and, when they match the request,
1728 # turn the response into 304 Not Modified.
1729 # Entry criteria: $entity is the unencoded body; $encoding is the coding
1730 # used or undef.
1731 # Exit status: 1 if a 304 was produced, 0 otherwise.
1732 # Side effects: Sets Last-Modified and ETag on 200 GET/HEAD responses;
1733 # on a match empties the body and changes the status.
1734 563 ▶sub _answer_not_modified :Private {
Subroutine _answer_not_modified: called CC=9 SCAR=22.0
1735 563 my ($self, $c, $options, $entity, $encoding, $code) = @_;
1736  
1737 563 ▶ return 0 unless ($code == $HTTP_OK) && $SAFE_METHODS{$c->req->method};
Branch: 1 branch
BranchTrueFalseTotal
unless $code == $HTTP_OK and $SAFE_METHODS{$c->req->method} 30 533 563
Condition100%3/3
$code == $HTTP_OK and $SAFE_METHODS{$c->req->method}
!ll&&!rl&&r
264533
MC/DC100%2/2
$code == $HTTP_OK and $SAFE_METHODS{$c->req->method}
$code == $HTTP_OK $SAFE_METHODS{$c->req->method}
Truth table100%3/3
A and B
A= $code == $HTTP_OKB= $SAFE_METHODS{$c->req->method}
ABresult
0X0
100
111
1738  
1739 533 my $headers = $c->res->headers;
1740 533 my $last_modified = $self->_resolve_last_modified($options->{last_modified}, $c);
1741 533 ▶ $headers->last_modified(Mojo::Date->new($last_modified)->to_string)
Branch: 1 branch
BranchTrueFalseTotal
if defined $last_modified and not $headers->last_modified 529 4 533
Condition66%2/3
defined $last_modified and not $headers->last_modified
!ll&&!rl&&r
40529
MC/DC50%1/2
defined $last_modified and not $headers->last_modified
defined $last_modified not $headers->last_modified
Truth table66%2/3
A and not(B)
A= defined $last_modifiedB= not $headers->last_modified
ABresult
0X0
100
111
1742 if defined($last_modified) && !$headers->last_modified;
1743  
1744 533 ▶ my $etag = $options->{generate_etag} ? _ensure_etag($headers, $entity, $encoding) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$options->{'generate_etag'} ? : 519 14 533
1745 533 ▶ return 0 unless $options->{generate_304} && _is_fresh($c->req->headers, $options, $etag, $last_modified);
Branch: 1 branch
BranchTrueFalseTotal
unless $options->{"generate_304"} and _is_fresh($c->req->headers, $options, $etag, $last_modified) 485 48 533
Condition100%3/3
$options->{"generate_304"} and _is_fresh($c->req->headers, $options, $etag, $last_modified)
!ll&&!rl&&r
448148
MC/DC100%2/2
$options->{"generate_304"} and _is_fresh($c->req->headers, $options, $etag, $last_modified)
$options->{"generate_304"} _is_fresh($c->req->headers, $options, $etag, $last_modified)
Truth table100%3/3
A and B
A= $options->{"generate_304"}B= _is_fresh($c->req->headers, $options, $etag, $last_modified)
ABresult
0X0
100
111
1746  
1747 48 ▶ $self->_log($c->app, debug => defined($etag) ? 'log_not_modified_etag' : 'log_not_modified', {etag => $etag});
Branch: 1 branch
BranchTrueFalseTotal
defined $etag ? : 44 4 48
1748 48 $c->res->code($HTTP_NOT_MODIFIED);
1749 48 $c->res->body('');
1750 48 $headers->remove('Content-Length');
1751  
1752 48 return 1;
1753 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1754  
1755 # Purpose: Make sure the response has an entity tag.
1756 # Entry criteria: $entity is bytes; $encoding is a coding name or undef.
1757 # Exit status: The tag in force: the action's own, or a new MD5 tag.
1758 # Side effects: Sets the ETag header when the action did not.
1759 519 ▶sub _ensure_etag :Private {
Subroutine _ensure_etag: called CC=4 SCAR=14.3
1760 519 my ($headers, $entity, $encoding) = @_;
1761  
1762 519 my $etag = $headers->etag;
1763 519 ▶ if (!defined($etag) || !length($etag)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $etag and length $etag) 519 0 519
Condition33%1/3
defined $etag and length $etag
!ll&&!rl&&r
51900
MC/DC0%0/2
defined $etag and length $etag
defined $etag length $etag
Truth table33%1/3
A and B
A= defined $etagB= length $etag
ABresult
0X0
100
111
1764 # The coding is part of the tag: gzip and identity differ
1765 519 ▶ $etag = '"' . md5_sum($entity . (defined($encoding) ? "\x00$encoding" : '')) . '"';
Branch: 1 branch
BranchTrueFalseTotal
defined $encoding ? : 56 463 519
1766 519 $headers->etag($etag);
1767 }
1768  
1769 519 return $etag;
1770 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1771  
1772 # Purpose: Decide whether the client's copy is current (RFC 7232).
1773 # Entry criteria: $req_headers are the request headers; $etag and
1774 # $last_modified are what this response carries, or undef.
1775 # Exit status: 1 if a 304 should be sent, 0 otherwise.
1776 # Side effects: None.
1777 529 ▶sub _is_fresh :Private {
Subroutine _is_fresh: called CC=9 SCAR=22.0
1778 529 my ($req_headers, $options, $etag, $last_modified) = @_;
1779  
1780 529 my $if_none_match = $req_headers->if_none_match;
1781 529 my $fresh;
1782  
1783 529 ▶ if (defined($if_none_match)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $if_none_match) { } 52 477 529
1784 # If-None-Match takes precedence; If-Modified-Since is then ignored
1785 # even when there is no ETag to compare it with
1786 52 ▶ $fresh = defined($etag) && _etag_matches($if_none_match, $etag);
Condition100%3/3
defined $etag && _etag_matches($if_none_match, $etag)
!ll&&!rl&&r
41434
MC/DC100%2/2
defined $etag && _etag_matches($if_none_match, $etag)
defined $etag _etag_matches($if_none_match, $etag)
Truth table100%3/3
A && B
A= defined $etagB= _etag_matches($if_none_match, $etag)
ABresult
0X0
100
111
1787 } else {
1788 # Without an entity tag, If-Modified-Since is the only validator the
1789 # client can offer. Last-Modified comes from the application and its
1790 # templates, not from the data a page was rendered from, so on its own
1791 # it cannot show that the representation is unchanged: a database row
1792 # or a stash value can move under a template that has not been
1793 # touched. trust_last_modified is the opt-in for pages where that
1794 # cannot happen.
1795 477 ▶ my $trusted = !defined($etag) || $options->{trust_last_modified};
Condition100%3/3
!defined($etag) || $options->{'trust_last_modified'}
l!l&&r!l&&!r
1020447
MC/DC100%2/2
!defined($etag) || $options->{'trust_last_modified'}
!defined($etag) $options->{'trust_last_modified'}
Truth table100%3/3
not(A) || B
A= !defined($etag)B= $options->{'trust_last_modified'}
ABresult
1X1
011
000
1796 477 my $since = $req_headers->if_modified_since;
1797 my $since_epoch = ($trusted && defined($last_modified) && defined($since))
1798 477 ▶ ? eval { Mojo::Date->new($since)->epoch }
Branch: 1 branch
BranchTrueFalseTotal
$trusted && defined $last_modified && defined $since ? : 20 457 477
Condition83%5/6
$trusted and defined $last_modified and defined $since
!ll&&!rl&&r
4471020
$trusted and defined $last_modified
!ll&&!rl&&r
447030
MC/DC66%2/3
$trusted and defined $last_modified and defined $since
$trusted defined $last_modified defined $since
Truth table75%3/4
A and B and C
A= $trustedB= defined $last_modifiedC= defined $since
ABCresult
0XX0
10X0
1100
1111
1799 : undef;
1800 477 ▶ $fresh = defined($since_epoch) && ($last_modified <= $since_epoch);
Condition100%3/3
defined $since_epoch && $last_modified <= $since_epoch
!ll&&!rl&&r
457614
MC/DC100%2/2
defined $since_epoch && $last_modified <= $since_epoch
defined $since_epoch $last_modified <= $since_epoch
Truth table100%3/3
A && B
A= defined $since_epochB= $last_modified <= $since_epoch
ABresult
0X0
100
111
1801 }
1802  
1803 529 ▶ return $fresh ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$fresh ? : 48 481 529
1804 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1805  
1806 # ---------------------------------------------------------------------------
1807 # The server-side cache and single-flight
1808 # ---------------------------------------------------------------------------
1809  
1810 # Purpose: The buffer_is_cached helper; see its POD.
1811 # Entry criteria: $c is the controller the helper was called on.
1812 # Exit status: 1 when the plugin answers the request, 0 when the action
1813 # must run.
1814 # Side effects: See the POD. Protected so a subclass can wrap it.
1815 297 ▶sub _is_cached :Protected {
Subroutine _is_cached: called CC=9 SCAR=22.3
1816 297 my ($self, $c) = @_;
1817  
1818 297 ▶ my $options = $self->_options_for($c) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $options = $self->_options_for($c) or return 0 293 4 297
1819 293 my $stash = $c->stash;
1820  
1821 # Calling the helper more than once should not replay a response twice
1822 # or register the same request as a waiter again
1823 293 ▶ return 1 if $stash->{$STASH_FROM_CACHE} || $stash->{$STASH_WAITER};
Branch: 1 branch
BranchTrueFalseTotal
if $stash->{$STASH_FROM_CACHE} or $stash->{$STASH_WAITER} 0 293 293
Condition33%1/3
$stash->{$STASH_FROM_CACHE} or $stash->{$STASH_WAITER}
l!l&&r!l&&!r
00293
MC/DC0%0/2
$stash->{$STASH_FROM_CACHE} or $stash->{$STASH_WAITER}
$stash->{$STASH_FROM_CACHE} $stash->{$STASH_WAITER}
Truth table33%1/3
A or B
A= $stash->{$STASH_FROM_CACHE}B= $stash->{$STASH_WAITER}
ABresult
1X1
011
000
1824 293 ▶ return 0 if $stash->{$STASH_FLIGHT};
Branch: 1 branch
BranchTrueFalseTotal
if $stash->{$STASH_FLIGHT} 0 293 293
1825  
1826 293 my $cache = $options->{cache};
1827 293 ▶ return 0 unless $cache && _request_cacheable($c);
Branch: 1 branch
BranchTrueFalseTotal
unless $cache and _request_cacheable($c) 63 230 293
Condition100%3/3
$cache and _request_cacheable($c)
!ll&&!rl&&r
4320230
MC/DC100%2/2
$cache and _request_cacheable($c)
$cache _request_cacheable($c)
Truth table100%3/3
A and B
A= $cacheB= _request_cacheable($c)
ABresult
0X0
100
111
1828  
1829 # From now on a miss should populate the cache at the end of the response
1830 230 $stash->{$STASH_CHECKED} = 1;
1831 230 my $key = $stash->{$STASH_KEY} = _cache_key($c, $options);
1832  
1833 230 my $lookup = $self->_lookup_entry($c, $cache, $key, 1);
1834 230 ▶ return 0 if $lookup->{failed};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup->{"failed"} 0 230 230
1835 230 ▶ return $self->_cache_miss($c, $options, $key, $cache) unless $lookup->{entry};
Branch: 1 branch
BranchTrueFalseTotal
unless $lookup->{"entry"} 167 63 230
1836  
1837 63 $self->_log($c->app, debug => 'log_cache_hit', {key => $key});
1838 63 return _replay_entry($c, $lookup->{entry});
1839 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1840  
1841 # Purpose: Fetch and validate an entry.
1842 # Entry criteria: $cache understands get() and remove().
1843 # Exit status: {entry => $entry} for a fresh entry, {} for a miss, and
1844 # {failed => 1} when the cache died, so the first lookup
1845 # can tell a broken cache from a miss while pollers treat
1846 # both as "not there yet".
1847 # Side effects: Removes an entry older than the application; logs.
1848 254 ▶sub _lookup_entry :Private {
Subroutine _lookup_entry: called CC=8 SCAR=22.2
1849 254 my ($self, $c, $cache, $key, $log_errors) = @_;
1850  
1851 254 my $entry = eval { $cache->get($key) };
1852 254 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 254 254
1853 0 ▶ $self->_log($c->app, error => 'log_cache_get_failed', {error => $error}) if $log_errors;
Branch: 1 branch
BranchTrueFalseTotal
if $log_errors 0 0 0
1854 0 return {failed => 1};
1855 }
1856  
1857 254 ▶ return {} unless (ref($entry) eq 'HASH') && defined($entry->{body});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" and defined $entry->{"body"} 175 79 254
Condition66%2/3
ref $entry eq "HASH" and defined $entry->{"body"}
!ll&&!rl&&r
175079
MC/DC50%1/2
ref $entry eq "HASH" and defined $entry->{"body"}
ref $entry eq "HASH" defined $entry->{"body"}
Truth table66%2/3
A and B
A= ref $entry eq "HASH"B= defined $entry->{"body"}
ABresult
0X0
100
111
1858  
1859 # An entry created before the application was last changed may have been
1860 # produced by different code, so throw it away
1861 79 my $mtime = $self->_application_mtime($c);
1862 79 ▶ if (defined($mtime) && (($entry->{created} // 0) < $mtime)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $mtime and ($entry->{"created"} // 0) < $mtime) 10 69 79
Condition60%3/5
defined $mtime and ($entry->{"created"} // 0) < $mtime
!ll&&!rl&&r
06910
$entry->{"created"} // 0
l!l
790
MC/DC0%0/2
defined $mtime and ($entry->{"created"} // 0) < $mtime
defined $mtime $entry->{"created"}
Truth table33%1/3
A and B
A= defined $mtimeB= $entry->{"created"}
ABresult
0X0
100
111
1863 10 $self->_log($c->app, debug => 'log_stale_entry');
1864 10 eval { $cache->remove($key) };
1865 10 return {};
1866 }
1867  
1868 69 return {entry => $entry};
1869 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1870  
1871 # Purpose: Handle a miss: join an in-flight build of the same key,
1872 # or become the request that builds and stores it.
1873 # Entry criteria: The cache has no fresh entry for $key.
1874 # Exit status: 1 if this request now waits, 0 if the action must run.
1875 # Side effects: Sets X-Cache: MISS; may take the shared lock; may start
1876 # a flight or register a waiter.
1877 167 ▶sub _cache_miss :Private {
Subroutine _cache_miss: called CC=6 SCAR=17.9
1878 167 my ($self, $c, $options, $key, $cache) = @_;
1879  
1880 167 $c->res->headers->header($X_CACHE => $MISS);
1881 167 ▶ return 0 unless $options->{cache_single_flight};
Branch: 1 branch
BranchTrueFalseTotal
unless $options->{"cache_single_flight"} 4 163 167
1882  
1883 # Include the cache object so that two caches with the same key do not
1884 # wait for each other
1885 163 my $id = refaddr($cache) . "\x00$key";
1886 163 my $flight = $self->{inflight}{$id};
1887 163 ▶ return $self->_join_flight($c, $flight) if $flight;
Branch: 1 branch
BranchTrueFalseTotal
if $flight 14 149 163
1888  
1889 # With a lock backend, elect one worker to build the entry and make the
1890 # others wait for it, even though they cannot share the flight table
1891 149 my $guard;
1892 149 ▶ if ($self->{lock}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lock"}) 18 131 149
1893 18 my $lock = $self->_acquire_lock($key);
1894 18 ▶ return $self->_join_shared_lock($c, $options, $key, $cache) if $lock->{busy};
Branch: 1 branch
BranchTrueFalseTotal
if $lock->{"busy"} 10 8 18
1895  
1896 # On a backend error, carry on with a flight local to this worker
1897 8 ▶ $self->_log($c->app, error => 'log_lock_failed', {error => $lock->{error}}) if !$lock->{guard};
Branch: 1 branch
BranchTrueFalseTotal
unless $lock->{"guard"} 4 4 8
1898 8 $guard = $lock->{guard};
1899 }
1900  
1901 139 $self->_start_flight($c, $id, $key, $options, $guard);
1902  
1903 139 return 0;
1904 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1905  
1906 # Purpose: Register this request as the builder for a key.
1907 # Entry criteria: No flight exists for $id.
1908 # Exit status: $self.
1909 # Side effects: Adds the flight, stores it in the stash, and arms a timer
1910 # that releases it if the action never finishes.
1911 139 ▶sub _start_flight :Private {
Subroutine _start_flight: called CC=1 SCAR=0.0
1912 139 my ($self, $c, $id, $key, $options, $guard) = @_;
1913  
1914 139 my $timeout = _lock_timeout($options);
1915 139 my $flight = {
1916 id => $id,
1917 key => $key,
1918 deadline => Time::HiRes::time() + $timeout,
1919 waiters => {},
1920 lock => $guard,
1921 };
1922  
1923 # Do not keep the key reserved for ever if the action never finishes.
1924 # Capture the app, not $c, so the timer does not keep the controller.
1925 139 my $app = $c->app;
1926 139 ▶ $flight->{timer} = Mojo::IOLoop->timer($timeout => sub { $self->_expire_flight($app, $flight) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1927  
1928 139 $self->{inflight}{$id} = $flight;
1929 139 $c->stash->{$STASH_FLIGHT} = $flight;
1930 139 $self->_log($app, debug => 'log_building', {key => $key});
1931  
1932 139 return $self;
1933 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1934  
1935 # Purpose: Hold a second request for the same key until the first
1936 # one has finished.
1937 # Entry criteria: $flight is the in-flight build this request joins.
1938 # Exit status: 1 (the plugin will answer this request).
1939 # Side effects: Suppresses automatic rendering; arms a give-up timer.
1940 14 ▶sub _join_flight :Private {
Subroutine _join_flight: called CC=4 SCAR=14.3
1941 14 my ($self, $c, $flight) = @_;
1942  
1943 14 my $id = refaddr($c);
1944 14 ▶ return 1 if $flight->{waiters}{$id} || $c->stash->{$STASH_FINISHED};
Branch: 1 branch
BranchTrueFalseTotal
if $flight->{"waiters"}{$id} or $c->stash->{$STASH_FINISHED} 0 14 14
Condition33%1/3
$flight->{"waiters"}{$id} or $c->stash->{$STASH_FINISHED}
l!l&&r!l&&!r
0014
MC/DC0%0/2
$flight->{"waiters"}{$id} or $c->stash->{$STASH_FINISHED}
$flight->{"waiters"}{$id} $c->stash->{$STASH_FINISHED}
Truth table33%1/3
A or B
A= $flight->{"waiters"}{$id}B= $c->stash->{$STASH_FINISHED}
ABresult
1X1
011
000
1945  
1946 # The response has to be finished later, so suppress automatic rendering
1947 14 $c->stash->{$STASH_WAITER} = 1;
1948 14 $c->render_later;
1949  
1950 # Every waiter gets at least one tick, even past the deadline
1951 14 my $remaining = $flight->{deadline} - Time::HiRes::time();
1952 14 ▶ $remaining = $MIN_WAITER_DELAY if $remaining < $MIN_WAITER_DELAY;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining < $MIN_WAITER_DELAY 0 14 14
1953  
1954 $flight->{waiters}{$id} = {
1955 c => $c,
1956 14 ▶ timer => Mojo::IOLoop->timer($remaining => sub { $self->_expire_waiter($flight, $id) }),
Subroutine __ANON__: called CC=1 SCAR=0.0
1957 };
1958 14 $self->_log($c->app, debug => 'log_waiting', {key => $flight->{key}});
1959  
1960 14 return 1;
1961 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1962  
1963 # Purpose: Give up on one waiter whose deadline passed.
1964 # Entry criteria: Called from the waiter's timer.
1965 # Exit status: $self.
1966 # Side effects: Removes the waiter and answers it with a 503.
1967 1 ▶sub _expire_waiter :Private {
Subroutine _expire_waiter: called CC=4 SCAR=14.8
1968 1 my ($self, $flight, $id) = @_;
1969  
1970 1 my $waiter = delete($flight->{waiters}{$id});
1971 1 ▶ my $c = $waiter ? $waiter->{c} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$waiter ? : 1 0 1
1972 1 ▶ if ($c && !$c->stash->{$STASH_FINISHED}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c and not $c->stash->{$STASH_FINISHED}) 1 0 1
Condition33%1/3
$c and not $c->stash->{$STASH_FINISHED}
!ll&&!rl&&r
001
MC/DC0%0/2
$c and not $c->stash->{$STASH_FINISHED}
$c not $c->stash->{$STASH_FINISHED}
Truth table33%1/3
A and not(B)
A= $cB= not $c->stash->{$STASH_FINISHED}
ABresult
0X0
100
111
1973 1 $self->_log($c->app, debug => 'log_gave_up');
1974 1 $self->_service_unavailable($c);
1975 }
1976  
1977 1 return $self;
1978 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1979  
1980 # Purpose: Wait for a request in another worker that holds the
1981 # shared lock. The builder cannot notify us, so poll the
1982 # cache until the entry appears or the lock is gone.
1983 # Entry criteria: The lock backend reported the key as held elsewhere.
1984 # Exit status: 1 (the plugin will answer this request).
1985 # Side effects: Suppresses automatic rendering; installs a recurring
1986 # timer that ends itself.
1987 10 ▶sub _join_shared_lock :Private {
Subroutine _join_shared_lock: called CC=1 SCAR=0.0
1988 10 my ($self, $c, $options, $key, $cache) = @_;
1989  
1990 10 $c->stash->{$STASH_WAITER} = 1;
1991 10 $c->render_later;
1992  
1993 10 my $deadline = Time::HiRes::time() + _lock_timeout($options);
1994 10 $self->_log($c->app, debug => 'log_waiting_worker', {key => $key});
1995  
1996 10 my ($poll, $done);
1997 22 ▶ $poll = Mojo::IOLoop->recurring($SHARED_POLL_INTERVAL => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
1998 22 ▶ return if $done;
Branch: 1 branch
BranchTrueFalseTotal
if $done 0 22 22
1999  
2000 # undef means "keep waiting"; anything else ends the poll
2001 22 ▶ my $outcome = $self->_poll_shared_lock($c, $key, $cache, $deadline) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $outcome = $self->_poll_shared_lock($c, $key, $cache, $deadline) or return 10 12 22
2002 10 $done = 1;
2003 10 Mojo::IOLoop->remove($poll);
2004 10 ▶ $self->_answer_waiter($c->app, $c, $outcome->{entry}) unless $outcome->{abandoned};
Branch: 1 branch
BranchTrueFalseTotal
unless $outcome->{"abandoned"} 10 0 10
2005 10 });
2006  
2007 10 return 1;
2008 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2009  
2010 # Purpose: One poll of a cross-worker wait.
2011 # Entry criteria: Called from _join_shared_lock's timer.
2012 # Exit status: undef to keep polling; {abandoned => 1} if the request
2013 # was finished elsewhere; otherwise {entry => $entry},
2014 # where a missing entry means "answer with a 503".
2015 # Side effects: May take and release the shared lock; logs.
2016 22 ▶sub _poll_shared_lock :Private {
Subroutine _poll_shared_lock: called CC=7 SCAR=19.7
2017 22 my ($self, $c, $key, $cache, $deadline) = @_;
2018  
2019 22 my $app = $c->app;
2020 22 ▶ return {abandoned => 1} if $c->stash->{$STASH_FINISHED};
Branch: 1 branch
BranchTrueFalseTotal
if $c->stash->{$STASH_FINISHED} 0 22 22
2021  
2022 22 my $entry = $self->_lookup_entry($c, $cache, $key, 0)->{entry};
2023 22 ▶ if ($entry) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry) 6 16 22
2024 6 $self->_log($app, debug => 'log_filled_elsewhere');
2025 6 return {entry => $entry};
2026 }
2027  
2028 16 ▶ if (Time::HiRes::time() >= $deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Time::HiRes::time() >= $deadline) 2 14 16
2029 2 $self->_log($app, debug => 'log_gave_up_worker');
2030 2 return {};
2031 }
2032  
2033 # If the lock can be taken, the builder has finished. Hold it while
2034 # checking again so that a new builder cannot start in between.
2035 14 my $lock = $self->_acquire_lock($key);
2036 14 ▶ return undef if $lock->{busy};
Branch: 1 branch
BranchTrueFalseTotal
if $lock->{"busy"} 12 2 14
2037 2 ▶ if (!$lock->{guard}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($lock->{"guard"}) 0 2 2
2038 0 $self->_log($app, error => 'log_lock_failed', {error => $lock->{error}});
2039 0 return {};
2040 }
2041  
2042 2 my $late = $self->_lookup_entry($c, $cache, $key, 0)->{entry};
2043 2 $self->_release_lock_logged($app, $lock->{guard});
2044 2 ▶ $self->_log($app, debug => $late ? 'log_filled_elsewhere' : 'log_not_cached_elsewhere');
Branch: 1 branch
BranchTrueFalseTotal
$late ? : 0 2 2
2045  
2046 2 return {entry => $late};
2047 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2048  
2049 # Purpose: Release a flight whose builder did not finish in time.
2050 # Entry criteria: Called from the flight's timer.
2051 # Exit status: $self.
2052 # Side effects: Logs, then answers the waiters with a 503 and releases
2053 # the shared lock.
2054 4 ▶sub _expire_flight :Private {
Subroutine _expire_flight: called CC=2 SCAR=7.0
2055 4 my ($self, $app, $flight) = @_;
2056  
2057 4 ▶ if ($self->_is_current_flight($flight)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_current_flight($flight)) 4 0 4
2058 4 $self->_log($app, debug => 'log_flight_expired');
2059 4 $self->_release_flight($app, $flight, undef);
2060 }
2061  
2062 4 return $self;
2063 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2064  
2065 # Purpose: Finish every request waiting for this key. With a stored
2066 # entry they are served it; without one (a failed or
2067 # uncacheable response) they are told to retry rather than
2068 # each running the action, which is what single-flight is
2069 # meant to prevent.
2070 # Entry criteria: $flight was started by _start_flight.
2071 # Exit status: $self.
2072 # Side effects: Removes the flight and its timers; answers waiters;
2073 # releases the shared lock.
2074 143 ▶sub _release_flight :Private {
Subroutine _release_flight: called CC=7 SCAR=19.5
2075 143 my ($self, $app, $flight, $entry) = @_;
2076  
2077 # A flight is only released once, by whichever of the finished response
2078 # and the timeout comes first
2079 143 ▶ return $self unless $self->_is_current_flight($flight);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_is_current_flight($flight) 4 139 143
2080  
2081 139 delete($self->{inflight}{$flight->{id}});
2082 139 ▶ Mojo::IOLoop->remove($flight->{timer}) if defined($flight->{timer});
Branch: 1 branch
BranchTrueFalseTotal
if defined $flight->{"timer"} 139 0 139
2083  
2084 139 my @waiters = values %{$flight->{waiters}};
2085 139 $flight->{waiters} = {};
2086  
2087 139 for my $waiter (@waiters) {
2088 13 ▶ Mojo::IOLoop->remove($waiter->{timer}) if defined($waiter->{timer});
Branch: 1 branch
BranchTrueFalseTotal
if defined $waiter->{"timer"} 13 0 13
2089 13 ▶ $self->_answer_waiter($app, $waiter->{c}, $entry,
Branch: 1 branch
BranchTrueFalseTotal
$entry ? : 8 5 13
2090 $entry ? 'log_serving_waiter' : 'log_uncacheable_flight');
2091 }
2092  
2093 139 my $guard = delete($flight->{lock});
2094 139 ▶ $self->_release_lock_logged($app, $guard) if $guard;
Branch: 1 branch
BranchTrueFalseTotal
if $guard 4 135 139
2095  
2096 139 return $self;
2097 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2098  
2099 # Purpose: Check that a flight is still the one registered for its
2100 # key, rather than one released earlier.
2101 # Entry criteria: $flight is a flight hash.
2102 # Exit status: 1 or 0.
2103 # Side effects: None.
2104 147 ▶sub _is_current_flight :Private {
Subroutine _is_current_flight: called CC=3 SCAR=11.0
2105 147 my ($self, $flight) = @_;
2106  
2107 147 my $current = $self->{inflight}{$flight->{id}};
2108 147 ▶ return ($current && (refaddr($current) == refaddr($flight))) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$current && builtin::refaddr($current) == builtin::refaddr($flight) ? : 143 4 147
Condition66%2/3
$current and builtin::refaddr($current) == builtin::refaddr($flight)
!ll&&!rl&&r
40143
MC/DC50%1/2
$current and builtin::refaddr($current) == builtin::refaddr($flight)
$current builtin::refaddr($current) == builtin::refaddr($flight)
Truth table66%2/3
A and B
A= $currentB= builtin::refaddr($current) == builtin::refaddr($flight)
ABresult
0X0
100
111
2109 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2110  
2111 # Purpose: Finish a request that was waiting for another one.
2112 # Entry criteria: $entry is the stored entry, or undef for "retry later";
2113 # $note is an optional log key.
2114 # Exit status: $self.
2115 # Side effects: Replays the entry or sends a 503; logs failures. Skips
2116 # requests that are already finished.
2117 23 ▶sub _answer_waiter :Private {
Subroutine _answer_waiter: called CC=6 SCAR=18.5
2118 23 my ($self, $app, $c, $entry, $note) = @_;
2119  
2120 # A client that went away, or was answered by a timeout, needs nothing
2121 23 ▶ if ($c && !$c->stash->{$STASH_FINISHED}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c and not $c->stash->{$STASH_FINISHED}) 23 0 23
Condition33%1/3
$c and not $c->stash->{$STASH_FINISHED}
!ll&&!rl&&r
0023
MC/DC0%0/2
$c and not $c->stash->{$STASH_FINISHED}
$c not $c->stash->{$STASH_FINISHED}
Truth table33%1/3
A and not(B)
A= $cB= not $c->stash->{$STASH_FINISHED}
ABresult
0X0
100
111
2122 23 ▶ $self->_log($app, debug => $note) if $note;
Branch: 1 branch
BranchTrueFalseTotal
if $note 13 10 23
2123 23 ▶ my $ok = eval { $entry ? _replay_entry($c, $entry) : $self->_service_unavailable($c); 1 };
Branch: 1 branch
BranchTrueFalseTotal
$entry ? : 14 9 23
2124 23 ▶ $self->_log($app, error => 'log_finish_waiter_failed', {error => $@}) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 23 23
2125 }
2126  
2127 23 return $self;
2128 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2129  
2130 # Purpose: Send a cached entry as this request's response.
2131 # Entry criteria: $entry has body, and optionally status and headers.
2132 # Exit status: 1.
2133 # Side effects: Replaces status, stored headers and body; adds
2134 # X-Cache: HIT; finishes the response.
2135 77 ▶sub _replay_entry :Private {
Subroutine _replay_entry: called CC=5 SCAR=16.4
2136 77 my ($c, $entry) = @_;
2137  
2138 77 my $res = $c->res;
2139 77 my $headers = $res->headers;
2140 77 ▶ $res->code($entry->{status} || $HTTP_OK);
Condition33%1/3
$entry->{'status'} || $HTTP_OK
l!l&&r!l&&!r
7700
MC/DC0%0/2
$entry->{'status'} || $HTTP_OK
$entry->{'status'} $HTTP_OK
Truth table33%1/3
A || B
A= $entry->{'status'}B= $HTTP_OK
ABresult
1X1
011
000
2141  
2142 # The first stored value replaces whatever the action set; later values
2143 # of the same header are added, so multi-valued headers survive
2144 77 my %seen;
2145 77 ▶ for my $pair (@{$entry->{headers} || []}) {
Condition50%1/2
$entry->{'headers'} || []
l!l
770
MC/DC0%0/1
$entry->{'headers'} || []
$entry->{'headers'}
Truth table50%1/2
A
A= $entry->{'headers'}
Aresult
11
00
2146 150 my ($name, $value) = @$pair;
2147 150 ▶ $headers->remove($name) unless $seen{lc($name)}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{lc $name}++ 150 0 150
2148 150 $headers->add($name => $value);
2149 }
2150  
2151 77 $res->body($entry->{body});
2152 77 $headers->header($X_CACHE => $HIT);
2153 77 $c->stash->{$STASH_FROM_CACHE} = 1;
2154  
2155 # Finish the response; the action can just return now
2156 77 $c->rendered;
2157  
2158 77 return 1;
2159 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2160  
2161 # Purpose: Tell a waiting client to retry shortly.
2162 # Entry criteria: $c has not been finished.
2163 # Exit status: 1.
2164 # Side effects: Sends 503 with Retry-After and the retry_later text,
2165 # encoded as UTF-8 so a translated message is safe.
2166 10 ▶sub _service_unavailable :Private {
Subroutine _service_unavailable: called CC=1 SCAR=0.0
2167 10 my ($self, $c) = @_;
2168  
2169 10 my $res = $c->res;
2170 10 my $headers = $res->headers;
2171 10 $res->code($HTTP_UNAVAILABLE);
2172 10 $headers->content_type('text/plain; charset=UTF-8');
2173 10 $headers->header('Cache-Control' => 'no-store');
2174 10 $headers->header('Retry-After' => $RETRY_AFTER);
2175 10 $headers->header($X_CACHE => $MISS);
2176 10 $res->body(encode('UTF-8', $self->i18n('retry_later')));
2177 10 $c->rendered;
2178  
2179 10 return 1;
2180 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2181  
2182 # Purpose: The effective wait limit for this response.
2183 # Entry criteria: $options may hold an unvalidated stash override.
2184 # Exit status: A positive number of seconds; the default when the
2185 # value is missing or unusable.
2186 # Side effects: None.
2187 149 ▶sub _lock_timeout :Private {
Subroutine _lock_timeout: called CC=3 SCAR=12.5
2188 149 my $options = shift;
2189  
2190 149 my $timeout = $options->{cache_lock_timeout};
2191 149 ▶ return (defined($timeout) && _option_valid('cache_lock_timeout', $timeout)) ? $timeout + 0 : $DEFAULT_LOCK_TIMEOUT;
Branch: 1 branch
BranchTrueFalseTotal
defined $timeout && _option_valid('cache_lock_timeout', $timeout) ? : 149 0 149
Condition33%1/3
defined $timeout and _option_valid("cache_lock_timeout", $timeout)
!ll&&!rl&&r
00149
MC/DC0%0/2
defined $timeout and _option_valid("cache_lock_timeout", $timeout)
defined $timeout _option_valid("cache_lock_timeout", $timeout)
Truth table33%1/3
A and B
A= defined $timeoutB= _option_valid("cache_lock_timeout", $timeout)
ABresult
0X0
100
111
2192 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2193  
2194 # Purpose: Call the lock backend's acquire(). A backend may die, so
2195 # exceptions become errors and the caller can fall back to
2196 # a per-worker flight rather than breaking the request.
2197 # Entry criteria: $self->{lock} is set.
2198 # Exit status: {guard, error, busy}: busy is true when another process
2199 # holds the lock and nothing went wrong.
2200 # Side effects: Whatever the backend does.
2201 32 ▶sub _acquire_lock :Private {
Subroutine _acquire_lock: called CC=6 SCAR=17.9
2202 32 my ($self, $key) = @_;
2203  
2204 32 my ($guard, $error);
2205 32 my $ok = eval { ($guard, $error) = $self->{lock}->acquire($key); 1 };
2206 32 ▶ $error = trim("$@") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 30 32
2207 32 ▶ $guard = undef unless $ok && $guard;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok and $guard 26 6 32
Condition100%3/3
$ok and $guard
!ll&&!rl&&r
2246
MC/DC100%2/2
$ok and $guard
$ok $guard
Truth table100%3/3
A and B
A= $okB= $guard
ABresult
0X0
100
111
2208  
2209 32 ▶ return {guard => $guard, error => $error, busy => (!$guard && !defined($error)) ? 1 : 0};
Branch: 1 branch
BranchTrueFalseTotal
!($guard || defined $error) ? : 22 10 32
Condition100%3/3
$guard || defined $error
l!l&&r!l&&!r
6422
MC/DC100%2/2
$guard || defined $error
$guard defined $error
Truth table100%3/3
A || B
A= $guardB= defined $error
ABresult
1X1
011
000
2210 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2211  
2212 # Purpose: Call the lock backend's release(), normalising its
2213 # answer.
2214 # Entry criteria: $guard came from _acquire_lock.
2215 # Exit status: {ok => 1} or {ok => 0, error => $text}. A backend that
2216 # returns nothing is treated as having released the lock.
2217 # Side effects: Whatever the backend does.
2218 6 ▶sub _release_lock :Private {
Subroutine _release_lock: called CC=5 SCAR=19.6
2219 6 my ($self, $guard) = @_;
2220  
2221 6 my ($released, $error);
2222 6 my $called = eval { ($released, $error) = $self->{lock}->release($guard); 1 };
2223  
2224 6 ▶ return !$called ? {ok => 0, error => trim("$@")}
Branch: 2 branches
BranchTrueFalseTotal
!$called ? : 0 6 6
!defined($released) || $released ? : 6 0 6
Condition16%1/6
not defined $released or $released
l!l&&r!l&&!r
060
$error // $self->i18n("unknown_error")
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $released or $released
not defined $released $released
MC/DC0%0/2
$error // $self->i18n("unknown_error")
$error $self->i18n("unknown_error")
Truth table33%1/3
not(A) or B
A= not defined $releasedB= $released
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= $errorB= $self->i18n("unknown_error")
ABresult
1X1
011
000
2225 : (!defined($released) || $released) ? {ok => 1}
2226 : {ok => 0, error => $error // $self->i18n('unknown_error')};
2227 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2228  
2229 # Purpose: Release a shared lock, logging a failure.
2230 # Entry criteria: $guard came from _acquire_lock.
2231 # Exit status: $self.
2232 # Side effects: Releases the lock; logs at error level on failure.
2233 6 ▶sub _release_lock_logged :Private {
Subroutine _release_lock_logged: called CC=2 SCAR=7.0
2234 6 my ($self, $app, $guard) = @_;
2235  
2236 6 my $result = $self->_release_lock($guard);
2237 6 ▶ $self->_log($app, error => 'log_unlock_failed', {error => $result->{error}}) unless $result->{ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $result->{"ok"} 0 6 6
2238  
2239 6 return $self;
2240 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2241  
2242 # Purpose: Store a finished response in the cache.
2243 # Entry criteria: $entity is the unencoded body; $code the status.
2244 # Exit status: $self.
2245 # Side effects: Writes the cache; sets X-Cache: MISS if unset; stores
2246 # the entry in the stash for waiting requests; logs.
2247 151 ▶sub _store_in_cache :Private {
Subroutine _store_in_cache: called CC=9 SCAR=23.6
2248 151 my ($self, $c, $options, $entity, $code) = @_;
2249  
2250 151 my $cache = $options->{cache};
2251 151 ▶ return $self unless $cache && ($code == $HTTP_OK)
Branch: 1 branch
BranchTrueFalseTotal
unless $cache and $code == $HTTP_OK and _request_cacheable($c) and _response_cacheable($c->res, $options) 38 113 151
Condition77%7/9
$cache and $code == $HTTP_OK and _request_cacheable($c) and _response_cacheable($c->res, $options)
!ll&&!rl&&r
2018113
$cache and $code == $HTTP_OK and _request_cacheable($c)
!ll&&!rl&&r
200131
$cache and $code == $HTTP_OK
!ll&&!rl&&r
020131
MC/DC50%2/4
$cache and $code == $HTTP_OK and _request_cacheable($c) and _response_cacheable($c->res, $options)
$cache $code == $HTTP_OK _request_cacheable($c) _response_cacheable($c->res, $options)
Truth table60%3/5
A and B and C and D
A= $cacheB= $code == $HTTP_OKC= _request_cacheable($c)D= _response_cacheable($c->res, $options)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2252 && _request_cacheable($c) && _response_cacheable($c->res, $options);
2253  
2254 113 ▶ my $key = $c->stash->{$STASH_KEY} // _cache_key($c, $options);
Condition33%1/3
$c->stash->{$STASH_KEY} // _cache_key($c, $options)
l!l&&r!l&&!r
11300
MC/DC0%0/2
$c->stash->{$STASH_KEY} // _cache_key($c, $options)
$c->stash->{$STASH_KEY} _cache_key($c, $options)
Truth table33%1/3
A // B
A= $c->stash->{$STASH_KEY}B= _cache_key($c, $options)
ABresult
1X1
011
000
2255 113 my $entry = {
2256 body => $entity,
2257 status => $HTTP_OK,
2258 created => time,
2259 headers => _headers_to_store($c->res->headers),
2260 };
2261  
2262 113 ▶ my $duration = $options->{cache_duration} // $DEFAULT_CACHE_DURATION;
Condition33%1/3
$options->{"cache_duration"} // $DEFAULT_CACHE_DURATION
l!l&&r!l&&!r
11300
MC/DC0%0/2
$options->{"cache_duration"} // $DEFAULT_CACHE_DURATION
$options->{"cache_duration"} $DEFAULT_CACHE_DURATION
Truth table33%1/3
A // B
A= $options->{"cache_duration"}B= $DEFAULT_CACHE_DURATION
ABresult
1X1
011
000
2263 113 ▶ if (!eval { $cache->set($key, $entry, $duration); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $cache->set($key, $entry, $duration); 1 } }) 0 113 113
2264 0 $self->_log($c->app, error => 'log_cache_set_failed', {error => $@});
2265 0 return $self;
2266 }
2267  
2268 113 $self->_log($c->app, debug => 'log_cached', {key => $key});
2269 113 my $headers = $c->res->headers;
2270 113 ▶ $headers->header($X_CACHE => $MISS) unless defined($headers->header($X_CACHE));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers->header($X_CACHE) 0 113 113
2271  
2272 # Hand this entry to any request that was waiting for it
2273 113 $c->stash->{$STASH_STORED} = $entry;
2274  
2275 113 return $self;
2276 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2277  
2278 # Purpose: Compute the cache key for this request.
2279 # Entry criteria: $options holds cache_key and vary_by.
2280 # Exit status: The custom key if one applies, else 'buffer:' and an MD5
2281 # of the app class, host, path, query and vary_by values.
2282 # Side effects: Calls a cache_key coderef.
2283 230 ▶sub _cache_key :Private {
Subroutine _cache_key: called CC=9 SCAR=22.7
2284 230 my ($c, $options) = @_;
2285  
2286 230 my $custom = $options->{cache_key};
2287 230 ▶ $custom = $custom->($c) if ref($custom) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $custom eq "CODE" 12 218 230
2288 230 ▶ return $custom if defined($custom) && !ref($custom) && length($custom);
Branch: 1 branch
BranchTrueFalseTotal
if defined $custom and not ref $custom and length $custom 68 162 230
Condition66%4/6
defined $custom and not ref $custom and length $custom
!ll&&!rl&&r
162068
defined $custom and not ref $custom
!ll&&!rl&&r
162068
MC/DC33%1/3
defined $custom and not ref $custom and length $custom
defined $custom not ref $custom length $custom
Truth table50%2/4
A and not(B) and C
A= defined $customB= not ref $customC= length $custom
ABCresult
0XX0
10X0
1100
1111
2289  
2290 162 my $req = $c->req;
2291 162 my $url = $req->url;
2292 162 ▶ my @material = (
Condition40%2/5
($url->host_port // $req->headers->host) // ""
l!l
1620
$url->host_port // $req->headers->host
l!l&&r!l&&!r
01620
MC/DC0%0/2
($url->host_port // $req->headers->host) // ""
$url->host_port $req->headers->host
Truth table33%1/3
A // B
A= $url->host_portB= $req->headers->host
ABresult
1X1
011
000
2293 ref($c->app),
2294 $url->host_port // $req->headers->host // '',
2295 $url->path->to_string,
2296 $url->query->to_string,
2297 );
2298  
2299 # Header names are case-insensitive, so the key uses the lower-cased name
2300 162 ▶ push @material, map { lc($_) . '=' . ($req->headers->header($_) // '') } @{$options->{vary_by} || []};
Condition75%3/4
$req->headers->header($_) // ""
l!l
8678
$options->{'vary_by'} || []
l!l
1620
MC/DC100%1/1
$req->headers->header($_) // ""
$req->headers->header($_)
MC/DC0%0/1
$options->{'vary_by'} || []
$options->{'vary_by'}
Truth table100%2/2
A
A= $req->headers->header($_)
Aresult
11
00
Truth table50%1/2
A
A= $options->{'vary_by'}
Aresult
11
00
2301  
2302 # A digest keeps the key short, driver-safe and free of cookie data.
2303 # md5_sum dies on characters above 255, so hash the UTF-8 bytes.
2304 162 return $KEY_PREFIX . md5_sum(encode('UTF-8', join("\x00", @material)));
2305 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2306  
2307 # Purpose: Decide whether this request may use the cache at all.
2308 # Entry criteria: $c is the current controller.
2309 # Exit status: 1 or 0.
2310 # Side effects: None.
2311 381 ▶sub _request_cacheable :Private {
Subroutine _request_cacheable: called CC=6 SCAR=18.5
2312 381 my $c = shift;
2313  
2314 381 my $req = $c->req;
2315  
2316 # Authenticated responses are per-user, whatever the URL says
2317 return ($ENV{NO_CACHE} || $ENV{NO_STORE}) ? 0
2318 381 ▶ : !$SAFE_METHODS{$req->method} ? 0
Branch: 4 branches
BranchTrueFalseTotal
$ENV{'NO_CACHE'} || $ENV{'NO_STORE'} ? : 0 381 381
!$SAFE_METHODS{$req->method} ? : 4 377 381
$req->headers->authorization ? : 4 373 377
_cache_control_forbids($req->headers->cache_control, \%REQUEST_NO_CACHE) ? : 12 361 373
Condition33%1/3
$ENV{"NO_CACHE"} or $ENV{"NO_STORE"}
l!l&&r!l&&!r
00381
MC/DC0%0/2
$ENV{"NO_CACHE"} or $ENV{"NO_STORE"}
$ENV{"NO_CACHE"} $ENV{"NO_STORE"}
Truth table33%1/3
A or B
A= $ENV{"NO_CACHE"}B= $ENV{"NO_STORE"}
ABresult
1X1
011
000
2319 : $req->headers->authorization ? 0
2320 : _cache_control_forbids($req->headers->cache_control, \%REQUEST_NO_CACHE) ? 0
2321 : 1;
2322 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2323  
2324 # Purpose: Decide whether a finished response may be stored.
2325 # Entry criteria: $res is the response; $options holds vary_by.
2326 # Exit status: 1 or 0.
2327 # Side effects: None.
2328 131 ▶sub _response_cacheable :Private {
Subroutine _response_cacheable: called CC=6 SCAR=18.0
2329 131 my ($res, $options) = @_;
2330  
2331 131 my $headers = $res->headers;
2332  
2333 # The request headers the key covers, plus the coding we vary on anyway
2334 131 ▶ my %allowed = map { lc($_) => 1 } @{$options->{vary_by} || []}, 'accept-encoding';
Condition50%1/2
$options->{'vary_by'} || []
l!l
1310
MC/DC0%0/1
$options->{'vary_by'} || []
$options->{'vary_by'}
Truth table50%1/2
A
A= $options->{'vary_by'}
Aresult
11
00
2335 131 ▶ my @varies = grep { length } map { lc(trim($_)) } split(/,/, $headers->vary // '');
Condition50%1/2
$headers->vary // ""
l!l
1310
MC/DC0%0/1
$headers->vary // ""
$headers->vary
Truth table50%1/2
A
A= $headers->vary
Aresult
11
00
2336  
2337 # Never replay cookies that were meant for one client, nor a response
2338 # that varies on something the key does not cover: it would be served to
2339 # the wrong client
2340 my $cacheable = !$headers->set_cookie
2341 && !_cache_control_forbids($headers->cache_control, \%RESPONSE_NO_STORE)
2342 131 ▶ && !grep { !$allowed{$_} } @varies;
Condition100%6/6
$headers->set_cookie || _cache_control_forbids($headers->cache_control, \%RESPONSE_NO_STORE) || grep({not $allowed{$_};} @varies)
l!l&&r!l&&!r
144113
$headers->set_cookie or _cache_control_forbids($headers->cache_control, \%RESPONSE_NO_STORE)
l!l&&r!l&&!r
68117
MC/DC100%3/3
$headers->set_cookie || _cache_control_forbids($headers->cache_control, \%RESPONSE_NO_STORE) || grep({not $allowed{$_};} @varies)
$headers->set_cookie _cache_control_forbids($headers->cache_control, \%RESPONSE_NO_STORE) grep({not $allowed{$_};} @varies)
Truth table100%4/4
A or B || C
A= $headers->set_cookieB= _cache_control_forbids($headers->cache_control, \%RESPONSE_NO_STORE)C= grep({not $allowed{$_};} @varies)
ABCresult
1XX1
01X1
0011
0000
2343  
2344 131 ▶ return $cacheable ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$cacheable ? : 113 18 131
2345 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2346  
2347 # Purpose: Check a Cache-Control value for forbidding directives.
2348 # Entry criteria: $value is the header or undef; $directives is a set of
2349 # lower-case directive names.
2350 # Exit status: 1 if a listed directive is present (max-age only when
2351 # it is zero), else 0.
2352 # Side effects: None. Mojo::Util::split_header does the parsing, so
2353 # quoted values and "no-cache-foo" are handled correctly.
2354 498 ▶sub _cache_control_forbids :Private {
Subroutine _cache_control_forbids: called CC=7 SCAR=19.5
2355 498 my ($value, $directives) = @_;
2356  
2357 498 my $forbidden = 0;
2358 498 ▶ for my $directive (@{split_header($value // '')}) {
Condition100%2/2
$value // ""
l!l
26472
MC/DC100%1/1
$value // ""
$value
Truth table100%2/2
A
A= $value
Aresult
11
00
2359 28 my ($name, $argument) = (lc($directive->[0]), $directive->[1]);
2360 28 ▶ next unless $directives->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $directives->{$name} 6 22 28
2361 22 ▶ $forbidden = 1 if ($name ne 'max-age') || (defined($argument) && ($argument =~ /^0+$/));
Branch: 1 branch
BranchTrueFalseTotal
if $name ne "max-age" or defined $argument and $argument =~ /^0+$/a 20 2 22
Condition83%5/6
$name ne "max-age" or defined $argument and $argument =~ /^0+$/a
l!l&&r!l&&!r
1642
defined $argument and $argument =~ /^0+$/a
!ll&&!rl&&r
024
MC/DC66%2/3
$name ne "max-age" or defined $argument and $argument =~ /^0+$/a
$name ne "max-age" defined $argument $argument =~ /^0+$/a
Truth table75%3/4
A or B and C
A= $name ne "max-age"B= defined $argumentC= $argument =~ /^0+$/a
ABCresult
1XX1
0111
00X0
0100
2362 }
2363  
2364 498 return $forbidden;
2365 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2366  
2367 # Purpose: Pick the response headers worth storing with an entry.
2368 # Entry criteria: $headers is a Mojo::Headers.
2369 # Exit status: An array reference of [name, value] pairs.
2370 # Side effects: None.
2371 113 ▶sub _headers_to_store :Private {
Subroutine _headers_to_store: called CC=2 SCAR=6.9
2372 113 my $headers = shift;
2373  
2374 113 my @pairs;
2375 113 for my $name (grep { !$UNSTORED_HEADERS{lc($_)} } @{$headers->names}) {
2376 228 push @pairs, map { [$name, $_] } @{$headers->every_header($name)};
2377 }
2378  
2379 113 return \@pairs;
2380 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2381  
2382 # ---------------------------------------------------------------------------
2383 # Modification times
2384 # ---------------------------------------------------------------------------
2385  
2386 # Purpose: The application script's mtime.
2387 # Entry criteria: None.
2388 # Exit status: An epoch, or undef if $0 is not a readable file.
2389 # Side effects: Remembers the answer for the life of the plugin: the
2390 # running code does not change when the file does.
2391 491 ▶sub _script_mtime :Private {
Subroutine _script_mtime: called CC=6 SCAR=19.9
2392 491 my $self = shift;
2393  
2394 491 ▶ if (!exists($self->{script_mtime})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"script_mtime"}) 196 295 491
2395 196 my $script = $0;
2396 196 ▶ my @stat = (defined($script) && length($script) && -f $script) ? stat($script) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $script && length $script && -f $script ? : 196 0 196
Condition33%2/6
defined $script and length $script and -f $script
!ll&&!rl&&r
00196
defined $script and length $script
!ll&&!rl&&r
00196
MC/DC0%0/3
defined $script and length $script and -f $script
defined $script length $script -f $script
Truth table25%1/4
A and B and C
A= defined $scriptB= length $scriptC= -f $script
ABCresult
0XX0
10X0
1100
1111
2397 196 ▶ $self->{script_mtime} = @stat ? $stat[9] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@stat ? : 196 0 196
2398 }
2399  
2400 491 return $self->{script_mtime};
2401 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2402  
2403 # Purpose: The newest mtime of the application and the templates.
2404 # Both Last-Modified and cache invalidation use this, so a
2405 # template edit invalidates a page even though the
2406 # application script has not changed.
2407 # Entry criteria: $c is the current controller.
2408 # Exit status: An epoch, or undef if nothing could be stat()ed.
2409 # Side effects: Caches the answer in the stash for this request, and in
2410 # template_mtime_cache if configured.
2411 554 ▶sub _application_mtime :Private {
Subroutine _application_mtime: called CC=7 SCAR=19.5
2412 554 my ($self, $c) = @_;
2413  
2414 554 my $stash = $c->stash;
2415  
2416 # Once per request: the cache lookup and the replay both ask
2417 554 ▶ if (!exists($stash->{$STASH_MTIME})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $stash->{$STASH_MTIME}) 475 79 554
2418 475 my $cache = $self->{options}{template_mtime_cache};
2419 475 ▶ my $cache_key = $cache ? $self->_template_mtime_cache_key($c) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$cache ? : 23 452 475
2420 475 ▶ my $latest = $cache ? $self->_cached_mtime($c, $cache, $cache_key) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$cache ? : 23 452 475
2421  
2422 # A miss, or no mtime cache at all, means walking the tree
2423 475 ▶ if (!defined($latest)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $latest) 468 7 475
2424 468 $latest = $self->_scan_mtime($c);
2425 468 ▶ $self->_remember_mtime($c, $cache, $cache_key, $latest) if $cache && defined($latest);
Branch: 1 branch
BranchTrueFalseTotal
if $cache and defined $latest 16 452 468
Condition66%2/3
$cache and defined $latest
!ll&&!rl&&r
452016
MC/DC50%1/2
$cache and defined $latest
$cache defined $latest
Truth table66%2/3
A and B
A= $cacheB= defined $latest
ABresult
0X0
100
111
2426 }
2427 475 $stash->{$STASH_MTIME} = $latest;
2428 }
2429  
2430 554 return $stash->{$STASH_MTIME};
2431 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2432  
2433 # Purpose: Read a previously scanned mtime from the mtime cache.
2434 # Entry criteria: $cache understands get().
2435 # Exit status: An epoch, or undef on a miss, junk, or a cache failure.
2436 # Side effects: Logs a failure at debug level.
2437 23 ▶sub _cached_mtime :Private {
Subroutine _cached_mtime: called CC=4 SCAR=13.9
2438 23 my ($self, $c, $cache, $cache_key) = @_;
2439  
2440 23 my $cached = eval { $cache->get($cache_key) };
2441 23 ▶ $self->_log($c->app, debug => 'log_mtime_get_failed', {error => $@}) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 21 23
2442  
2443 23 ▶ return (defined($cached) && ($cached =~ /^\d+$/)) ? $cached : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $cached && $cached =~ /^\d+$/a ? : 7 16 23
Condition66%2/3
defined $cached and $cached =~ /^\d+$/a
!ll&&!rl&&r
1607
MC/DC50%1/2
defined $cached and $cached =~ /^\d+$/a
defined $cached $cached =~ /^\d+$/a
Truth table66%2/3
A and B
A= defined $cachedB= $cached =~ /^\d+$/a
ABresult
0X0
100
111
2444 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2445  
2446 # Purpose: Store a scanned mtime in the mtime cache.
2447 # Entry criteria: $cache understands set(); $latest is an epoch.
2448 # Exit status: $self.
2449 # Side effects: Writes the cache; logs failures at debug level, because
2450 # a broken mtime cache only costs a scan.
2451 16 ▶sub _remember_mtime :Private {
Subroutine _remember_mtime: called CC=4 SCAR=14.6
2452 16 my ($self, $c, $cache, $cache_key, $latest) = @_;
2453  
2454 16 ▶ my $duration = $self->{options}{template_mtime_cache_duration} // $DEFAULT_MTIME_DURATION;
Condition33%1/3
$self->{"options"}{"template_mtime_cache_duration"} // $DEFAULT_MTIME_DURATION
l!l&&r!l&&!r
1600
MC/DC0%0/2
$self->{"options"}{"template_mtime_cache_duration"} // $DEFAULT_MTIME_DURATION
$self->{"options"}{"template_mtime_cache_duration"} $DEFAULT_MTIME_DURATION
Truth table33%1/3
A // B
A= $self->{"options"}{"template_mtime_cache_duration"}B= $DEFAULT_MTIME_DURATION
ABresult
1X1
011
000
2455 16 my $stored = eval { $cache->set($cache_key, $latest, $duration) };
2456 16 ▶ if ($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 2 14 16
elsif (not $stored) { } 0 14 14
2457 2 $self->_log($c->app, debug => 'log_mtime_set_failed', {error => $@});
2458 } elsif (!$stored) {
2459 0 $self->_log($c->app, debug => 'log_mtime_not_stored');
2460 }
2461  
2462 16 return $self;
2463 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2464  
2465 # Purpose: Walk the script and every renderer path for the newest
2466 # mtime.
2467 # Entry criteria: $c is the current controller.
2468 # Exit status: An epoch, or undef.
2469 # Side effects: stat()s every file and directory under the paths.
2470 468 ▶sub _scan_mtime :Private {
Subroutine _scan_mtime: called CC=4 SCAR=14.3
2471 468 my ($self, $c) = @_;
2472  
2473 468 my $latest = $self->_script_mtime;
2474 468 my %seen;
2475 468 ▶ for my $dir (grep { defined($_) && length($_) } @{$c->app->renderer->paths || []}) {
Condition40%2/5
defined $_ && length $_
!ll&&!rl&&r
00468
$c->app->renderer->paths || []
l!l
4680
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
MC/DC0%0/1
$c->app->renderer->paths || []
$c->app->renderer->paths
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
Truth table50%1/2
A
A= $c->app->renderer->paths
Aresult
11
00
2476 468 $latest = _latest_mtime($dir, $latest, \%seen);
2477 }
2478  
2479 468 return $latest;
2480 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2481  
2482 # Purpose: Key for the template mtime cache.
2483 # Entry criteria: $c is the current controller.
2484 # Exit status: A key that changes with the app class, script, script
2485 # mtime and template paths.
2486 # Side effects: None.
2487 23 ▶sub _template_mtime_cache_key :Private {
Subroutine _template_mtime_cache_key: called CC=5 SCAR=17.5
2488 23 my ($self, $c) = @_;
2489  
2490 23 ▶ my @parts = (ref($c->app), $0 // '', $self->_script_mtime // '', map { $_ // '' } @{$c->app->renderer->paths || []});
Condition50%4/8
$0 // ""
l!l
230
$self->_script_mtime // ""
l!l
230
$_ // ""
l!l
230
$c->app->renderer->paths || []
l!l
230
MC/DC0%0/1
$0 // ""
$0
MC/DC0%0/1
$self->_script_mtime // ""
$self->_script_mtime
MC/DC0%0/1
$_ // ""
$_
MC/DC0%0/1
$c->app->renderer->paths || []
$c->app->renderer->paths
Truth table50%1/2
A
A= $0
Aresult
11
00
Truth table50%1/2
A
A= $self->_script_mtime
Aresult
11
00
Truth table50%1/2
A
A= $_
Aresult
11
00
Truth table50%1/2
A
A= $c->app->renderer->paths
Aresult
11
00
2491  
2492 23 return $MTIME_KEY_PREFIX . md5_sum(encode('UTF-8', join("\0", @parts)));
2493 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2494  
2495 # Purpose: Newest mtime in a tree. Directory mtimes are included as
2496 # well as file mtimes: editing a file moves the file's
2497 # mtime, while adding, removing or renaming one moves its
2498 # directory's. stat() follows symlinks, and the seen set
2499 # stops a symlink loop.
2500 # Entry criteria: $path is a path; $latest the best so far or undef;
2501 # $depth how many directories down the walk is (undef at
2502 # the top).
2503 # Exit status: The newer of $latest and anything under $path.
2504 # Side effects: stat()s and reads directories; unreadable ones, and
2505 # those deeper than $MAX_SCAN_DEPTH, are skipped.
2506 842 ▶sub _latest_mtime :Private {
Subroutine _latest_mtime: called CC=12 SCAR=24.9
2507 842 my ($path, $latest, $seen, $depth) = @_;
2508  
2509 842 my @stat = stat($path);
2510 842 ▶ return $latest unless @stat;
Branch: 1 branch
BranchTrueFalseTotal
unless @stat 394 448 842
2511  
2512 448 ▶ $latest = $stat[9] if defined($stat[9]) && (!defined($latest) || ($stat[9] > $latest));
Branch: 1 branch
BranchTrueFalseTotal
if defined $stat[9] and !defined($latest) || $stat[9] > $latest 90 358 448
Condition66%4/6
defined $stat[9] and !defined($latest) || $stat[9] > $latest
!ll&&!rl&&r
035890
not defined $latest or $stat[9] > $latest
l!l&&r!l&&!r
090358
MC/DC33%1/3
defined $stat[9] and !defined($latest) || $stat[9] > $latest
defined $stat[9] not defined $latest $stat[9] > $latest
Truth table50%2/4
A and not(B) or C
A= defined $stat[9]B= not defined $latestC= $stat[9] > $latest
ABCresult
0XX0
1000
11X1
1011
2513 448 ▶ return $latest unless -d _;
Branch: 1 branch
BranchTrueFalseTotal
unless -d _ 276 172 448
2514  
2515 # device:inode identifies a directory however it was reached. Where
2516 # the inode is always 0 (Windows before Perl 5.38) that key would make
2517 # every directory after the first look already seen, so fall back to
2518 # the path, and let the depth limit end a loop through a symlink.
2519 172 ▶ my $id = $stat[1] ? "$stat[0]:$stat[1]" : File::Spec->canonpath($path);
Branch: 1 branch
BranchTrueFalseTotal
$stat[1] ? : 100 72 172
2520 172 ▶ return $latest if $seen->{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$id}++ 2 170 172
2521 170 ▶ $depth //= 0;
Condition100%2/2
$depth //= 0
l!l
9674
MC/DC100%1/1
$depth //= 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
2522 170 ▶ return $latest if $depth >= $MAX_SCAN_DEPTH;
Branch: 1 branch
BranchTrueFalseTotal
if $depth >= $MAX_SCAN_DEPTH 2 168 170
2523  
2524 # autodie makes an unreadable directory an exception; skipping it is the
2525 # right answer for a freshness check, so catch it here
2526 168 ▶ my $dh = eval { opendir(my $handle, $path); $handle } or return $latest;
Branch: 1 branch
BranchTrueFalseTotal
my $dh = eval { do { &Mojolicious::Plugin::Buffer::opendir(my $handle, $path); $handle } } or return $latest 168 0 168
2527 168 for my $entry (File::Spec->no_upwards(readdir($dh))) {
2528 374 $latest = _latest_mtime(File::Spec->catfile($path, $entry), $latest, $seen, $depth + 1);
2529 }
2530 168 eval { closedir($dh) };
2531  
2532 168 return $latest;
2533 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2534  
2535 # Purpose: Resolve the last_modified option to an epoch.
2536 # Entry criteria: $option is 0, 1, an epoch, a date string or a coderef.
2537 # Exit status: An epoch, or undef for "no header".
2538 # Side effects: Calls a coderef; may scan the template tree.
2539 533 ▶sub _resolve_last_modified :Private {
Subroutine _resolve_last_modified: called CC=6 SCAR=17.9
2540 533 my ($self, $option, $c) = @_;
2541  
2542 # A coderef is called once; it cannot return another coderef
2543 533 ▶ my $value = (ref($option) eq 'CODE') ? $option->($c) : $option;
Branch: 1 branch
BranchTrueFalseTotal
ref $option eq 'CODE' ? : 2 531 533
2544  
2545 # 0, undef and references mean "no header"; 1 means "work it out from
2546 # the application and its templates"; digits are an epoch; anything else
2547 # is a date string for Mojo::Date
2548 return (!$value || ref($value)) ? undef
2549 : ($value eq '1') ? $self->_application_mtime($c)
2550 : ($value =~ /^\d+$/) ? $value + 0
2551 533 ▶ : scalar(eval { Mojo::Date->new($value)->epoch });
Branch: 3 branches
BranchTrueFalseTotal
!$value || ref $value ? : 4 529 533
$value eq '1' ? : 475 54 529
$value =~ /^\d+$/a ? : 52 2 54
Condition66%2/3
not $value or ref $value
l!l&&r!l&&!r
40529
MC/DC50%1/2
not $value or ref $value
not $value ref $value
Truth table66%2/3
not(A) or B
A= not $valueB= ref $value
ABresult
1X1
011
000
2552 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2553  
2554 # ---------------------------------------------------------------------------
2555 # HTML optimisation
2556 # ---------------------------------------------------------------------------
2557  
2558 # Purpose: Optimise an HTML body.
2559 # Entry criteria: $options->{optimise_content} is the level.
2560 # Exit status: The optimised body; the squashed body if HTML::Packer is
2561 # missing or fails.
2562 # Side effects: Logs a packer failure. Protected so a subclass can use
2563 # another minifier.
2564 54 ▶sub _optimise :Protected {
Subroutine _optimise: called CC=7 SCAR=20.3
2565 54 my ($self, $body, $c, $options) = @_;
2566  
2567 54 ▶ my $level = $options->{optimise_content} || 0;
Condition50%1/2
$options->{'optimise_content'} || 0
l!l
540
MC/DC0%0/1
$options->{'optimise_content'} || 0
$options->{'optimise_content'}
Truth table50%1/2
A
A= $options->{'optimise_content'}
Aresult
11
00
2568 54 ▶ return $body unless $level;
Branch: 1 branch
BranchTrueFalseTotal
unless $level 0 54 54
2569  
2570 54 $body = _squash($body);
2571 54 ▶ if ($options->{rewrite_links}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"rewrite_links"}) 48 6 54
2572 48 my $rewritten = _rewrite_links($body, $c);
2573 48 ▶ $body = $rewritten if defined($rewritten);
Branch: 1 branch
BranchTrueFalseTotal
if defined $rewritten 48 0 48
2574 }
2575  
2576 # Without HTML::Packer comments and embedded CSS/JavaScript cannot be
2577 # minified, but the white-space squashing above is still worth keeping
2578 54 ▶ return $body unless _module_available('HTML::Packer');
Branch: 1 branch
BranchTrueFalseTotal
unless _module_available("HTML::Packer") 27 27 54
2579  
2580 27 my $minified = eval { $self->_pack($body, $level) };
2581 27 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 27 27
2582 0 $self->_log($c->app, error => 'log_packer_failed', {error => $error});
2583 0 return $body;
2584 }
2585  
2586 27 return $minified;
2587 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2588  
2589 # Purpose: Run HTML::Packer over a body.
2590 # Entry criteria: HTML::Packer is available; $level is 1 or 2.
2591 # Exit status: The minified HTML.
2592 # Side effects: Creates and keeps one HTML::Packer per plugin instance;
2593 # may die (the caller catches it).
2594 27 ▶sub _pack :Private {
Subroutine _pack: called CC=4 SCAR=13.9
2595 27 my ($self, $body, $level) = @_;
2596  
2597 27 my $packer_options = {
2598 remove_comments => 1,
2599 remove_newlines => 0,
2600 do_stylesheet => 'minify',
2601 };
2602  
2603 27 ▶ if ($level >= $OPTIMISE_AGGRESSIVE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($level >= $OPTIMISE_AGGRESSIVE) 2 25 27
2604 # Strip the <!-- ... //--> hiding technique, which the JavaScript
2605 # minifier would otherwise treat as code. [^>] keeps each match
2606 # inside the <script> tag: .*? could run on through the page and
2607 # leave the text of an HTML comment showing.
2608 2 $packer_options->{do_javascript} = 'best';
2609 2 $body =~ s/(<script[^>]*+>)\s*+<!--/$1/gi;
2610 2 $body =~ s/\/\/-->\s*+<\/script>/<\/script>/gi;
2611 2 $body =~ s/(<script[^>]*+>)\s++/$1/gi;
2612 }
2613  
2614 # The packer holds no per-document state, so one per plugin will do
2615 27 ▶ $self->{packer} //= HTML::Packer->init;
Condition66%2/3
$self->{"packer"} //= "HTML::Packer"->init
l!l&&r!l&&!r
9180
MC/DC0%0/2
$self->{"packer"} //= "HTML::Packer"->init
$self->{"packer"} "HTML::Packer"->init
Truth table66%2/3
A //= B
A= $self->{"packer"}B= "HTML::Packer"->init
ABresult
1X1
011
000
2616 27 my $result = $self->{packer}->minify(\$body, $packer_options);
2617  
2618 27 ▶ return ($level >= $OPTIMISE_AGGRESSIVE) ? _merge_document_writes($result) : $result;
Branch: 1 branch
BranchTrueFalseTotal
$level >= $OPTIMISE_AGGRESSIVE ? : 2 25 27
2619 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2620  
2621 # Purpose: Turn document.write("a"); document.write("b") into
2622 # document.write("a"+"b").
2623 # Entry criteria: $html is minified HTML.
2624 # Exit status: The rewritten HTML. Each substitution replaces
2625 # ");document.write(" with "+", so the body shrinks every
2626 # time and the loop always ends.
2627 # Side effects: None. Only <script type="text/javascript"> blocks are
2628 # touched, their tag is kept as written, and nothing may
2629 # cross a </script>: writes in different scripts, or in a
2630 # script of another type such as a template, stay apart.
2631 2 ▶sub _merge_document_writes :Private {
Subroutine _merge_document_writes: called CC=2 SCAR=6.9
2632 2 my $html = shift;
2633  
2634 2 ▶ 1 while $html =~ s{
Branch: 1 branch
BranchTrueFalseTotal
$html =~ s[ (<script\s+type\s*=\s*"text/javascript"\s*>) # $1: the opening tag ((?:(?!</script>).)*?) # $2: code before the writes document\.write\(((?:(?!</script>)[^;])*?)\);\s*+ # $3: first argument document\.write\(((?:(?!</script>)[^;])*?)\) # $4: second argument ][$1$2document.write($3+$4)]agisx and do { '???' } 1 2 3
2635 (<script\s+type\s*=\s*"text/javascript"\s*>) # $1: the opening tag
2636 ((?:(?!</script>).)*?) # $2: code before the writes
2637 document\.write\(((?:(?!</script>)[^;])*?)\);\s*+ # $3: first argument
2638 document\.write\(((?:(?!</script>)[^;])*?)\) # $4: second argument
2639 }{$1${2}document.write($3+$4)}gisx;
2640  
2641 2 return $html;
2642 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2643  
2644 # Purpose: Reduce output by removing superfluous white space. This
2645 # is the set of substitutions used by CGI::Buffer and
2646 # FCGI::Buffer, with three corrections: a "+" at the start
2647 # of a line is no longer deleted, the content of pre,
2648 # textarea, script and style elements is left alone, and
2649 # a visible space between two inline elements is kept.
2650 # Every pattern runs in linear time: one that starts with
2651 # white space starts only at the first character of a run
2652 # ((?<!\s)) and never gives any of it back (\s++), and one
2653 # that looks for the end of an element cannot run past
2654 # the next tag.
2655 # Entry criteria: $body is HTML.
2656 # Exit status: The squashed HTML.
2657 # Side effects: None.
2658 54 ▶sub _squash :Private {
Subroutine _squash: called CC=1 SCAR=0.0
2659 54 my $body = shift;
2660  
2661 54 my $vault = _protect_verbatim(\$body);
2662  
2663 # Any run of white space that holds a line break becomes that one line
2664 # break. One pattern, so CRLF ("\r\n <") loses its indentation as
2665 # well as LF does: the old (\s+|\r)\n alternative consumed the "\n" and
2666 # left the indentation after it behind.
2667 54 $body =~ s{
2668 (?<![^\S\n]) # start only at the beginning of a white space run
2669 [^\S\n]*+ # spaces, tabs and \r before the line break
2670 \n
2671 \s*+ # blank lines and indentation after it
2672 }{\n}gx;
2673 54 $body =~ s/\<\/div\>\s+\<div/\<\/div\>\<div/gi;
2674 54 $body =~ s/(?:<div>\s++|(?<!\s)\s++<div>)/<div>/gi;
2675 54 $body =~ s/(?<!\s)\s++<\/div>/<\/div>/gi;
2676 54 $body =~ s/(?:(?<!\s)\s++<p>|<p>\s++)/<p>/i;
2677 54 $body =~ s/(?:(?<!\s)\s++<\/p>|<\/p>\s++)/<\/p>/gi;
2678 54 $body =~ s/<html>\s+<head>/<html><head>/i;
2679 54 $body =~ s/(?<!\s)\s*+<\/head>\s++<body>\s*+/<\/head><body>/i;
2680 54 $body =~ s/<html>\s+<body>/<html><body>/i;
2681 54 $body =~ s/<body>\s+/<body>/i;
2682 54 $body =~ s/(?<!\s)\s++<\/html/<\/html/i;
2683 54 $body =~ s/(?<!\s)\s++<\/body/<\/body/i;
2684 54 $body =~ s/\<p\>\s/\<p\>/gi;
2685 54 $body =~ s/\<\/p\>\s\<p\>/\<\/p\>\<p\>/gi;
2686 54 $body =~ s/\<\/tr\>\s\<tr\>/\<\/tr\>\<tr\>/gi;
2687 54 $body =~ s/\<\/td\>\s\<\/tr\>/\<\/td\>\<\/tr\>/gi;
2688 54 $body =~ s/\<\/td\>\s*\<td\>/\<\/td\>\<td\>/gi;
2689 54 $body =~ s/\<\/tr\>\s\<\/table\>/\<\/tr\>\<\/table\>/gi;
2690 54 $body =~ s/\<br\s?\/\>\s?\<p\>/\<p\>/gi;
2691 54 $body =~ s/\<br\>\s/\<br\>/gi;
2692 54 $body =~ s/(?<!\s)\s++<br/<br/gi;
2693 54 $body =~ s/\<br\s?\/\>\s/\<br \/>/gi;
2694 54 $body =~ s/[ \t]+/ /g; # Don't use \s+, it would join lines
2695 54 $body =~ s/\s\<p\>/\<p\>/gi;
2696 54 $body =~ s/\s\<script/\<script/gi;
2697 54 $body =~ s/(<script>\s|\s<script>)/<script>/gi;
2698 54 $body =~ s/(<\/script>\s|\s<\/script>)/<\/script>/gi;
2699 54 $body =~ s/\<td\>\s/\<td\>/gi;
2700  
2701 # The link cannot leave its quotes, so these cannot span tags or search
2702 # the rest of the page
2703 54 $body =~ s{
2704 (?<!\s)\s++ # a whole run of white space
2705 <a\shref="([^"]*+)"> # $1: the link
2706 \s?
2707 }{ <a href="$1">}gix;
2708 54 $body =~ s{
2709 \s?
2710 <a\shref=\s"([^"]*+)"> # $1: the link
2711 }{ <a href="$1">}gix;
2712 54 $body =~ s/(?<!\s)\s++<\/a>\s+/<\/a> /gi;
2713 54 $body =~ s/(?:\s?<hr>\s++|(?<!\s)\s++<hr>\s?)/<hr>/gi;
2714 54 $body =~ s/<\/li>\s+<li>/<\/li><li>/gi;
2715 54 $body =~ s/<\/li>\s+<\/ul>/<\/li><\/ul>/gi;
2716 54 $body =~ s/<ul>\s+<li>/<ul><li>/gi;
2717 54 $body =~ s/(?<!\s)\s++<\/li>/<\/li>/gi;
2718 54 $body =~ s/\<\/option\>\s+\<option/\<\/option\>\<option/gi;
2719  
2720 # A title cannot contain a tag, so [^<] stops each unterminated <title>
2721 # from being searched to the end of the page
2722 54 $body =~ s{<title>\s*+([^<]*+)</title>}{
2723 23 my $title = $1;
2724 23 $title =~ s/(?<!\s)\s++\z//;
2725 23 "<title>$title</title>"
2726 }ie;
2727 54 $body =~ s/<\/center>\s+<center>/ /gi;
2728  
2729 54 return _restore_verbatim($body, $vault);
2730 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2731  
2732 # Purpose: Swap the content of white-space-sensitive elements for
2733 # placeholders, so the squasher cannot change it.
2734 # Entry criteria: $body_ref refers to the HTML.
2735 # Exit status: {marker, saved}: what _restore_verbatim needs.
2736 # Side effects: Rewrites $$body_ref in place. The tags themselves stay,
2737 # so white space around them is still squashed.
2738 54 ▶sub _protect_verbatim :Private {
Subroutine _protect_verbatim: called CC=5 SCAR=16.1
2739 54 my $body_ref = shift;
2740  
2741 # A marker that does not already occur, so restoring is exact. NUL
2742 # never matches \s, so no squash pattern can touch a placeholder.
2743 54 my $marker = "\x00MPB";
2744 54 ▶ $marker .= "\x00" while index($$body_ref, $marker) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
index($$body_ref, $marker) != -1 and do { $marker .= "\000" } 2 54 56
2745  
2746 # One pass along the page. An element whose closing tag is missing
2747 # is searched for once: if no </pre> follows one <pre>, none follows a
2748 # later one either, so every unterminated element cannot each search
2749 # to the end of the page.
2750 54 my (@saved, %unclosed);
2751 54 my ($out, $from) = ('', 0);
2752 54 pos($$body_ref) = 0;
2753 54 ▶ while ($$body_ref =~ m{$VERBATIM_OPEN}gc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$body_ref =~ /$VERBATIM_OPEN/acg) 32040 54 32094
2754 32040 my $name = lc($1);
2755 32040 my $content_start = pos($$body_ref);
2756 32040 ▶ next if $unclosed{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $unclosed{$name} 31999 41 32040
2757  
2758 41 ▶ if ($$body_ref =~ m{\G(.*?)</\Q$name\E\s*+>}gcis) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$body_ref =~ m[\G(.*?)</\Q$name\E\s*+>]acgis) { } 40 1 41
2759 40 push(@saved, $1);
2760 40 $out .= substr($$body_ref, $from, $content_start - $from) . $marker . $#saved . $marker;
2761 40 $from = $+[1]; # the closing tag stays where it is
2762 } else {
2763 1 $unclosed{$name} = 1;
2764 1 pos($$body_ref) = $content_start;
2765 }
2766 }
2767 54 $$body_ref = $out . substr($$body_ref, $from);
2768  
2769 54 return {marker => $marker, saved => \@saved};
2770 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2771  
2772 # Purpose: Put back what _protect_verbatim took out.
2773 # Entry criteria: $vault came from _protect_verbatim on this body.
2774 # Exit status: The HTML with every placeholder restored.
2775 # Side effects: None.
2776 54 ▶sub _restore_verbatim :Private {
Subroutine _restore_verbatim: called CC=2 SCAR=6.9
2777 54 my ($body, $vault) = @_;
2778  
2779 54 my ($marker, $saved) = @{$vault}{qw(marker saved)};
2780 54 ▶ $body =~ s{\Q$marker\E(\d+)\Q$marker\E}{$saved->[$1]}g if @$saved;
Branch: 1 branch
BranchTrueFalseTotal
if @$saved 19 35 54
2781  
2782 54 return $body;
2783 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2784  
2785 # Purpose: Make links back to this site relative.
2786 # Entry criteria: $body is HTML; $c is the current controller.
2787 # Exit status: The rewritten HTML, or undef when the request has no
2788 # host to compare against.
2789 # Side effects: None.
2790 48 ▶sub _rewrite_links :Private {
Subroutine _rewrite_links: called CC=8 SCAR=21.9
2791 48 my ($body, $c) = @_;
2792  
2793 48 my $url = eval { $c->req->url->to_abs };
2794 48 ▶ my $host = $url ? $url->host : undef;
Branch: 1 branch
BranchTrueFalseTotal
$url ? : 48 0 48
2795 48 ▶ return undef unless defined($host) && length($host);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host and length $host 0 48 48
Condition33%1/3
defined $host and length $host
!ll&&!rl&&r
0048
MC/DC0%0/2
defined $host and length $host
defined $host length $host
Truth table33%1/3
A and B
A= defined $hostB= length $host
ABresult
0X0
100
111
2796  
2797 48 ▶ my $authority = $url->host_port // $host;
Condition33%1/3
$url->host_port // $host
l!l&&r!l&&!r
4800
MC/DC0%0/2
$url->host_port // $host
$url->host_port $host
Truth table33%1/3
A // B
A= $url->host_portB= $host
ABresult
1X1
011
000
2798 48 ▶ my $origin = quotemeta(($url->scheme // 'http') . "://$authority");
Condition50%1/2
$url->scheme // "http"
l!l
480
MC/DC0%0/1
$url->scheme // "http"
$url->scheme
Truth table50%1/2
A
A= $url->scheme
Aresult
11
00
2799 48 my $relative = quotemeta("//$authority");
2800  
2801 # The site root becomes "/", anything beneath it a root-relative path
2802 48 for my $link (@LINK_ATTRIBUTES) {
2803 96 my ($tag, $attribute) = @$link;
2804 96 $body =~ s{<$tag\s+?$attribute="$origin"}{<$tag $attribute="/"}gi;
2805 96 $body =~ s{<$tag\s+?$attribute="(?:$origin|$relative)/}{<$tag $attribute="/}gi;
2806 }
2807  
2808 # A link to the current page with a query string only needs the query
2809 # string, e.g. href="/search?q=perl" becomes href="?q=perl"
2810 48 my $path = $c->req->url->path->to_string;
2811 48 ▶ $body =~ s{<a\s+?href="\Q$path\E\?}{<a href="?}gi if length($path) > 1;
Branch: 1 branch
BranchTrueFalseTotal
if length $path > 1 21 27 48
2812  
2813 48 return $body;
2814 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2815  
2816 # ---------------------------------------------------------------------------
2817 # Content coding
2818 # ---------------------------------------------------------------------------
2819  
2820 # Purpose: Pick the best content coding from an Accept-Encoding
2821 # header.
2822 # Entry criteria: $supported is the server's list in preference order.
2823 # Exit status: A coding name, or undef when identity should be used.
2824 # Side effects: None.
2825 532 ▶sub _negotiate_encoding :Private {
Subroutine _negotiate_encoding: called CC=17 SCAR=29.4
2826 532 my ($accept, $supported) = @_;
2827  
2828 532 ▶ return undef unless defined($accept) && length($accept) && $supported && @$supported;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $accept and length $accept and $supported and @$supported 338 194 532
Condition66%6/9
defined $accept and length $accept and $supported and @$supported
!ll&&!rl&&r
3380194
defined $accept and length $accept and $supported
!ll&&!rl&&r
3380194
defined $accept and length $accept
!ll&&!rl&&r
3380194
MC/DC25%1/4
defined $accept and length $accept and $supported and @$supported
defined $accept length $accept $supported @$supported
Truth table40%2/5
A and B and C and D
A= defined $acceptB= length $acceptC= $supportedD= @$supported
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2829  
2830 # Highest q per coding, with "*" as the fallback for unlisted ones
2831 194 my (%quality, $wildcard);
2832 194 for my $coding (@{split_header($accept)}) {
2833 196 my ($token, undef, %params) = @$coding;
2834 196 ▶ next unless defined($token) && length($token);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token and length $token 0 196 196
Condition33%1/3
defined $token and length $token
!ll&&!rl&&r
00196
MC/DC0%0/2
defined $token and length $token
defined $token length $token
Truth table33%1/3
A and B
A= defined $tokenB= length $token
ABresult
0X0
100
111
2835  
2836 196 my $name = _canonical_encoding($token);
2837 196 my $q = _quality(\%params);
2838 196 ▶ if ($name eq '*') {
Branch: 2 branches
BranchTrueFalseTotal
if ($name eq '*') { } 2 194 196
elsif (not exists $quality{$name} or $q > $quality{$name}) { } 194 0 194
2839 2 $wildcard = $q;
2840 ▶ } elsif (!exists($quality{$name}) || ($q > $quality{$name})) {
Condition33%1/3
not exists $quality{$name} or $q > $quality{$name}
l!l&&r!l&&!r
19400
MC/DC0%0/2
not exists $quality{$name} or $q > $quality{$name}
not exists $quality{$name} $q > $quality{$name}
Truth table33%1/3
not(A) or B
A= not exists $quality{$name}B= $q > $quality{$name}
ABresult
1X1
011
000
2841 194 $quality{$name} = $q;
2842 }
2843 }
2844  
2845 # Server order breaks ties, so the first equal-best coding wins
2846 194 my ($best, $best_quality);
2847 194 for my $encoding (@$supported) {
2848 368 ▶ my $q = $quality{$encoding} // $wildcard // 0;
Condition100%5/5
($quality{$encoding} // $wildcard) // 0
l!l
196172
$quality{$encoding} // $wildcard
l!l&&r!l&&!r
1924172
MC/DC100%2/2
($quality{$encoding} // $wildcard) // 0
$quality{$encoding} $wildcard
Truth table100%3/3
A // B
A= $quality{$encoding}B= $wildcard
ABresult
1X1
011
000
2849 368 ▶ next if $q <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $q <= 0 174 194 368
2850 194 ▶ ($best, $best_quality) = ($encoding, $q) if !defined($best_quality) || ($q > $best_quality);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $best_quality or $q > $best_quality 192 2 194
Condition66%2/3
not defined $best_quality or $q > $best_quality
l!l&&r!l&&!r
19202
MC/DC50%1/2
not defined $best_quality or $q > $best_quality
not defined $best_quality $q > $best_quality
Truth table66%2/3
not(A) or B
A= not defined $best_qualityB= $q > $best_quality
ABresult
1X1
011
000
2851 }
2852  
2853 194 return $best;
2854 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2855  
2856 # Purpose: Read the q parameter of one Accept-Encoding entry.
2857 # Entry criteria: $params maps parameter names to values.
2858 # Exit status: A quality between 0 and 1; 1 if absent or unreadable.
2859 # Side effects: None.
2860 196 ▶sub _quality :Private {
Subroutine _quality: called CC=5 SCAR=16.6
2861 196 my $params = shift;
2862  
2863 196 my %lower = map { lc($_) => $params->{$_} } keys %$params;
2864 196 ▶ my $q = (defined($lower{q}) && looks_like_number($lower{q})) ? $lower{q} + 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $lower{'q'} && &looks_like_number($lower{'q'}) ? : 8 188 196
Condition66%2/3
defined $lower{"q"} and &looks_like_number($lower{"q"})
!ll&&!rl&&r
18808
MC/DC50%1/2
defined $lower{"q"} and &looks_like_number($lower{"q"})
defined $lower{"q"} &looks_like_number($lower{"q"})
Truth table66%2/3
A and B
A= defined $lower{"q"}B= &looks_like_number($lower{"q"})
ABresult
0X0
100
111
2865  
2866 196 ▶ return ($q < 0) ? 0 : ($q > 1) ? 1 : $q;
Branch: 2 branches
BranchTrueFalseTotal
$q < 0 ? : 0 196 196
$q > 1 ? : 0 196 196
2867 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2868  
2869 # Purpose: Normalise a content coding name.
2870 # Entry criteria: Any value.
2871 # Exit status: The lower-cased name, with legacy aliases resolved.
2872 # Side effects: None.
2873 885 ▶sub _canonical_encoding :Private {
Subroutine _canonical_encoding: called CC=3 SCAR=13.1
2874 885 ▶ my $name = lc(shift // '');
Condition50%1/2
shift() // ""
l!l
8850
MC/DC0%0/1
shift() // ""
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
2875  
2876 885 ▶ return $ENCODING_ALIAS{$name} // $name;
Condition33%1/3
$ENCODING_ALIAS{$name} // $name
l!l&&r!l&&!r
08850
MC/DC0%0/2
$ENCODING_ALIAS{$name} // $name
$ENCODING_ALIAS{$name} $name
Truth table33%1/3
A // B
A= $ENCODING_ALIAS{$name}B= $name
ABresult
1X1
011
000
2877 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2878  
2879 # Purpose: Compress bytes with one coding.
2880 # Entry criteria: $encoding is a key of %ENCODERS.
2881 # Exit status: {body => $compressed} or {error => $text}.
2882 # Side effects: Loads the coding's module on first use.
2883 62 ▶sub _encode_body :Private {
Subroutine _encode_body: called CC=3 SCAR=11.3
2884 62 my ($encoding, $bytes) = @_;
2885  
2886 62 my $encoder = $ENCODERS{$encoding};
2887 62 my $body = eval {
2888 62 ▶ $encoder ? $encoder->($bytes) : croak(__PACKAGE__->i18n('unknown_encoding', {encoding => $encoding}));
Branch: 1 branch
BranchTrueFalseTotal
$encoder ? : 62 0 62
2889 };
2890  
2891 62 ▶ return $@ ? {error => $@} : {body => $body};
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 62 62
2892 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2893  
2894 # ---------------------------------------------------------------------------
2895 # Small header helpers
2896 # ---------------------------------------------------------------------------
2897  
2898 # Purpose: Compare If-None-Match with this response's tag, using
2899 # the weak comparison RFC 7232 requires for it.
2900 # Entry criteria: Both arguments are defined.
2901 # Exit status: 1 if any listed tag, or "*", matches; else 0.
2902 # Side effects: None.
2903 48 ▶sub _etag_matches :Private {
Subroutine _etag_matches: called CC=5 SCAR=16.1
2904 48 my ($if_none_match, $etag) = @_;
2905  
2906 48 (my $mine = $etag) =~ s{^W/}{};
2907  
2908 48 my $match = 0;
2909 48 for my $candidate (grep { length } map { trim($_) } split(/,/, $if_none_match)) {
2910 50 $candidate =~ s{^W/}{};
2911 50 ▶ $match ||= ($candidate eq '*') || ($candidate eq $mine);
Condition100%6/6
$match ||= $candidate eq "*" || $candidate eq $mine
l!l&&r!l&&!r
23414
$candidate eq '*' || $candidate eq $mine
l!l&&r!l&&!r
23214
MC/DC0%0/3
$match ||= $candidate eq "*" || $candidate eq $mine
$match $candidate eq '*' $candidate eq $mine
Truth table0%0/4
A ||= B || C
A= $matchB= $candidate eq '*'C= $candidate eq $mine
ABCresult
1XX1
01X1
0011
0000
2912 }
2913  
2914 48 ▶ return $match ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$match ? : 34 14 48
2915 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2916  
2917 # Purpose: Say that the representation depends on Accept-Encoding.
2918 # Entry criteria: $headers is a Mojo::Headers.
2919 # Exit status: $headers.
2920 # Side effects: Appends Accept-Encoding to Vary unless already listed.
2921 532 ▶sub _add_vary :Private {
Subroutine _add_vary: called CC=3 SCAR=11.0
2922 532 my $headers = shift;
2923  
2924 532 ▶ my $listed = grep { lc(trim($_)) eq 'accept-encoding' } split(/,/, $headers->vary // '');
Condition100%2/2
$headers->vary // ""
l!l
79453
MC/DC100%1/1
$headers->vary // ""
$headers->vary
Truth table100%2/2
A
A= $headers->vary
Aresult
11
00
2925 532 ▶ $headers->append(Vary => 'Accept-Encoding') unless $listed;
Branch: 1 branch
BranchTrueFalseTotal
unless $listed 461 71 532
2926  
2927 532 return $headers;
2928 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2929  
2930 # Purpose: Extract the media type from a Content-Type value.
2931 # Entry criteria: Any value.
2932 # Exit status: The lower-cased type/subtype, or undef.
2933 # Side effects: None.
2934 565 ▶sub _mime_type :Private {
Subroutine _mime_type: called CC=3 SCAR=11.7
2935 565 my $content_type = shift;
2936  
2937 565 ▶ my ($type) = ($content_type // '') =~ m{^\s*([\w.+-]+/[\w.+-]+)};
Condition50%1/2
$content_type // ""
l!l
5650
MC/DC0%0/1
$content_type // ""
$content_type
Truth table50%1/2
A
A= $content_type
Aresult
11
00
2938  
2939 565 ▶ return defined($type) ? lc($type) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $type ? : 565 0 565
2940 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2941  
2942 # Purpose: Match a media type against a list of strings and regexes.
2943 # Entry criteria: $type is lower-case; $patterns is an array reference.
2944 # Exit status: 1 if any entry matches, else 0.
2945 # Side effects: None.
2946 1128 ▶sub _matches :Private {
Subroutine _matches: called CC=7 SCAR=19.6
2947 1128 my ($type, $patterns) = @_;
2948  
2949 1128 my $found = 0;
2950 1128 ▶ for my $pattern ((ref($patterns) eq 'ARRAY') ? @$patterns : ()) {
Branch: 1 branch
BranchTrueFalseTotal
ref $patterns eq 'ARRAY' ? : 1128 0 1128
2951 2246 ▶ $found ||= (ref($pattern) eq 'Regexp')
Branch: 1 branch
BranchTrueFalseTotal
ref $pattern eq 'Regexp' ? : 1132 4 1136
Condition83%5/6
$found ||= ref $pattern eq "Regexp" ? scalar $type =~ /$pattern/a : defined $pattern && lc $pattern eq $type
l!l&&r!l&&!r
1110561575
defined $pattern and lc $pattern eq $type
!ll&&!rl&&r
022
MC/DC100%2/2
$found ||= ref $pattern eq "Regexp" ? scalar $type =~ /$pattern/a : defined $pattern && lc $pattern eq $type
$found ref $pattern eq "Regexp" ? scalar $type =~ /$pattern/a : defined $pattern && lc $pattern eq $type
MC/DC50%1/2
defined $pattern and lc $pattern eq $type
defined $pattern lc $pattern eq $type
Truth table100%3/3
A ||= B
A= $foundB= ref $pattern eq "Regexp" ? scalar $type =~ /$pattern/a : defined $pattern && lc $pattern eq $type
ABresult
1X1
011
000
Truth table66%2/3
A and B
A= defined $patternB= lc $pattern eq $type
ABresult
0X0
100
111
2952 ? scalar($type =~ $pattern)
2953 : (defined($pattern) && (lc($pattern) eq $type));
2954 }
2955  
2956 1128 ▶ return $found ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 561 567 1128
2957 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2958  
2959 37 1; # End of Mojolicious::Plugin::Buffer
2960  
2961 =head1 DEPLOYMENT
2962  
2963 =head2 Hypnotoad
2964  
2965 L<hypnotoad> preloads the application before forking the workers, so the
2966 plugin is registered once and every worker inherits the same cache object
2967 and lock backend. The cache storage, and the storage used by the lock
2968 backend, must be shared and writable by the user that runs the workers. The
2969 example below uses L<CHI>, which must be installed in the application's
2970 environment.
2971  
2972 A complete application:
2973  
2974 package MyApp;
2975 use Mojo::Base 'Mojolicious';
2976  
2977 use CHI;
2978  
2979 sub startup {
2980 my $self = shift;
2981  
2982 $self->config(hypnotoad => {
2983 listen => ['http://*:8080'],
2984 workers => 4,
2985 pid_file => '/var/lib/myapp/hypnotoad.pid',
2986 });
2987  
2988 $self->plugin('Buffer' => {
2989 optimise_content => 1,
2990 cache => CHI->new(
2991 driver => 'File',
2992 root_dir => '/var/cache/myapp/buffer',
2993 namespace => 'pages',
2994 ),
2995 cache_lock_dir => '/var/lib/myapp/buffer-locks',
2996 cache_duration => '10 minutes',
2997 });
2998  
2999 $self->routes->get('/expensive' => sub {
3000 my $c = shift;
3001 return if $c->buffer_is_cached;
3002  
3003 # ... expensive work ...
3004  
3005 $c->render(template => 'expensive');
3006 });
3007 }
3008  
3009 1;
3010  
3011 A runnable copy of this example, with its paths under C<examples/hypnotoad>,
3012 is included as F<examples/hypnotoad>.
3013  
3014 C<script/my_app> is the usual launcher:
3015  
3016 #!/usr/bin/env perl
3017 use strict;
3018 use warnings;
3019 use FindBin;
3020 use lib "$FindBin::Bin/../lib";
3021 use MyApp;
3022  
3023 MyApp->new->start;
3024  
3025 Create the directories as the deployment user and start the server:
3026  
3027 install -d -o www-data -g www-data -m 0750 /var/cache/myapp/buffer
3028 install -d -o www-data -g www-data -m 0750 /var/lib/myapp /var/lib/myapp/buffer-locks
3029 hypnotoad script/my_app
3030  
3031 Replace C<www-data> with the unprivileged user that runs the workers; do not
3032 run hypnotoad as root. The plugin creates C<cache_lock_dir> if necessary,
3033 but pre-creating it as the deployment user sets its ownership and
3034 permissions. The cache directory must be writable by that user too. Use
3035 C<hypnotoad -f script/my_app> in the foreground while testing, and
3036 C<hypnotoad -s script/my_app> to stop it.
3037  
3038 =head2 Cache and lock requirements
3039  
3040 For workers on the same host, L<CHI>'s C<File> driver and the built-in file
3041 lock backend work. Do not use C<Memory>, and do not put a per-worker C<L1>
3042 cache in front of the shared cache: a waiting worker would not see the entry
3043 built by another worker and would eventually receive C<503 Service
3044 Unavailable>. A shared filesystem with reliable C<flock> can also be used
3045 on several hosts.
3046  
3047 =head2 Multiple hosts
3048  
3049 Workers on different hosts need a shared cache and a lock backend that does
3050 not rely on C<flock>. This example uses CHI's Memcached driver for the cache
3051 and L<Mojolicious::Plugin::Buffer::Lock::Redis> for the lock, with the
3052 L<Redis> client:
3053  
3054 use CHI;
3055 use Mojolicious::Plugin::Buffer::Lock::Redis;
3056 use Redis;
3057  
3058 my $redis = sub {
3059 Redis->new(
3060 server => 'redis://redis.internal:6379',
3061 cnx_timeout => 1,
3062 read_timeout => 1,
3063 write_timeout => 1,
3064 );
3065 };
3066  
3067 $app->plugin('Buffer' => {
3068 cache => CHI->new(
3069 driver => 'Memcached',
3070 servers => ['cache1.internal:11211', 'cache2.internal:11211'],
3071 namespace => 'pages',
3072 ),
3073 cache_lock => Mojolicious::Plugin::Buffer::Lock::Redis->new(
3074 redis => $redis,
3075 namespace => 'myapp:buffer:',
3076 ttl => 60,
3077 ),
3078 cache_duration => '10 minutes',
3079 });
3080  
3081 The C<ttl> must be longer than L</cache_lock_timeout> and longer than the
3082 slowest cached action. If it expires while the builder is still working,
3083 another worker can start building the same entry. The Redis client is
3084 called synchronously, so set short connect, read and write timeouts. The
3085 code reference is called once per worker, after the fork; a connection
3086 created in C<startup> would be shared by every worker and must not be used.
3087 CHI's Memcached driver needs L<Cache::Memcached::Fast>.
3088  
3089 Only cache pages that are identical for every visitor. The default key
3090 includes the C<Cookie> header, not the contents of the session, so a page
3091 that depends on the session needs L</cache_key> or a suitable L</vary_by>
3092 list. Entries are discarded when the application script or a template
3093 changes, and otherwise expire after L</cache_duration>.
3094  
3095 =head1 NOTES
3096  
3097 =head2 Testing
3098  
3099 The Redis lock backend has an optional live integration test. It skips when
3100 C<MPB_REDIS_URL> (or C<REDIS_SERVER>) is not set, or when neither L<Redis> nor
3101 L<Redis::Fast> is installed. Redis::Fast is used when it is the only client
3102 available. CI runs the test against a live Redis service with each client,
3103 once with L<Redis> and once with only L<Redis::Fast> available (L<Redis>
3104 hidden with L<Test::Without::Module>), and each run proves from the test
3105 output which client it used, so both paths include the three-process crash
3106 check described below rather than merely being wired up. When either
3107 variable is set, the test expects that server to be reachable; the value may
3108 be a C<redis://> URL or a bare C<host:port>, so C<REDIS_SERVER> already in
3109 the environment needs no rewriting:
3110  
3111 MPB_REDIS_URL=redis://127.0.0.1:6379 prove -Ilib t/76-live-redis.t
3112 REDIS_SERVER=127.0.0.1:6379 prove -Ilib t/76-live-redis.t
3113  
3114 A server named by either variable must answer. The variable says a live
3115 Redis is there for this test, so an unreachable one fails the file, naming
3116 the variable and the connection error, rather than skipping and looking like
3117 a checkout with no Redis configured. Unset both to skip the test.
3118  
3119 That includes a three-process check of the crash path: a worker takes the
3120 lock and is killed, another process stays blocked until the TTL expires,
3121 takes the lock over, and a third process is blocked until that owner
3122 releases it. The crash test uses a two second lock TTL and waits for it to
3123 run out rather than sleeping a fixed margin; set C<MPB_REDIS_TTL> to widen
3124 that further on a heavily loaded machine. The normal test suite does not
3125 require a Redis server.
3126  
3127 The private routines are guarded by L<Sub::Private> in C<enforce> mode and
3128 L<Sub::Protected>. Both stand aside while C<HARNESS_ACTIVE> is set, so the
3129 white-box tests can reach them under C<prove>; F<t/16-encapsulation.t> turns
3130 that bypass off to check the guards themselves.
3131  
3132 =head2 Why a plugin?
3133  
3134 L<CGI::Buffer> replaces C<STDOUT> with an in-memory buffer and does its work
3135 in an C<END> block, and L<FCGI::Buffer> buffers each FastCGI request and does
3136 its work in C<DESTROY>. Neither trick is needed in Mojolicious: the response
3137 already exists as an object before it is written, so the plugin can simply
3138 hook C<after_dispatch> and rewrite it. That gives the same effect without a
3139 source filter, without reading C<$_>, and without depending on a specific
3140 server or environment.
3141  
3142 =head2 Interaction with the renderer
3143  
3144 C<Mojolicious::Renderer> compresses rendered output with gzip by default
3145 (C<compress> is on and C<min_compress_size> is 860 bytes). That happens
3146 before L<Mojolicious/"after_dispatch"> is emitted, which would leave this
3147 plugin with nothing to optimise and no C<ETag> to generate on any page
3148 larger than 860 bytes. Registering this plugin therefore calls
3149 C<< $app->renderer->compress(0) >>, and the plugin does the compression
3150 instead - with gzip, Brotli or Zstandard as negotiated, and with the header
3151 work the renderer does not do. If you enable C<< $app->renderer->compress >>
3152 after loading the plugin, those responses will be skipped by the plugin.
3153  
3154 =head2 What is not implemented
3155  
3156 C<save_to>, which rewrites dynamic pages into static ones, is a site
3157 generation feature rather than a response filter and is not part of this
3158 plugin. The server-side cache is available as the opt-in
3159 L</buffer_is_cached> helper described above.
3160  
3161 =head1 COMMON PITFALLS
3162  
3163 =head2 The C<buffer> stash: what each value means
3164  
3165 =over 4
3166  
3167 =item * C<< buffer =E<gt> 0 >> and C<< buffer =E<gt> '' >> turn the plugin
3168 B<off> for this response.
3169  
3170 =item * C<< buffer =E<gt> undef >> does B<not> turn it off. undef means
3171 "nothing set here", so the plugin options are used.
3172  
3173 =item * C<< buffer =E<gt> {} >> keeps the plugin B<on> and changes nothing.
3174  
3175 =back
3176  
3177 =head2 The C<buffer> stash is merged one level deep only
3178  
3179 The hash you put in the stash is laid over the plugin options one key at a
3180 time. A key you give replaces the whole plugin value for that key; nothing
3181 inside it is merged. So lists are replaced, not added to:
3182  
3183 plugin 'Buffer' => {encodings => [qw(br gzip)]};
3184  
3185 # This response may ONLY use br. If Brotli is not installed, it is
3186 # not compressed at all, and an error is logged.
3187 $c->stash(buffer => {encodings => ['br']});
3188  
3189 Values in the stash are not checked the way C<plugin()> options are, and
3190 they are not filtered by which compression modules are installed.
3191  
3192 =head2 undef in options
3193  
3194 =over 4
3195  
3196 =item * In the C<buffer> stash, an undef value is a real value.
3197 C<< {compress_content =E<gt> undef} >> turns compression B<off> for that
3198 response, and C<< {cache =E<gt> undef} >> turns the cache off.
3199  
3200 =item * In a group declaration (a route default or C<buffer_NAME>
3201 controller method), undef means "not declared", so the plugin option is
3202 used.
3203  
3204 =item * In C<plugin()> options, undef is accepted only where it means "use
3205 the default" or "off":
3206  
3207 optimise_content and the true/false off
3208 flags (compress_content,
3209 rewrite_links, generate_etag,
3210 generate_304, trust_last_modified,
3211 cache_single_flight)
3212 last_modified no Last-Modified header
3213 cache, cache_lock, cache_lock_dir, not used
3214 template_mtime_cache
3215 cache_key the generated key
3216 cache_duration, cache_lock_timeout, their default values
3217 template_mtime_cache_duration
3218 messages the built-in English texts
3219  
3220 For C<encodings>, C<compressible_types>, C<excluded_types>, C<vary_by>,
3221 C<min_compress_size> and C<min_compress_saving>, undef is refused when the
3222 plugin is registered. This matters most for C<vary_by>: an undef there
3223 would have silently removed the C<Cookie> header from the cache key.
3224  
3225 =item * In C<messages>, undef does B<not> restore the built-in text.
3226 C<< messages =E<gt> {retry_later =E<gt> undef} >> makes visitors see the
3227 word C<retry_later>. Leave the key out instead. See
3228 L<Mojolicious::Plugin::Buffer::I18N/COMMON PITFALLS>.
3229  
3230 =back
3231  
3232 =head2 Using the server-side cache safely
3233  
3234 =over 4
3235  
3236 =item * B<Check access before L</buffer_is_cached>.> A cached page is sent
3237 straight away and the rest of the action does not run. Any login or
3238 country check that comes later in the action is skipped on a hit.
3239  
3240 =item * B<Personal pages need a personal key.> C<< vary_by =E<gt> [] >>
3241 makes the key the same for every visitor. A page that shows a name, a
3242 basket or anything else from the session is then shown to other visitors.
3243 Keep the default C<['cookie']>, or set L</cache_key>.
3244  
3245 =item * B<The cache must be shared by all workers.> With several workers,
3246 a per-worker cache such as CHI's C<Memory> driver means a waiting request
3247 never sees the entry another worker built; after L</cache_lock_timeout>
3248 it gets C<503 Service Unavailable>.
3249  
3250 =item * B<Waiting requests get 503, not a second build.> If the request
3251 that is building a page fails, makes something that cannot be stored (for
3252 example, it sets a cookie), or is slower than L</cache_lock_timeout>, the
3253 requests waiting for it get C<503> with C<Retry-After: 1>.
3254  
3255 =item * B<A Redis lock TTL must be longer than the slowest action>, or a
3256 second worker starts building the same page.
3257  
3258 =item * B<Template edits can be missed for a while> when
3259 L</template_mtime_cache> is set: until its entry expires.
3260  
3261 =back
3262  
3263 =head2 Other pitfalls
3264  
3265 =over 4
3266  
3267 =item * B<Do not turn the renderer's compression back on.> The plugin turns
3268 off C<< $app->renderer->compress >>. If you turn it on again, the renderer
3269 compresses first, and the plugin then skips those responses: no
3270 optimisation and no C<ETag>.
3271  
3272 =item * B<Do not stream through the plugin.> Responses written with
3273 C<< $c->write >> are not buffered and are left alone.
3274  
3275 =item * B<C<$c-E<gt>stash(buffer =E<gt> ...)> must be set before the action
3276 ends.> The plugin reads it in C<after_dispatch>. To turn the cache off for
3277 one request, set C<< {cache =E<gt> undef} >> I<before> calling
3278 L</buffer_is_cached>.
3279  
3280 =back
3281  
3282 =head1 ENCODING
3283  
3284 This section says which text may contain non-ASCII characters, such as
3285 accented letters, other scripts and emoji.
3286  
3287 =over 4
3288  
3289 =item Response bodies
3290  
3291 Any encoding works. Pages rendered by Mojolicious are already UTF-8 bytes
3292 when the plugin sees them. A body that is still a Perl character string is
3293 encoded to UTF-8 first. Bodies in another character set, such as
3294 ISO-8859-1 or Shift_JIS, are passed through unchanged; the plugin does not
3295 convert them.
3296  
3297 =item HTML optimisation
3298  
3299 Safe for every UTF-8 character, including emoji. The optimiser only
3300 changes ASCII white space (space, tab, carriage return, line feed, form
3301 feed) and ASCII markup. A non-breaking space (U+00A0) is kept.
3302  
3303 =item The C<ETag>
3304  
3305 Made from the bytes of the body, so any content is fine.
3306  
3307 =item Cache keys
3308  
3309 A custom L</cache_key> may contain any characters, including emoji. Keys
3310 are encoded to UTF-8 before they are hashed for the lock backends. The
3311 generated key is an ASCII MD5 digest. The cache itself receives a custom
3312 key as it is; L<CHI>'s File and Memory drivers accept any characters, but
3313 check this for other cache objects.
3314  
3315 =item Request headers in L</vary_by>
3316  
3317 Header I<names> are ASCII. Header I<values> are used as raw bytes, so any
3318 value is fine.
3319  
3320 =item The C<503> text (C<retry_later>) and other messages
3321  
3322 May contain any characters. The C<503> body is sent as UTF-8 with
3323 C<Content-Type: text/plain; charset=UTF-8>. Log lines go through
3324 L<Mojo::Log>, which writes them as UTF-8.
3325  
3326 =item Error messages
3327  
3328 The plugin's C<croak> messages are Perl character strings. If you
3329 translate them into a non-ASCII language and print them to C<STDERR>, give
3330 C<STDERR> an encoding layer, or Perl warns "Wide character".
3331  
3332 =item File paths (C<cache_lock_dir>)
3333  
3334 Paths go to the operating system as bytes. ASCII paths are always safe.
3335 For a non-ASCII path, pass bytes that are already encoded the way your file
3336 system expects, usually UTF-8.
3337  
3338 =item Option names, encoding names and media types
3339  
3340 These are ASCII words.
3341  
3342 =back
3343  
3344 =head1 LIMITATIONS
3345  
3346 =over 4
3347  
3348 =item * Only in-memory responses are processed. Static files
3349 (C<Mojo::Asset::File>) and streaming responses are left alone.
3350  
3351 =item * The whole response is held in memory, more than once while it is
3352 being optimised and compressed. There is no size limit; a very large
3353 generated body costs several times its size in a worker.
3354  
3355 =item * Responses that already have a C<Content-Encoding>, for example from
3356 C<$app-E<gt>renderer-E<gt>compress>, are not compressed again.
3357  
3358 =item * Gzip, Brotli, Zstandard and identity representations have different
3359 C<ETag>s, because the tag identifies the selected representation. A client
3360 that switches between content codings will therefore download the page once
3361 for each coding.
3362  
3363 =item * Because the body is buffered, the plugin must not be used for
3364 responses that are streamed with C<$c-E<gt>write> (server-sent events,
3365 long-polling and so on). C<text/event-stream> is excluded by default.
3366  
3367 =item * The HTML optimiser is a set of regular expressions inherited from
3368 L<CGI::Buffer>, not an HTML parser. It protects the content of
3369 C<E<lt>preE<gt>>, C<E<lt>textareaE<gt>>, C<E<lt>scriptE<gt>> and
3370 C<E<lt>styleE<gt>>, but white space made significant by CSS
3371 (C<white-space: pre> on another element) is still collapsed, and some rules
3372 (for example merging adjacent C<E<lt>centerE<gt>> blocks) change the
3373 document slightly. The squashing runs in time proportional to the size
3374 of the page, even for malformed HTML, but L<HTML::Packer> does not: on a
3375 page with thousands of unclosed C<E<lt>preE<gt>> tags it can take seconds.
3376 Do not optimise HTML that a visitor controls. Use
3377 C<optimise_content =E<gt> 0> on pages where every
3378 byte matters, or disable it per response with
3379 C<$c-E<gt>stash(buffer =E<gt> {optimise_content =E<gt> 0})>. Link rewriting
3380 only recognises double-quoted attributes.
3381  
3382 =item * The server-side cache is opt-in: a page is only stored if its action
3383 calls L</buffer_is_cached>. An action that forgets to call it is never
3384 cached, and an action that calls it for a personalised page must supply a
3385 L</cache_key> that distinguishes users (the default key only includes the
3386 C<Cookie> header, not the session contents).
3387  
3388 =item * The default key includes the C<Cookie> header, so each session gets
3389 its own set of entries and anonymous visitors share them. Sites that set an
3390 analytics cookie on every visit will get little sharing; use
3391 C<vary_by =E<gt> []> for genuinely public pages, or L</cache_key>.
3392  
3393 =item * Single-flight is per worker by default. Each C<hypnotoad> worker
3394 keeps its own in-flight table, so a cold entry can be built once per worker;
3395 set L</cache_lock> or L</cache_lock_dir> to coalesce across workers, with a
3396 shared cache. A request waiting on an in-flight response is answered with
3397 C<503> if that response fails, cannot be cached, or exceeds
3398 L</cache_lock_timeout>, rather than running the action a second time. A
3399 waiter in another worker polls the cache every 100 milliseconds, so it can
3400 be answered up to that much later than the builder finishes.
3401  
3402 =item * Entries are invalidated when the application script or a template
3403 path changes, but not when data or configuration changes. The TTL is the
3404 backstop for those.
3405  
3406 =item * Options in the C<buffer> stash and group declarations are not
3407 validated the way C<plugin()> options are. A bad C<cache_lock_timeout>
3408 there falls back to the default; other bad values are used as given.
3409  
3410 =item * The lock backend protocol returns two-element lists rather than
3411 references. That is the documented interface third-party backends already
3412 implement, so it was kept.
3413  
3414 =item * Every private routine is wrapped by L<Sub::Private> or
3415 L<Sub::Protected>, which costs a C<caller> check on each call. The plugin
3416 makes a few hundred such calls per response, which is small next to MD5,
3417 compression and template rendering, but it is not free. The modules also
3418 add L<Readonly>, L<Params::Validate::Strict> and their dependencies to what
3419 was a Mojolicious-only plugin, and C<use autodie qw(:all)> requires
3420 L<IPC::System::Simple> even though the plugin never runs an external
3421 command.
3422  
3423 =item * The C<503> text is chosen per application through L</messages>; it
3424 is not negotiated from C<Accept-Language>.
3425  
3426 =back
3427  
3428 =head1 SEE ALSO
3429  
3430 L<CGI::Buffer>, L<FCGI::Buffer>, L<CHI>, L<HTML::Packer>,
3431 L<Mojolicious::Plugin>, L<Mojolicious::Plugin::Buffer::Lock::File>,
3432 L<Mojolicious::Plugin::Buffer::Lock::Redis>,
3433 L<Mojolicious::Plugin::Buffer::I18N>
3434  
3435 =encoding utf8
3436  
3437 =head1 FORMAL SPECIFICATION
3438  
3439 This section describes the plugin in the Z notation, for readers who want
3440 an exact model. You do not need it to use the plugin. C<now> is the
3441 current time and C<mtime> is the newest modification time of the
3442 application script and its templates. C<Schema> maps each option name to
3443 its L<Params::Validate::Strict> rule.
3444  
3445 [OPTION, VALUE, APP, KEY, Controller, Entry, Guard, Response]
3446  
3447 Known == dom Schema
3448 Valid == { o : Known; v : VALUE | v ∈ Schema(o) }
3449  
3450 Flight == [ waiters : ℙ Controller ; deadline : ℝ ; guard : Guard ∪ {⊥} ]
3451  
3452 ┌─ Plugin ────────────────────────────────────
3453 │ options : OPTION ⇸ VALUE
3454 │ inflight : KEY ⇸ Flight
3455 │ polling : Controller ⇸ (KEY × ℝ)
3456 │ lock : LockBackend ∪ {⊥}
3457 ├─────────────────────────────────────────────
3458 │ dom options = Known
3459 │ ∀ o : dom options • (o, options o) ∈ Valid
3460 │ ∀ k : dom inflight • (inflight k).deadline ≤ now + timeout
3461 └─────────────────────────────────────────────
3462  
3463 ┌─ Cache ─────────────────────────────────────
3464 │ store : KEY ⇸ Entry
3465 │ created : KEY ⇸ ℝ
3466 ├─────────────────────────────────────────────
3467 │ dom created = dom store
3468 └─────────────────────────────────────────────
3469  
3470 fresh : ℙ KEY
3471 fresh = { k : dom store | created k ≥ mtime }
3472  
3473 =head2 register
3474  
3475 ┌─ Register ──────────────────────────────────
3476 │ ΔPlugin
3477 │ app? : APP ; conf? : OPTION ⇸ VALUE ; result! : Plugin
3478 ├─────────────────────────────────────────────
3479 │ dom conf? ⊆ Known
3480 │ ∀ o : dom conf? • (o, conf? o) ∈ Valid
3481 │ ∀ o : dom conf? • conf? o = ⊥ ⇒ undefAllowed(o)
3482 │ ¬(cache_lock ∈ dom conf? ∧ cache_lock_dir ∈ dom conf?)
3483 │ ran (conf? encodings) ⊆ {br, zstd, gzip, x-gzip}
3484 │ options′ = Defaults ⊕ conf?
3485 │ inflight′ = ∅ ∧ polling′ = ∅
3486 │ compress(renderer app?)′ = false
3487 │ after_dispatch ∈ hooks(app?)′ ∧ buffer_is_cached ∈ helpers(app?)′
3488 │ result! = θPlugin′
3489 └─────────────────────────────────────────────
3490 -- Any violated predicate: croak, and app? is unchanged
3491  
3492 =head2 buffer_is_cached
3493  
3494 C<cacheable(c)> holds when the plugin is on for this response, a cache is
3495 configured, the method is C<GET> or C<HEAD>, and the request carries no
3496 C<Authorization> header, no C<no-store>, C<no-cache>, C<private> or
3497 C<max-age=0> directive, and C<NO_CACHE> and C<NO_STORE> are not set.
3498 C<busy(k)> holds when the lock backend says another process holds C<k>.
3499  
3500 ┌─ BufferIsCached ────────────────────────────
3501 │ ΔPlugin ; ΔCache
3502 │ c? : Controller ; result! : 𝔹 ; response! : Response
3503 ├─────────────────────────────────────────────
3504 │ let k == key(c?) •
3505 │ ¬cacheable(c?) ⇒ result! = false
3506 │ cacheable(c?) ∧ k ∈ fresh ⇒
3507 │ response! = replay(store k) ∧ result! = true
3508 │ cacheable(c?) ∧ k ∉ fresh ⇒ store′ = {k} ⩤ store ∧ (
3509 │ ¬singleFlight ⇒ result! = false
3510 │ singleFlight ∧ k ∈ dom inflight ⇒
3511 │ (inflight′ k).waiters = (inflight k).waiters ∪ {c?}
3512 │ ∧ result! = true
3513 │ singleFlight ∧ k ∉ dom inflight ∧ busy(k) ⇒
3514 │ polling′ = polling ⊕ {c? ↦ (k, now + timeout)}
3515 │ ∧ result! = true
3516 │ singleFlight ∧ k ∉ dom inflight ∧ ¬busy(k) ⇒
3517 │ k ∈ dom inflight′ ∧ (inflight′ k).waiters = ∅
3518 │ ∧ result! = false )
3519 └─────────────────────────────────────────────
3520  
3521 The building request finishes (the C<after_dispatch> hook), or its time
3522 runs out. C<e?> is the stored entry, or C<⊥> when the response could not be
3523 stored or the build timed out.
3524  
3525 ┌─ FinishFlight ──────────────────────────────
3526 │ ΔPlugin
3527 │ k? : KEY ; e? : Entry ∪ {⊥}
3528 ├─────────────────────────────────────────────
3529 │ k? ∈ dom inflight
3530 │ ∀ w : (inflight k?).waiters •
3531 │ (e? ≠ ⊥ ⇒ response(w)′ = replay(e?))
3532 │ ∧ (e? = ⊥ ⇒ response(w)′ = 503)
3533 │ inflight′ = {k?} ⩤ inflight
3534 │ (inflight k?).guard ≠ ⊥ ⇒ released((inflight k?).guard)
3535 └─────────────────────────────────────────────
3536  
3537 ExpireFlight == [ FinishFlight | now ≥ (inflight k?).deadline ∧ e? = ⊥ ]
3538  
3539 Every 0.1 seconds, each request waiting for another worker looks again:
3540  
3541 ┌─ PollTick ──────────────────────────────────
3542 │ ΔPlugin
3543 │ c? : dom polling
3544 ├─────────────────────────────────────────────
3545 │ let (k, d) == polling c? •
3546 │ k ∈ fresh ⇒ response(c?)′ = replay(store k)
3547 │ ∧ polling′ = {c?} ⩤ polling
3548 │ k ∉ fresh ∧ now ≥ d ⇒ response(c?)′ = 503
3549 │ ∧ polling′ = {c?} ⩤ polling
3550 │ k ∉ fresh ∧ now < d ∧ busy(k) ⇒ polling′ = polling
3551 │ k ∉ fresh ∧ now < d ∧ ¬busy(k) ⇒
3552 │ response(c?)′ = 503 ∧ polling′ = {c?} ⩤ polling
3553 └─────────────────────────────────────────────
3554 -- In the last case the lock is taken and the cache read once more
3555 -- before the 503, so an entry stored at that moment is still replayed
3556  
3557 =head2 i18n
3558  
3559 The same operation as L<Mojolicious::Plugin::Buffer::I18N/i18n>, where
3560 C<overrides> is the L</messages> option.
3561  
3562 =head1 STATE DIAGRAM
3563  
3564 There are three pictures. The numbers on the arrows are explained below
3565 each picture. In each explanation, the text in C<[ ]> is the condition and
3566 the text after C</> is what happens.
3567  
3568 =head2 A. One page in the server-side cache
3569  
3570 This is the life of one cache key, seen by all workers together.
3571  
3572 +---------------------+
3573 | EMPTY |<-----------------------+
3574 | nothing is stored | |
3575 +---------------------+ |
3576 | ^ ^ |
3577 (1)| (3)| (4)| |
3578 v | | |
3579 +---------------------+ (5) |
3580 | BUILDING |-----------+ |
3581 | one request builds; | | |
3582 | others wait | v |
3583 +---------------------+ +--------------+ |
3584 | | CACHED | |
3585 (2)+----------------------->| fresh entry | |
3586 +--------------+ |
3587 | ^ | |
3588 (6)| |(7) |(8) |
3589 v | v |
3590 +--------------+ |
3591 | STALE |----+
3592 | too old | (9)
3593 +--------------+
3594  
3595 (1) a request calls buffer_is_cached [no fresh entry, single-flight
3596 on, nobody else building]
3597 / X-Cache: MISS; this request becomes the builder; it takes the
3598 shared lock if one is configured; a timer of
3599 cache_lock_timeout starts
3600 (2) the builder's response is finished [200, may be stored]
3601 / the uncompressed page is stored with cache_duration; every
3602 waiting request is answered from it; the lock is released
3603 (3) the builder's response is finished [error, or not storable:
3604 it sets a cookie, is marked private, no-store or no-cache, or
3605 varies on a
3606 header not in vary_by]
3607 / every waiting request gets 503 with Retry-After: 1; the lock
3608 is released
3609 (4) cache_lock_timeout passes before the builder finishes
3610 / waiting requests get 503; the lock is released. If the
3611 builder finishes later and its page may be stored, it is still
3612 stored: that is arrow (5).
3613 (5) a late builder finishes [200, may be stored]
3614 / the page is stored
3615 (6) the application script or a template file is changed
3616 / nothing happens yet; the entry is now older than the code
3617 (7) a request reads the entry [it is fresh]
3618 / the stored page is replayed with X-Cache: HIT; it is
3619 compressed for this client and gets its own ETag
3620 (8) cache_duration passes
3621 / the cache forgets the entry
3622 (9) a request reads the entry [it is older than the code]
3623 / the entry is removed; the request goes on as at (1)
3624  
3625 While BUILDING, a second request for the same key:
3626 - in the same worker: waits for (2), (3) or (4);
3627 - in another worker, with a shared lock: looks in the cache every
3628 0.1 seconds until the page appears, the lock is free, or
3629 cache_lock_timeout passes;
3630 - with cache_single_flight => 0: does not wait, and builds the page
3631 too.
3632  
3633 =head2 B. One request that calls buffer_is_cached
3634  
3635 buffer_is_cached
3636 |
3637 v
3638 +--------------+ (1) +--------+ (5) +-----------------+
3639 | RUN ACTION |<------| DECIDE |------>| BUILDER |
3640 | not cached | +--------+ | the action runs;|
3641 +--------------+ | | | | see picture C |
3642 (2)| | |(3) +-----------------+
3643 v | v
3644 REPLAYED | +----------------+ (8)
3645 | | WAITING_REMOTE |------> REPLAYED
3646 | | polls the cache| (9)
3647 | | 10 times a sec |------> 503
3648 | +----------------+
3649 | | ^
3650 (4)| +--(10)--+
3651 v
3652 +----------------+ (6)
3653 | WAITING_LOCAL |------> REPLAYED
3654 | same worker | (7)
3655 +----------------+------> 503
3656  
3657 (1) [the plugin is off, no cache, method not GET or HEAD, an
3658 Authorization header, Cache-Control no-store, no-cache, private
3659 or max-age=0, NO_CACHE or NO_STORE set, or the cache's get() died]
3660 / returns false: the action runs normally
3661 (2) [a fresh entry exists]
3662 / status, headers and body are replayed; X-Cache: HIT; the
3663 response is finished; returns true
3664 (3) [no entry; another worker holds the shared lock]
3665 / render_later; X-Cache: MISS; returns true
3666 (4) [no entry; a request in this worker is building it]
3667 / render_later; X-Cache: MISS; returns true
3668 (5) [no entry; nobody is building it, or single-flight is off]
3669 / X-Cache: MISS; returns false. If the lock backend failed, the
3670 error is logged and this worker builds without a shared lock.
3671 (6) the builder in this worker stored the page
3672 / the page is replayed with X-Cache: HIT
3673 (7) the builder failed, made something not storable, or
3674 cache_lock_timeout passed
3675 / 503 with Retry-After: 1 and the retry_later text
3676 (8) a poll finds the page in the cache
3677 / the page is replayed
3678 (9) a poll finds [cache_lock_timeout has passed], or [the lock is free
3679 but there is still no page], or [the lock backend failed]
3680 / 503 with Retry-After: 1
3681 (10) a poll finds [no page yet, and the lock is still held]
3682 / wait another 0.1 seconds
3683  
3684 Calling buffer_is_cached again in the same request returns the same
3685 answer and changes nothing.
3686  
3687 =head2 C. What the after_dispatch hook does with every response
3688  
3689 response finished by the action
3690 |
3691 v
3692 +-----------------+ (1)
3693 | 1. CHECK |-----------------------------------> sent as it is
3694 +-----------------+
3695 |
3696 v
3697 +-----------------+ [HTML and optimise_content on, and the result
3698 | 2. OPTIMISE | is smaller] / white space removed, links
3699 +-----------------+ shortened. Skipped for a replayed entry.
3700 |
3701 v
3702 +-----------------+ [compress_content on and type in
3703 | 3. COMPRESS | compressible_types] / Vary: Accept-Encoding;
3704 +-----------------+ then [client accepts a coding, body >=
3705 | min_compress_size, result at least
3706 | min_compress_saving bytes smaller]
3707 | / body compressed, Content-Encoding set
3708 |
3709 v
3710 +-----------------+ [buffer_is_cached ran, it was not a hit, the
3711 | 4. STORE | status is 200, the response may be stored]
3712 +-----------------+ / the uncompressed page goes into the cache
3713 |
3714 v
3715 +-----------------+ (2)
3716 | 5. VALIDATE |-----------------------------------> 304, no body
3717 +-----------------+
3718 |
3719 v
3720 +-----------------+
3721 | 6. SEND | the compressed or plain body; Content-Length
3722 +-----------------+
3723 |
3724 v
3725 if this request was the builder: answer every waiting request and
3726 release the shared lock (arrows (2) and (3) of picture A). This
3727 also happens when a step above dies.
3728  
3729 (1) [the stash says buffer => 0, or the body is empty, streamed or a
3730 file, or the status is 1xx, 204, 206 or 304, or a
3731 Content-Encoding is already set, or the media type is unknown or
3732 in excluded_types]
3733 (2) [GET or HEAD, status 200, generate_304 on, and If-None-Match
3734 matches the ETag; or there is no ETag (or trust_last_modified is
3735 on) and If-Modified-Since is not older than Last-Modified]
3736 / 304 Not Modified is sent with no body
3737  
3738 =head1 AUTHOR
3739  
3740 Nigel Horne, C<< <njh at nigelhorne.com> >>
3741  
3742 =head1 LICENCE AND COPYRIGHT
3743  
3744 Copyright 2026 Nigel Horne.
3745  
3746 Usage is subject to the GPL2 licence terms.
3747 If you use it,
3748 please let me know.
3749  
3750 =cut
3751  
3752 37 1;
↑ Summary blib/lib/Mojolicious/Plugin/Buffer/I18N.pm »