blib/lib/Mojo/UserAgent/Cached.pm

filter: Statementstmt 90.2% 295 / 327 Branchbran 76.0% 73 / 96 Conditioncond 47.0% 56 / 119 MC/DCmcdc 17.9% 12 / 67 Subroutinesub 98.4% 62 / 63 Podpod 66.6% 8 / 12 totaltotal 73.9% 506 / 684 CC 93 SCAR 29.6
CC
93
Cov
78%
_log_line
123.2
start
19.2
__ANON__
16.1
CRAP 19.3
↑ Summary
1 package Mojo::UserAgent::Cached;
2  
3 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use Algorithm::LCSS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Devel::StackTrace;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 5 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 5 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 5 ▶use List::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 5 ▶use Mojo::JSON qw/to_json/;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 5 ▶use Mojo::Transaction::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 5 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 5 ▶use Mojo::Log;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 5 ▶use Mojo::Base 'Mojo::UserAgent';
Subroutine BEGIN: called CC=1 SCAR=0.0
20 5 ▶use Mojo::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 5 ▶use POSIX qw/O_WRONLY O_APPEND O_CREAT/;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 5 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 5 ▶use String::Truncate;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 5 ▶use Time::HiRes qw/time/;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 5 Readonly my $HTTP_OK => 200;
27 5 Readonly my $HTTP_FILE_NOT_FOUND => 404;
28  
29 5 our $VERSION = '1.25';
30  
31 # TODO: Timeout, fallback
32 # TODO: Expected result content (json etc)
33  
34 # MOJO_USERAGENT_CONFIG
35 ## no critic (ProhibitMagicNumbers)
36 16 ▶has 'connect_timeout' => sub { $ENV{MOJO_CONNECT_TIMEOUT} // 10 };
Subroutine __ANON__: called CC=2 SCAR=6.9
Condition100%2/2
$ENV{"MOJO_CONNECT_TIMEOUT"} // 10
l!l
115
MC/DC100%1/1
$ENV{"MOJO_CONNECT_TIMEOUT"} // 10
$ENV{"MOJO_CONNECT_TIMEOUT"}
Truth table100%2/2
A
A= $ENV{"MOJO_CONNECT_TIMEOUT"}
Aresult
11
00
37 14 ▶has 'inactivity_timeout' => sub { $ENV{MOJO_INACTIVITY_TIMEOUT} // 20 };
Subroutine __ANON__: called CC=2 SCAR=6.9
Condition100%2/2
$ENV{"MOJO_INACTIVITY_TIMEOUT"} // 20
l!l
212
MC/DC100%1/1
$ENV{"MOJO_INACTIVITY_TIMEOUT"} // 20
$ENV{"MOJO_INACTIVITY_TIMEOUT"}
Truth table100%2/2
A
A= $ENV{"MOJO_INACTIVITY_TIMEOUT"}
Aresult
11
00
38 2 ▶has 'max_redirects' => sub { $ENV{MOJO_MAX_REDIRECTS} // 4 };
Subroutine __ANON__: called CC=2 SCAR=7.2
Condition50%1/2
$ENV{"MOJO_MAX_REDIRECTS"} // 4
l!l
20
MC/DC0%0/1
$ENV{"MOJO_MAX_REDIRECTS"} // 4
$ENV{"MOJO_MAX_REDIRECTS"}
Truth table50%1/2
A
A= $ENV{"MOJO_MAX_REDIRECTS"}
Aresult
11
00
39 17 ▶has 'request_timeout' => sub { $ENV{MOJO_REQUEST_TIMEOUT} // 0 };
Subroutine __ANON__: called CC=2 SCAR=6.9
Condition100%2/2
$ENV{"MOJO_REQUEST_TIMEOUT"} // 0
l!l
215
MC/DC100%1/1
$ENV{"MOJO_REQUEST_TIMEOUT"} // 0
$ENV{"MOJO_REQUEST_TIMEOUT"}
Truth table100%2/2
A
A= $ENV{"MOJO_REQUEST_TIMEOUT"}
Aresult
11
00
40 ## use critic
41  
42 # MUAC_CLIENT_CONFIG
43 4 ▶has 'local_dir' => sub { $ENV{MUAC_LOCAL_DIR} // q{} };
Subroutine __ANON__: called CC=2 SCAR=7.2
Condition50%1/2
$ENV{"MUAC_LOCAL_DIR"} // ""
l!l
04
MC/DC0%0/1
$ENV{"MUAC_LOCAL_DIR"} // ""
$ENV{"MUAC_LOCAL_DIR"}
Truth table50%1/2
A
A= $ENV{"MUAC_LOCAL_DIR"}
Aresult
11
00
44 22 ▶has 'always_return_file' => sub { $ENV{MUAC_ALWAYS_RETURN_FILE} // undef };
Subroutine __ANON__: called CC=2 SCAR=7.2
Condition50%1/2
$ENV{"MUAC_ALWAYS_RETURN_FILE"} // undef
l!l
022
MC/DC0%0/1
$ENV{"MUAC_ALWAYS_RETURN_FILE"} // undef
$ENV{"MUAC_ALWAYS_RETURN_FILE"}
Truth table50%1/2
A
A= $ENV{"MUAC_ALWAYS_RETURN_FILE"}
Aresult
11
00
45  
46 17 ▶has 'cache_agent' => sub {
Subroutine __ANON__: called CC=9 SCAR=27.8
47 $ENV{MUAC_NOCACHE} ? () : CHI->new(
48 driver => $ENV{MUAC_CACHE_DRIVER} || 'File',
49 root_dir => $ENV{MUAC_CACHE_ROOT_DIR} || '/tmp/mojo-useragent-cached',
50 serializer => $ENV{MUAC_CACHE_SERIALIZER} || 'Storable',
51 namespace => $ENV{MUAC_CACHE_NAMESPACE} || 'MUAC_Client',
52 expires_in => $ENV{MUAC_CACHE_EXPIRES_IN} // '1 minute',
53 expires_on_backend => $ENV{MUAC_CACHE_EXPIRES_ON_BACKEND} // 1,
54 max_key_length => 140,
55 17 ▶ %{ shift->cache_opts || {} },
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'MUAC_NOCACHE'} ? : 0 17 17
Condition50%7/14
$ENV{'MUAC_CACHE_DRIVER'} || 'File'
l!l
017
$ENV{'MUAC_CACHE_ROOT_DIR'} || '/tmp/mojo-useragent-cached'
l!l
017
$ENV{'MUAC_CACHE_SERIALIZER'} || 'Storable'
l!l
017
$ENV{'MUAC_CACHE_NAMESPACE'} || 'MUAC_Client'
l!l
017
$ENV{"MUAC_CACHE_EXPIRES_IN"} // "1 minute"
l!l
017
$ENV{"MUAC_CACHE_EXPIRES_ON_BACKEND"} // 1
l!l
017
(shift())->cache_opts || {}
l!l
170
MC/DC0%0/1
$ENV{'MUAC_CACHE_DRIVER'} || 'File'
$ENV{'MUAC_CACHE_DRIVER'}
MC/DC0%0/1
$ENV{'MUAC_CACHE_ROOT_DIR'} || '/tmp/mojo-useragent-cached'
$ENV{'MUAC_CACHE_ROOT_DIR'}
MC/DC0%0/1
$ENV{'MUAC_CACHE_SERIALIZER'} || 'Storable'
$ENV{'MUAC_CACHE_SERIALIZER'}
MC/DC0%0/1
$ENV{'MUAC_CACHE_NAMESPACE'} || 'MUAC_Client'
$ENV{'MUAC_CACHE_NAMESPACE'}
MC/DC0%0/1
$ENV{"MUAC_CACHE_EXPIRES_IN"} // "1 minute"
$ENV{"MUAC_CACHE_EXPIRES_IN"}
MC/DC0%0/1
$ENV{"MUAC_CACHE_EXPIRES_ON_BACKEND"} // 1
$ENV{"MUAC_CACHE_EXPIRES_ON_BACKEND"}
MC/DC0%0/1
(shift())->cache_opts || {}
(shift())->cache_opts
Truth table50%1/2
A
A= $ENV{'MUAC_CACHE_DRIVER'}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{'MUAC_CACHE_ROOT_DIR'}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{'MUAC_CACHE_SERIALIZER'}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{'MUAC_CACHE_NAMESPACE'}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{"MUAC_CACHE_EXPIRES_IN"}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{"MUAC_CACHE_EXPIRES_ON_BACKEND"}
Aresult
11
00
Truth table50%1/2
A
A= (shift())->cache_opts
Aresult
11
00
56 )
57 5 };
58 16 ▶has 'cache_opts' => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
59 5 ▶has 'cache_url_opts' => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
60 23 ▶has 'key_generator' => sub { \&key_generator_cb; };
Subroutine __ANON__: called CC=1 SCAR=0.0
61 23 ▶has 'logger' => sub { Mojo::Log->new() };
Subroutine __ANON__: called CC=1 SCAR=0.0
62 23 ▶has 'access_log' => sub { $ENV{MUAC_ACCESS_LOG} || '' };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"MUAC_ACCESS_LOG"} or "" 0 23 23
63 2 ▶has 'use_expired_cached_content' => sub { $ENV{MUAC_USE_EXPIRED_CACHED_CONTENT} // 1 };
Subroutine __ANON__: called CC=2 SCAR=7.2
Condition50%1/2
$ENV{"MUAC_USE_EXPIRED_CACHED_CONTENT"} // 1
l!l
02
MC/DC0%0/1
$ENV{"MUAC_USE_EXPIRED_CACHED_CONTENT"} // 1
$ENV{"MUAC_USE_EXPIRED_CACHED_CONTENT"}
Truth table50%1/2
A
A= $ENV{"MUAC_USE_EXPIRED_CACHED_CONTENT"}
Aresult
11
00
64 2 ▶has 'accepted_error_codes' => sub { $ENV{MUAC_ACCEPTED_ERROR_CODES} || '' };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"MUAC_ACCEPTED_ERROR_CODES"} or "" 0 2 2
65 5 has 'sorted_queries' => 1;
66  
67 5 has 'created_stacktrace' => '';
68  
69 37 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
70 37 my ($class, %opts) = @_;
71  
72 37 my %mojo_agent_config = map { $_ => $opts{$_} } grep { exists $opts{$_} } qw/
73 ca
74 cert
75 connect_timeout
76 cookie_jar
77 inactivity_timeout
78 insecure
79 ioloop
80 key
81 local_address
82 max_connections
83 max_redirects
84 max_response_size
85 proxy
86 request_timeout
87 server
88 transactor
89 /;
90  
91 37 my $ua = $class->SUPER::new(%mojo_agent_config);
92  
93 # Populate attributes
94 37 map { $ua->$_( $opts{$_} ) } grep { exists $opts{$_} } qw/
95 local_dir
96 always_return_file
97 cache_opts
98 cache_agent
99 cache_url_opts
100 logger
101 access_log
102 use_expired_cached_content
103 accepted_error_codes
104 sorted_queries
105 /;
106  
107 37 $ua->created_stacktrace($ua->_get_stacktrace);
108  
109 37 return bless($ua, $class);
110 }
111  
112  
113 6 ▶sub invalidate {
Subroutine invalidate: called CC=2 SCAR=7.4
Pod documented
114 6 my ($self, $key) = @_;
115  
116 6 ▶ if ($self->is_cacheable($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_cacheable($key)) 6 0 6
117 6 $self->logger->debug("Invalidating cache for '$key'");
118 6 return $self->cache_agent->remove($key);
119 }
120  
121 0 return;
122 }
123  
124 2 ▶sub expire {
Subroutine expire: called CC=2 SCAR=7.4
Pod documented
125 2 my ($self, $key) = @_;
126  
127 2 ▶ if ($self->is_cacheable($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_cacheable($key)) 2 0 2
128 2 $self->logger->debug("Expiring cache for '$key'");
129 2 return $self->cache_agent->expire($key);
130 }
131  
132 0 return;
133 }
134  
135 101 ▶sub build_tx {
Subroutine build_tx: called CC=6 SCAR=18.5
Pod documented
136 101 my ($self, $method, $url, @more) = @_;
137  
138 101 ▶ $url = ($self->always_return_file || $url);
Condition66%2/3
$self->always_return_file || $url
l!l&&r!l&&!r
2990
MC/DC0%0/2
$self->always_return_file || $url
$self->always_return_file $url
Truth table66%2/3
A || B
A= $self->always_return_fileB= $url
ABresult
1X1
011
000
139  
140 101 ▶ if ($url !~ m{^(/|[^/]+:)}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($url =~ m[^(/|[^/]+:)]u) 11 90 101
141 11 ▶ if ($self->local_dir) {
Branch: 3 branches
BranchTrueFalseTotal
if ($self->local_dir) { } 5 6 11
elsif ($self->always_return_file) { } 0 6 6
elsif (not $url =~ m[^(/|[^/]+:)]u) { } 6 0 6
142 5 $url = 'file://' . File::Spec->catfile($self->local_dir, "$url");
143 } elsif ($self->always_return_file) {
144 0 $url = 'file://' . "$url";
145 } elsif ($url !~ m{^(/|[^/]+:)}) {
146 6 $url = 'file://' . Cwd::realpath("$url");
147 }
148 }
149  
150 101 $self->transactor->tx($method, $url, @more);
151 }
152  
153 100 ▶sub start {
Subroutine start: called CC=19 SCAR=29.5
Pod documented
154 100 my ($self, $tx, $cb) = @_;
155  
156 100 my $url = $tx->req->url->to_unsafe_string;
157 100 my $method = $tx->req->method;
158 100 my $headers = $tx->req->headers->to_hash(1);
159 100 my $content = $tx->req->content->asset->slurp;
160 100 delete $headers->{'User-Agent'};
161 100 delete $headers->{'Accept-Encoding'};
162 100 ▶ my @opts = (($method eq 'GET' ? () : $method), (keys %{ $headers || {} } ? $headers : ()), $content || ());
Branch: 2 branches
BranchTrueFalseTotal
$method eq 'GET' ? : 82 18 100
keys %{$headers or {};} ? : 7 93 100
Condition80%4/5
$headers || {}
l!l
1000
$content || ()
l!l&&r!l&&!r
72568
MC/DC0%0/1
$headers || {}
$headers
MC/DC100%2/2
$content || ()
$content ()
Truth table50%1/2
A
A= $headers
Aresult
11
00
Truth table100%3/3
A || B
A= $contentB= ()
ABresult
1X1
011
000
163 100 my $key = $self->generate_key($url, @opts);
164 100 my $start_time = time;
165  
166 # Fork-safety
167 100 ▶ $self->_cleanup->server->restart if $self->{pid} && $self->{pid} ne $$;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pid"} and $self->{"pid"} ne $$ 3 97 100
Condition100%3/3
$self->{"pid"} and $self->{"pid"} ne $$
!ll&&!rl&&r
23743
MC/DC100%2/2
$self->{"pid"} and $self->{"pid"} ne $$
$self->{"pid"} $self->{"pid"} ne $$
Truth table100%3/3
A and B
A= $self->{"pid"}B= $self->{"pid"} ne $$
ABresult
0X0
100
111
168 100 ▶ $self->{pid} //= $$;
Condition66%2/3
$self->{"pid"} //= $$
l!l&&r!l&&!r
74260
MC/DC0%0/2
$self->{"pid"} //= $$
$self->{"pid"} $$
Truth table66%2/3
A //= B
A= $self->{"pid"}B= $$
ABresult
1X1
011
000
169  
170 # We wrap the incoming callback in our own callback to be able to cache the response
171 22 ▶ my $wrapper_cb = $cb ? sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
172 22 my ($ua, $tx) = @_;
173 22 $cb->($ua, $ua->_post_process_get($tx, $start_time, $key, @opts));
174 100 ▶ } : ();
Branch: 1 branch
BranchTrueFalseTotal
$cb ? : 25 75 100
175  
176 # Is an absolute URL or an URL relative to the app eg. http://foo.com/ or /foo.txt
177 100 ▶ if ($url !~ m{ \A file:// }gmx && (Mojo::URL->new($url)->is_abs || ($url =~ m{ \A / }gmx && !$self->always_return_file))) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $url =~ m[ \A file:// ]gmux and 'Mojo::URL'->new($url)->is_abs || $url =~ m[ \A / ]gmux && !$self->always_return_file) { } 88 12 100
Condition55%5/9
not $url =~ m[ \A file:// ]gmux and "Mojo::URL"->new($url)->is_abs || $url =~ m[ \A / ]gmux && !$self->always_return_file
!ll&&!rl&&r
12088
"Mojo::URL"->new($url)->is_abs or $url =~ m[ \A / ]gmux and not $self->always_return_file
l!l&&r!l&&!r
6820
$url =~ m[ \A / ]gmux and not $self->always_return_file
!ll&&!rl&&r
0082
MC/DC25%1/4
not $url =~ m[ \A file:// ]gmux and "Mojo::URL"->new($url)->is_abs || $url =~ m[ \A / ]gmux && !$self->always_return_file
not $url =~ m[ \A file:// ]gmux "Mojo::URL"->new($url)->is_abs $url =~ m[ \A / ]gmux not $self->always_return_file
Truth table60%3/5
not(A) and B or C and not(D)
A= not $url =~ m[ \A file:// ]gmuxB= "Mojo::URL"->new($url)->is_absC= $url =~ m[ \A / ]gmuxD= not $self->always_return_file
ABCDresult
0XXX0
100X0
10100
11XX1
10111
178 88 ▶ if ($self->is_cacheable($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_cacheable($key)) 27 61 88
179 27 my $serialized = $self->cache_agent->get($key);
180 27 ▶ if ($serialized) {
Branch: 1 branch
BranchTrueFalseTotal
if ($serialized) 14 13 27
181 14 $serialized->{events} = $tx->{events};
182 14 $serialized->{req_events} = $tx->req->{events};
183 14 $serialized->{res_events} = $tx->res->{events};
184 14 my $cached_tx = _build_fake_tx($serialized);
185 14 $self->_log_line($cached_tx, {
186 start_time => $start_time,
187 key => $key,
188 type => 'cached result',
189 });
190 14 $cached_tx->req->finish;
191 14 $cached_tx->res->finish;
192 14 $cached_tx->closed;
193 14 ▶ return $cb->($self, $cached_tx) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 2 12 14
194 12 return $cached_tx;
195 }
196 }
197  
198 # Non-blocking
199 74 ▶ if ($wrapper_cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wrapper_cb) 22 52 74
200 22 warn "-- Non-blocking request (@{[_url($tx)]})\n" if Mojo::UserAgent::DEBUG;
201 22 return $self->_start(Mojo::IOLoop->singleton, $tx, $wrapper_cb);
202 }
203  
204 # Blocking
205 52 warn "-- Blocking request (@{[_url($tx)]})\n" if Mojo::UserAgent::DEBUG;
206 52 ▶ $self->_start($self->ioloop, $tx => sub { shift->ioloop->stop; $tx = shift });
Subroutine __ANON__: called CC=1 SCAR=0.0
207 52 $self->ioloop->start;
208  
209 52 return $self->_post_process_get( $tx, $start_time, $key, @opts );
210 } else { # Local file eg. t/data/foo.txt or file://.*/
211 12 $url =~ s{file://}{};
212 12 my $code = $HTTP_FILE_NOT_FOUND;
213 12 my $res;
214 12 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $res = $self->_parse_local_file_res($url); $code = $res->{"code"} } } or $self->logger->error($Mojo::UserAgent::Cached::EVAL_ERROR) 10 2 12
215 12 $res = $self->_parse_local_file_res($url);
216 10 $code = $res->{code};
217 } or $self->logger->error($EVAL_ERROR);
218  
219 12 my $params = { url => $url, body => $res->{body}, code => $code, method => 'FILE', headers => $res->{headers}, events => $tx->{events}, req_events => $tx->req->{events}, res_events => $tx->res->{events} };
220  
221 # first non-blocking, if no callback, regular post process
222 12 my $tx = _build_fake_tx($params);
223 12 $self->_log_line($tx, {
224 start_time => $start_time,
225 key => $key,
226 type => 'local file',
227 });
228  
229 12 ▶ return $cb->($self, $tx) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 11 12
230 11 return $tx;
231 }
232  
233 0 return $tx;
234 }
235  
236 74 ▶sub _post_process_get {
Subroutine _post_process_get: called CC=6 SCAR=17.9
237 74 my ($self, $tx, $start_time, $key) = @_;
238  
239 74 ▶ if ( $tx->req->url->scheme ne 'file' && $self->is_cacheable($key) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tx->req->url->scheme ne "file" and $self->is_cacheable($key)) 13 61 74
Condition66%2/3
$tx->req->url->scheme ne "file" and $self->is_cacheable($key)
!ll&&!rl&&r
06113
MC/DC50%1/2
$tx->req->url->scheme ne "file" and $self->is_cacheable($key)
$tx->req->url->scheme ne "file" $self->is_cacheable($key)
Truth table66%2/3
A and B
A= $tx->req->url->scheme ne "file"B= $self->is_cacheable($key)
ABresult
0X0
100
111
240 13 ▶ if ( $self->is_considered_error($tx) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_considered_error($tx)) { } 4 9 13
241 # Return an expired+cached version of the page for other errors
242 4 ▶ if ( $self->use_expired_cached_content ) { # TODO: URL by URL, and case-by-case expiration
Branch: 1 branch
BranchTrueFalseTotal
if ($self->use_expired_cached_content) 4 0 4
243 4 ▶ if (my $cache_obj = $self->cache_agent->get_object($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cache_obj = $self->cache_agent->get_object($key)) 1 3 4
244 1 my $serialized = $cache_obj->value;
245 1 $serialized->{headers}->{'X-Mojo-UserAgent-Cached-ExpiresAt'} = $cache_obj->expires_at($key);
246 1 $serialized->{events} = $tx->{events};
247 1 $serialized->{req_events} = $tx->req->{events};
248 1 $serialized->{res_events} = $tx->res->{events};
249  
250 1 my $expired_tx = _build_fake_tx($serialized);
251 1 $self->_log_line( $expired_tx, {
252 start_time => $start_time,
253 key => $key,
254 type => 'expired and cached',
255 orig_tx => $tx,
256 });
257 1 $expired_tx->req->finish;
258 1 $expired_tx->res->finish;
259 1 $expired_tx->closed;
260  
261 1 return $expired_tx;
262 }
263 }
264 } else {
265 # Store object in cache
266 9 $self->cache_agent->set($key, _serialize_tx($tx), $self->_cache_url_opts($tx->req->url));
267 }
268 }
269  
270 73 $self->_log_line($tx, {
271 start_time => $start_time,
272 key => $key,
273 type => 'fetched',
274 });
275  
276 73 return $tx;
277 }
278  
279 9 ▶sub _cache_url_opts {
Subroutine _cache_url_opts: called CC=3 SCAR=11.2
280 9 my ($self, $url) = @_;
281 9 ▶ my ($pat, $opts) = List::Util::pairfirst { $url =~ /$a/; } %{ $self->cache_url_opts || {} };
Subroutine __ANON__: called CC=1 SCAR=0.1
Condition50%1/2
$self->cache_url_opts || {}
l!l
90
MC/DC0%0/1
$self->cache_url_opts || {}
$self->cache_url_opts
Truth table50%1/2
A
A= $self->cache_url_opts
Aresult
11
00
282 9 ▶ return $opts || ();
Condition66%2/3
$opts || ()
l!l&&r!l&&!r
180
MC/DC0%0/2
$opts || ()
$opts ()
Truth table66%2/3
A || B
A= $optsB= ()
ABresult
1X1
011
000
283 }
284  
285 1 ▶sub set {
Subroutine set: called CC=3 SCAR=12.3
Pod documented
286 1 my ($self, $url, $value, @opts) = @_;
287  
288 1 my $key = $self->generate_key($url, @opts);
289 1 ▶ $self->logger->debug("Illegal cache key: $key") && return if ref $key;
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 0 1 1
Condition20%1/5
ref $key && ($self->logger->debug("Illegal cache key: $key") && (return))
!ll&&!rl&&r
100
$self->logger->debug("Illegal cache key: $key") and return
!ll
00
MC/DC0%0/2
ref $key && ($self->logger->debug("Illegal cache key: $key") && (return))
ref $key $self->logger->debug("Illegal cache key: $key")
Truth table33%1/3
A && B
A= ref $keyB= $self->logger->debug("Illegal cache key: $key")
ABresult
0X0
100
111
290  
291 1 my $fake_tx = _build_fake_tx({
292 url => $key,
293 body => $value,
294 code => $HTTP_OK,
295 method => 'FILE'
296 });
297  
298 1 $self->logger->debug("Set cache key: $key");
299 1 $self->cache_agent->set($key, _serialize_tx($fake_tx));
300 1 return $key;
301 }
302  
303 4 ▶sub is_valid {
Subroutine is_valid: called CC=3 SCAR=11.2
Pod undocumented
304 4 my ($self, $key) = @_;
305  
306 4 ▶ ($self->logger->debug("Illegal cache key: $key") && return) if ref $key;
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 1 3 4
Condition60%3/5
ref $key && ($self->logger->debug("Illegal cache key: $key") && (return))
!ll&&!rl&&r
310
$self->logger->debug("Illegal cache key: $key") and return
!ll
01
MC/DC0%0/2
ref $key && ($self->logger->debug("Illegal cache key: $key") && (return))
ref $key $self->logger->debug("Illegal cache key: $key")
Truth table33%1/3
A && B
A= ref $keyB= $self->logger->debug("Illegal cache key: $key")
ABresult
0X0
100
111
307  
308 3 $self->logger->debug("Checking if key is valid: $key");
309 3 return $self->cache_agent->is_valid($key);
310 }
311  
312 133 ▶sub is_cacheable {
Subroutine is_cacheable: called CC=2 SCAR=7.1
Pod undocumented
313 133 my ($self, $url) = @_;
314  
315 133 ▶ return $self->cache_agent && ($url !~ m{ \A / }gmx);
Condition66%2/3
$self->cache_agent && !($url =~ m[ \A / ]gmux)
!ll&&!rl&&r
012211
MC/DC50%1/2
$self->cache_agent && !($url =~ m[ \A / ]gmux)
$self->cache_agent !($url =~ m[ \A / ]gmux)
Truth table66%2/3
A && not(B)
A= $self->cache_agentB= !($url =~ m[ \A / ]gmux)
ABresult
0X0
100
111
316 }
317  
318 113 ▶sub generate_key {
Subroutine generate_key: called CC=1 SCAR=0.0
Pod documented
319 113 my ($self, $url, @opts) = @_;
320  
321 113 return $self->key_generator->($self, $url, @opts);
322 }
323  
324 113 ▶sub key_generator_cb {
Subroutine key_generator_cb: called CC=3 SCAR=11.0
Pod undocumented
325 113 my ($self, $url, @opts) = @_;
326  
327 113 ▶ my $key = join q{,}, $self->sort_query($url), (@opts ? to_json(@opts > 1 ? \@opts : $opts[0]) : ());
Branch: 2 branches
BranchTrueFalseTotal
@opts ? : 33 80 113
@opts > 1 ? : 7 26 33
328  
329 113 return $key;
330 }
331  
332 13 ▶sub is_considered_error {
Subroutine is_considered_error: called CC=5 SCAR=16.2
Pod undocumented
333 13 my ($self, $tx) = @_;
334  
335 # If we find some error codes that should be accepted, we don't consider this an error
336 13 ▶ if ( $tx->error && $self->accepted_error_codes ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tx->error and $self->accepted_error_codes) 2 11 13
Condition100%3/3
$tx->error and $self->accepted_error_codes
!ll&&!rl&&r
742
MC/DC100%2/2
$tx->error and $self->accepted_error_codes
$tx->error $self->accepted_error_codes
Truth table100%3/3
A and B
A= $tx->errorB= $self->accepted_error_codes
ABresult
0X0
100
111
337 2 ▶ my $codes = ref $self->accepted_error_codes ? $self->accepted_error_codes
Branch: 1 branch
BranchTrueFalseTotal
ref $self->accepted_error_codes ? : 0 2 2
338 : [ ( $self->accepted_error_codes ) ];
339 2 ▶ return if List::Util::first { $tx->error->{code} == $_ } @{$codes};
Subroutine __ANON__: called CC=1 SCAR=0.1
Branch: 1 branch
BranchTrueFalseTotal
if &List::Util::first(sub { $tx->error->{"code"} == $_; } , @{$codes;}) 2 0 2
340 }
341  
342 11 return $tx->error;
343 }
344  
345 119 ▶sub sort_query {
Subroutine sort_query: called CC=8 SCAR=20.8
Pod documented
346 119 my ($self, $url) = @_;
347 119 ▶ return $url unless $self->sorted_queries;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->sorted_queries 0 119 119
348  
349 119 ▶ $url = Mojo::URL->new($url) unless ref $url eq 'Mojo::URL';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $url eq "Mojo::URL" 118 1 119
350  
351 119 ▶ my $flattened_sorted_url = ($url->protocol ? ( $url->protocol . '://' ) : '' ) .
Branch: 4 branches
BranchTrueFalseTotal
$url->protocol ? : 28 91 119
$url->userinfo ? : 1 118 119
$url->host ? : 16 103 119
$url->path ? : 119 0 119
352 ($url->userinfo ? ( $url->userinfo . '@' ) : '' ) .
353 ($url->host ? ( $url->host_port ) : '' ) .
354 ($url->path ? ( $url->path ) : '' ) ;
355  
356 7 ▶ $flattened_sorted_url .= '?' . join '&', sort { $a cmp $b } List::Util::pairmap { (($b ne '') ? (join '=', $a, $b) : $a); } @{ $url->query }
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$b ne '' ? : 16 5 21
357 119 ▶ if scalar @{ $url->query };
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$url->query;} 14 105 119
358  
359 119 return $flattened_sorted_url;
360 }
361  
362 10 ▶sub _serialize_tx {
Subroutine _serialize_tx: called CC=1 SCAR=0.0
363 10 my ($tx) = @_;
364  
365 10 $tx->res->headers->header('X-Mojo-UserAgent-Cached', time);
366  
367 return {
368 10 method => $tx->req->method,
369 url => $tx->req->url,
370 code => $tx->res->code,
371 body => $tx->res->body,
372 json => $tx->res->json,
373 headers => $tx->res->headers->to_hash,
374 };
375 }
376  
377 28 ▶sub _build_fake_tx {
Subroutine _build_fake_tx: called CC=2 SCAR=6.9
378 28 my ($opts) = @_;
379  
380 # Create transaction object to return so we look like a regular request
381 28 my $tx = Mojo::Transaction::HTTP->new();
382  
383 28 $tx->req->method($opts->{method});
384 28 $tx->req->url(Mojo::URL->new($opts->{url}));
385  
386 28 $tx->res->headers->from_hash($opts->{headers});
387  
388 28 my $now = time;
389 28 ▶ $tx->res->headers->header('X-Mojo-UserAgent-Cached-Age', $now - ($tx->res->headers->header('X-Mojo-UserAgent-Cached') || $now));
Condition66%2/3
$tx->res->headers->header('X-Mojo-UserAgent-Cached') || $now
l!l&&r!l&&!r
15130
MC/DC0%0/2
$tx->res->headers->header('X-Mojo-UserAgent-Cached') || $now
$tx->res->headers->header('X-Mojo-UserAgent-Cached') $now
Truth table66%2/3
A || B
A= $tx->res->headers->header('X-Mojo-UserAgent-Cached')B= $now
ABresult
1X1
011
000
390  
391 28 $tx->res->code($opts->{code});
392 28 $tx->res->{json} = $opts->{json};
393 28 $tx->res->body($opts->{body});
394  
395 28 $tx->{events} = $opts->{events};
396 28 $tx->req->{events} = $opts->{req_events};
397 28 $tx->res->{events} = $opts->{res_events};
398  
399 28 return $tx;
400 }
401  
402 12 ▶sub _parse_local_file_res {
Subroutine _parse_local_file_res: called CC=2 SCAR=6.9
403 12 my ($self, $url) = @_;
404  
405 12 my $headers;
406 12 my $body = Mojo::File->new($url)->slurp;
407 10 my $code = $HTTP_OK;
408 10 my $msg = 'OK';
409  
410 10 ▶ if ($body =~ m{\A (?: DELETE | GET | HEAD | OPTIONS | PATCH | POST | PUT ) \s }gmx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ /\A (?: DELETE | GET | HEAD | OPTIONS | PATCH | POST | PUT ) \s /gmux) 2 8 10
411 2 my $code_msg_headers;
412 my $code_msg;
413 2 my $http;
414 2 my $msg;
415 2 (undef, $code_msg_headers, $body) = split m{(?:\r\n|\n){2,}}mx, $body, 3; ## no critic (ProhibitMagicNumbers)
416 2 ($code_msg, $headers) = split m{(?:\r\n|\n)}mx, $code_msg_headers, 2;
417 2 ($http, $code, $msg) = $code_msg =~ m{ \A (?:(\S+) \s+)? (\d+) \s+ (.*) \z}mx;
418  
419 2 $headers = Mojo::Headers->new->parse("$headers\n\n")->to_hash;
420 }
421  
422 10 return { body => $body, code => $code, message => $msg, headers => $headers };
423 }
424  
425 100 ▶sub _write_local_file_res {
Subroutine _write_local_file_res: called CC=5 SCAR=27.4
426 100 my ($self, $tx, $dir) = @_;
427  
428 100 ▶ return unless ($dir && -e $dir && -d $dir);
Branch: 1 branch
BranchTrueFalseTotal
unless $dir and -e $dir and -d $dir 100 0 100
Condition33%2/6
$dir and -e $dir and -d $dir
!ll&&!rl&&r
10000
$dir and -e $dir
!ll&&!rl&&r
10000
MC/DC0%0/3
$dir and -e $dir and -d $dir
$dir -e $dir -d $dir
Truth table25%1/4
A and B and C
A= $dirB= -e $dirC= -d $dir
ABCresult
0XX0
10X0
1100
1111
429  
430 0 my $method = $tx->req->method;
431 0 my $url = $tx->req->url;
432 0 my $body = $tx->res->body;
433 0 my $code = $tx->res->code;
434 0 my $message = $tx->res->message;
435  
436 0 my $target_file = File::Spec->catfile($dir, split '/', $url->path_query);
437 0 File::Path::make_path(File::Basename::dirname($target_file));
438 0 ▶ Mojo::File->new($target_file)->spurt((
Branch: 1 branch
BranchTrueFalseTotal
"Mojo::File"->new($target_file)->spurt(join("\n\n", join(" ", $method, "$url\n") . $tx->req->headers->to_string, join(" ", $code, "$message\n") . $tx->res->headers->to_string, $body)) and $self->logger->debug("Wrote request+response to: '${target_file}'") 0 0 0
439 join "\n\n",
440 (join " ", $method, "$url\n" ) . $tx->req->headers->to_string,
441 (join " ", $code, "$message\n") . $tx->res->headers->to_string,
442 $body
443 )
444 ) and $self->logger->debug("Wrote request+response to: '$target_file'");
445 }
446  
447 100 ▶sub _log_line {
Subroutine _log_line: called CC=17 SCAR=48.1
448 100 my ($self, $tx, $opts) = @_;
449  
450 100 $self->_write_local_file_res($tx, $ENV{MUAC_CLIENT_WRITE_LOCAL_FILE_RES_DIR});
451  
452 100 my $callers = $self->_get_stacktrace;
453 100 my $created_stacktrace = $self->created_stacktrace;
454  
455 # Remove common parts to get smaller created stacktrace
456 100 my $strings = Algorithm::LCSS::CSS_Sorted( [ split /,/, $callers ] , [ split /,/, $created_stacktrace ] );
457 map {
458 24 my @lcss = @{$_};
459 24 my $pat = join ",", @lcss[1..$#lcss-1];
460 24 ▶ if (scalar @lcss > 2) { $created_stacktrace =~ s{$pat}{,}mx }
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @lcss > 2) 24 0 24
461 100 ▶ } @{ $strings || [] };
Condition50%1/2
$strings || []
l!l
1000
MC/DC0%0/1
$strings || []
$strings
Truth table50%1/2
A
A= $strings
Aresult
11
00
462  
463 $self->logger->debug(sprintf(q{Returning %s '%s' => %s for %s (%s)}, (
464 $opts->{type},
465 String::Truncate::elide( $tx->req->url, 150, { truncate => 'middle'} ),
466 100 ▶ ($tx->res->code || $tx->res->error->{code} || $tx->res->error->{message}),
Condition66%4/6
$tx->res->code || $tx->res->error->{'code'} || $tx->res->error->{'message'}
l!l&&r!l&&!r
9190
$tx->res->code or $tx->res->error->{"code"}
l!l&&r!l&&!r
9109
MC/DC0%0/3
$tx->res->code || $tx->res->error->{'code'} || $tx->res->error->{'message'}
$tx->res->code $tx->res->error->{"code"} $tx->res->error->{'message'}
Truth table50%2/4
A or B || C
A= $tx->res->codeB= $tx->res->error->{"code"}C= $tx->res->error->{'message'}
ABCresult
1XX1
01X1
0011
0000
467 $callers, $created_stacktrace
468 )));
469  
470 100 ▶ return unless $self->access_log;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->access_log 100 0 100
471  
472 0 my $elapsed_time = sprintf '%.3f', (time-$opts->{start_time});
473  
474 0 my $NONE = q{-};
475  
476 0 ▶ my $http_host = $tx->req->url->host || $NONE;
Condition0%0/3
$tx->req->url->host || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
$tx->req->url->host || $NONE
$tx->req->url->host $NONE
Truth table0%0/3
A || B
A= $tx->req->url->hostB= $NONE
ABresult
1X1
011
000
477 0 my $remote_addr = $NONE;
478 0 ▶ my $time_local = POSIX::strftime('%d/%b/%Y:%H:%M:%S %z', localtime) || $NONE;
Condition0%0/3
POSIX::strftime('%d/%b/%Y:%H:%M:%S %z', localtime) || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
POSIX::strftime('%d/%b/%Y:%H:%M:%S %z', localtime) || $NONE
POSIX::strftime('%d/%b/%Y:%H:%M:%S %z', localtime) $NONE
Truth table0%0/3
A || B
A= POSIX::strftime('%d/%b/%Y:%H:%M:%S %z', localtime)B= $NONE
ABresult
1X1
011
000
479 0 ▶ my $request = ($tx->req->method . q{ } . $tx->req->url->path_query) || $NONE;
Condition0%0/3
$tx->req->method . ' ' . $tx->req->url->path_query || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
$tx->req->method . ' ' . $tx->req->url->path_query || $NONE
$tx->req->method . ' ' . $tx->req->url->path_query $NONE
Truth table0%0/3
A || B
A= $tx->req->method . ' ' . $tx->req->url->path_queryB= $NONE
ABresult
1X1
011
000
480 0 ▶ my $status = $tx->res->code || $NONE;
Condition0%0/3
$tx->res->code || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
$tx->res->code || $NONE
$tx->res->code $NONE
Truth table0%0/3
A || B
A= $tx->res->codeB= $NONE
ABresult
1X1
011
000
481 0 ▶ my $body_bytes_sent = length $tx->res->body || $NONE;
Condition0%0/3
length $tx->res->body || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
length $tx->res->body || $NONE
length $tx->res->body $NONE
Truth table0%0/3
A || B
A= length $tx->res->bodyB= $NONE
ABresult
1X1
011
000
482 0 ▶ my $http_referer = $callers || $NONE;
Condition0%0/3
$callers || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
$callers || $NONE
$callers $NONE
Truth table0%0/3
A || B
A= $callersB= $NONE
ABresult
1X1
011
000
483 0 ▶ my $http_user_agent = __PACKAGE__ . "(" . $opts->{type} .")" || $NONE;
Condition0%0/3
'Mojo::UserAgent::Cached(' . $opts->{'type'} . ')' || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
'Mojo::UserAgent::Cached(' . $opts->{'type'} . ')' || $NONE
'Mojo::UserAgent::Cached(' . $opts->{'type'} . ')' $NONE
Truth table0%0/3
A || B
A= 'Mojo::UserAgent::Cached(' . $opts->{'type'} . ')'B= $NONE
ABresult
1X1
011
000
484 0 ▶ my $request_time = $elapsed_time || $NONE;
Condition0%0/3
$elapsed_time || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
$elapsed_time || $NONE
$elapsed_time $NONE
Truth table0%0/3
A || B
A= $elapsed_timeB= $NONE
ABresult
1X1
011
000
485 0 ▶ my $upstream_response_time = $elapsed_time || $NONE;
Condition0%0/3
$elapsed_time || $NONE
l!l&&r!l&&!r
000
MC/DC0%0/2
$elapsed_time || $NONE
$elapsed_time $NONE
Truth table0%0/3
A || B
A= $elapsed_timeB= $NONE
ABresult
1X1
011
000
486 0 my $http_x_forwarded_for = $NONE;
487  
488 # Use sysopen, slightly slower and hits disk, but avoids clobbering
489 0 sysopen my $fh, $self->access_log, O_WRONLY | O_APPEND | O_CREAT; ## no critic (ProhibitBitwiseOperators)
490 0 ▶ syswrite $fh, qq{$http_host $remote_addr [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time $upstream_response_time "$http_x_forwarded_for"\n}
Branch: 1 branch
BranchTrueFalseTotal
syswrite $fh, qq[$http_host $remote_addr [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time $upstream_response_time "$http_x_forwarded_for"\n] or $self->logger->warn(q[Unable to write to '] . $self->access_log . "': $Mojo::UserAgent::Cached::OS_ERROR") 0 0 0
491 or $self->logger->warn("Unable to write to '" . $self->access_log . "': $OS_ERROR");
492 0 ▶ close $fh or $self->logger->warn("Unable to close '" . $self->access_log . "': $OS_ERROR");
Branch: 1 branch
BranchTrueFalseTotal
close $fh or $self->logger->warn(q[Unable to close '] . $self->access_log . "': $Mojo::UserAgent::Cached::OS_ERROR") 0 0 0
493  
494 0 return;
495 }
496  
497 137 ▶sub _get_stacktrace {
Subroutine _get_stacktrace: called CC=3 SCAR=11.1
498 137 my ($self) = @_;
499  
500 my @frames = ( Devel::StackTrace->new(
501 ignore_class => [ 'Devel::StackTrace', 'Mojo::UserAgent::Cached', 'Template::Document', 'Template::Context', 'Template::Service' ],
502 618 ▶ frame_filter => sub { ($_[0]->{caller}->[0] !~ m{ \A Mojo | Try }gmx) },
Subroutine __ANON__: called CC=1 SCAR=0.0
503 137 )->frames() );
504  
505 137 my $prev_package = '';
506 my $callers = join q{,}, map {
507 299 my $package = $_->package;
508 299 ▶ if ($package eq 'Template::Provider') {
Branch: 1 branch
BranchTrueFalseTotal
if ($package eq "Template::Provider") 0 299 299
509 0 $package = (join "/", grep { $_ } (split '/', $_->filename)[-3..-1]);
510 }
511 299 ▶ if ($prev_package eq $package) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prev_package eq $package) { } 42 257 299
512 42 $package = '';
513 } else {
514 257 $prev_package = $package;
515 257 $package =~ s/(?:(\w)\w*::)/$1./gmx;
516 257 $package .= ':';
517 }
518 299 $package . $_->line();
519 137 } grep { $_ } @frames;
520 }
521  
522 0 ▶sub _url { shift->req->url->to_abs }
Subroutine _url: not called CC=1 SCAR=6.9
523  
524 5 1;
525  
526 =encoding utf8
527  
528 =head1 NAME
529  
530 Mojo::UserAgent::Cached - Caching, Non-blocking I/O HTTP, Local file and WebSocket user agent
531  
532 =head1 SYNOPSIS
533  
534 use Mojo::UserAgent::Cached;
535  
536 my $ua = Mojo::UserAgent::Cached->new;
537  
538 =head1 DESCRIPTION
539  
540 L<Mojo::UserAgent::Cached> is a full featured caching, non-blocking I/O HTTP, Local file and WebSocket user
541 agent, with IPv6, TLS, SNI, IDNA, Comet (long polling), keep-alive, connection
542 pooling, timeout, cookie, multipart, proxy, gzip compression and multiple
543 event loop support.
544  
545 It inherits all of the features L<Mojo::UserAgent> provides but in addition allows you to
546 retrieve cached content using a L<CHI> compatible caching engine.
547  
548 See L<Mojo::UserAgent> and L<Mojolicious::Guides::Cookbook/"USER AGENT"> for more.
549  
550 =head1 ATTRIBUTES
551  
552 L<Mojo::UserAgent::Cached> inherits all attributes from L<Mojo::UserAgent> and implements the following new ones.
553  
554 =head2 local_dir
555  
556 my $local_dir = $ua->local_dir;
557 $ua->local_dir('/path/to/local_files');
558  
559 Sets the local dir, used as a prefix where relative URLs are fetched from. A C<get('foobar.txt')> request would
560 read the file '/tmp/foobar.txt' if local_dir is set to '/tmp', defaults to the value of the
561 C<MUAC_LOCAL_DIR> environment variable and if not set, to ''.
562  
563 =head2 always_return_file
564  
565 my $file = $ua->always_return_file;
566 $ua->always_return_file('/tmp/default_file.txt');
567  
568 Makes all consecutive request return the same file, no matter what file or URL is requested with C<get()>, defaults
569 to the value of the C<MUAC_ALWAYS_RETURN_FILE> environment value and if not, it respects the File/URL in the request.
570  
571 =head2 cache_agent
572  
573 my $cache_agent = $ua->cache_agent;
574 $ua->cache_agent(CHI->new(
575 driver => $ENV{MUAC_CACHE_DRIVER} || 'File',
576 root_dir => $ENV{MUAC_CACHE_ROOT_DIR} || '/tmp/mojo-useragent-cached',
577 serializer => $ENV{MUAC_CACHE_SERIALIZER} || 'Storable',
578 namespace => $ENV{MUAC_CACHE_NAMESPACE} || 'MUAC_Client',
579 expires_in => $ENV{MUAC_CACHE_EXPIRES_IN} // '1 minute',
580 expires_on_backend => $ENV{MUAC_CACHE_EXPIRES_ON_BACKEND} // 1,
581 ));
582  
583 Tells L<Mojo::UserAgent::Cached> which cache_agent to use. It needs to be CHI-compliant and defaults to the above settings.
584  
585 You may also set the C<$ENV{MUAC_NOCACHE}> environment variable to avoid caching at all.
586  
587 =head2 cache_opts
588  
589 my $cache_opts = $ua->cache_opts;
590 $ua->cache_opts({ expires_in => '5 minutes' });
591  
592 Allows passing in cache options that will be appended to existing options in default cache agent creation.
593  
594 =head2 cache_url_opts
595  
596 my $urls_href = $ua->cache_url_opts;
597 $ua->cache_url_opts({
598 'https?://foo.com/long-lasting-data.*' => { expires_in => '2 weeks' }, # Cache some data two weeks
599 '.*' => { expires_at => 0 }, # Don't store anything in cache
600 });
601
602 Accepts a hash ref of regexp strings and expire times, this allows you to define cache validity time for individual URLs, hosts etc.
603 The first match will be used.
604  
605 =head2 key_generator
606  
607 A callback method to generate keys. The method gets ($self, $url, @opts) passed as parameters. The default is set to C<key_generator_cb>
608  
609 =head2 logger
610  
611 Provide a logging object, defaults to Mojo::Log
612  
613 # Example:
614 # Returning fetched 'https://graph.facebook.com?ids=http%3A%2F%2Fexample.com%2Flivet%2F20...-lommebok&access_token=1234' => 200 for A.C.Facebook:133,185,183,A.M.F.ArticleList:19,9,A.M.Selector:47,responsive/modules/most-shared.html.tt:15,15,13,templates/inc/macros.tt:125,138,templates/responsive/frontpage.html.tt:10,10,16,Template:66,A.G.C.Article:338,147,main:14 (A.C.Facebook:68,E.C.Sandbox_874:7,A.C.Facebook:133,,,main:14)
615  
616 Format:
617 Returning <cache-status> '<URL>' => 'HTTP code' for <request_stacktrace> (<created_stacktrace>)
618  
619 cache-status: (cached|fetched|cached+expired)
620 URL: the URL requested, shortened when it is really long
621 request_stacktrace: Simplified stacktrace with leading module names shortened, also includes TT stacktrace support. Line numbers in the same module are grouped (order kept of course).
622 created_stacktrace: Stack trace for creation of UA object, useful to see what options went in, and which object is used. Same format as normal stacktrace, but skips common parts.
623
624 Example:
625 created_stacktrace: A.C.Facebook:68,E.C.Sandbox_874:7,A.C.Facebook:133,<common part replaced>,main:14
626 stacktrace: A.C.Facebook:133,< common part: 185,183,A.M.F.ArticleList:19,9,A.M.Selector:47,responsive/modules/most-shared.html.tt:15,15,13,templates/inc/macros.tt:125,138,templates/responsive/frontpage.html.tt:10,10,16,Template:66,A.G.C.Article:338,147 >,main:14
627  
628 =head2 access_log
629  
630 A file that will get logs of every request, the format is a hybrid of Apache combined log, including time spent for the request.
631 If provided the file will be written to. Defaults to C<$ENV{MUAC_ACCESS_LOG} || ''> which means no log will be written.
632  
633 =head2 use_expired_cached_content
634  
635 Indicates that we will send expired, cached content back. This means that if a request fails, and the cache has expired, you
636 will get back the last successful content. Defaults to C<$ENV{MUAC_EXPIRED_CONTENT} // 1>
637  
638 =head2 accepted_error_codes
639  
640 A list of error codes that should not be considered as errors. For instance this means that the client will not look for expired
641 cached content for requests that result in this response. Defaults to C<$ENV{MUAC_ACCEPTED_ERROR_CODES} || ''>
642  
643 =head2 sorted_queries
644  
645 Setting this to a true value will sort query parameters in the resulting URL. This means that requests will be identical if the key/value pairs
646 are the same. This helps when URLs have been built up using hashes that may have random orders.
647  
648 =head1 OVERRIDEN ATTRIBUTES
649  
650 In addition L<Mojo::UserAgent::Cached> overrides the following L<Mojo::UserAgent> attributes.
651  
652 =head2 connect_timeout
653  
654 Defaults to C<$ENV{MOJO_CONNECT_TIMEOUT} // 2>
655  
656 =head2 inactivity_timeout
657  
658 Defaults to C<$ENV{MOJO_INACTIVITY_TIMEOUT} // 5>
659  
660 =head2 max_redirects
661  
662 Defaults to C<$ENV{MOJO_MAX_REDIRECTS} // 4>
663  
664 =head2 request_timeout
665  
666 Defaults to C<$ENV{MOJO_REQUEST_TIMEOUT} // 10>
667  
668 =head1 METHODS
669  
670 L<Mojo::UserAgent::Cached> inherits all methods from L<Mojo::UserAgent> and
671 implements the following new ones.
672  
673 =head2 invalidate
674  
675 $ua->invalidate($key);
676  
677 Deletes the cache of the given $key.
678  
679 =head2 expire
680  
681 $ua->expire($key);
682  
683 Set the cache of the given $key as expired.
684  
685 =head2 set
686  
687 my $tx = $ua->build_tx(GET => "http://localhost:$port", ...);
688 $tx = $ua->start($tx);
689 my $cache_key = $ua->generate_key("http://localhost:$port", ...);
690 $ua->set($cache_key, $tx);
691  
692 Set allows setting data directly for a given URL
693  
694 =head2 generate_key(@params)
695  
696 Returns a key to be used for the cache agent. It accepts the same parameters
697 that a normal ->get() request does.
698  
699 =head2 validate_key
700  
701 my $status = $ua4->validate_key('http://example.com');
702  
703 Fast validates if key is valid in cache without doing fetch.
704 Return 1 if true.
705  
706 =head2 sort_query($url)
707  
708 Returns a string with the URL passed, with sorted query parameters suitable for cache lookup
709  
710 =head1 OVERRIDEN METHODS
711  
712 =head2 new
713  
714 my $ua = Mojo::UserAgent::Cached->new( request_timeout => 1, ... );
715  
716 Accepts the attributes listed above and all attributes from L<Mojo::UserAgent>.
717 Stores its own attributes and passes on the relevant ones when creating a
718 parent L<Mojo::UserAgent> object that it inherits from. Returns a L<Mojo::UserAgent::Cached> object
719  
720 =head2 get(@params)
721  
722 my $tx = $ua->get('http://example.com');
723  
724 Accepts the same arguments and returns the same as L<Mojo::UserAgent>.
725  
726 It will try to return a cached version of the $url, adhering to the set or default attributes.
727  
728 In addition if a relative file path is given, it tries to return the file appended to
729 the attribute C<local_dir>. In this case a fake L<Mojo::Transaction::HTTP> object is returned,
730 populated with a L<Mojo::Message::Request> with method and url, and a L<Mojo::Message::Response>
731 with headers, code and body set.
732  
733 =head1 ENVIRONMENT VARIABLES
734  
735 C<$ENV{MUAC_CLIENT_WRITE_LOCAL_FILE_RES_DIR}> can be set to a directory to store a request in:
736  
737 # Re-usable local file with headers and metadata ends up at 't/data/dir/lol/foo.html?bar=1'
738 $ENV{MUAC_CLIENT_WRITE_LOCAL_FILE_RES_DIR}='t/data/dir';
739 Mojo::UserAgent::Cached->new->get("http://foo.com/lol/foo.html?bar=1");
740  
741 =head1 SEE ALSO
742  
743 L<Mojo::UserAgent>, L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
744  
745 =head1 COPYRIGHT
746  
747 Nicolas Mendoza (2015-), ABC Startsiden (2015)
748  
749 =head1 LICENSE
750  
751 Same as Perl licence as per agreement with ABC Startsiden on 2015-06-02
752  
753 =cut
↑ Summary