blib/lib/CGI/Cache.pm

filter: Statementstmt 87.9% 168 / 191 Branchbran 79.4% 62 / 78 Conditioncond 55.5% 15 / 27 MC/DCmcdc 20.0% 3 / 15 Subroutinesub 83.7% 31 / 37 Podpod 100% 9 / 9 totaltotal 80.6% 288 / 357 CC 49 SCAR 16.4
CC
49
Cov
83%
_bind
14.8
_unbind
6.0
warn
6.0
CRAP 5.2
↑ Summary
1 package CGI::Cache;
2  
3 25 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 25 ▶use vars qw( $VERSION );
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 25 ▶use 5.005;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 25 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 25 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 25 ▶use File::Spec::Functions qw( tmpdir );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 25 ▶use Cache::SizeAwareFileCache;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 25 ▶use Tie::Restore;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 25 ▶use Storable qw( freeze );
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 25 $VERSION = sprintf "%d.%02d%02d", q/1.42.7/ =~ /(\d+)/g;
15  
16 # --------------------------------------------------------------------------
17  
18 # Global because CatchSTDOUT and CatchSTDERR need them
19 25 use vars qw( $THE_CAPTURED_OUTPUT $OUTPUT_HANDLE $ERROR_HANDLE
20 25 ▶ $WROTE_TO_STDERR $ENABLE_OUTPUT );
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 # Global because test script needs them. They really should be lexically
23 # scoped to this package.
24 25 ▶use vars qw( $THE_CACHE $THE_CACHE_KEY $CACHE_PATH );
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 # 1 indicates that we started capturing output
27 25 my $CAPTURE_STARTED = 0;
28  
29 # 1 indicates that we are currently capturing output
30 25 my $CAPTURING = 0;
31  
32 # The cache key
33 25 $THE_CACHE_KEY = undef;
34  
35 # The cache
36 25 $THE_CACHE = undef;
37  
38 # Path to cache. Used by test harness to clean things up.
39 25 $CACHE_PATH = '';
40  
41 # The temporarily stored output
42 25 $THE_CAPTURED_OUTPUT = '';
43  
44 # Indicates whether output should be sent to the output filehandle when
45 # print() is called.
46 25 $ENABLE_OUTPUT = 1;
47  
48 # Used to determine if there was an error in the script that caused it to
49 # write to STDERR
50 25 $WROTE_TO_STDERR = 0;
51 25 my $CALLED_WARN_OR_DIE = 0;
52  
53 # The filehandles to monitor. These are normally STDOUT and STDERR.
54 25 my $WATCHED_OUTPUT_HANDLE = undef;
55 25 my $WATCHED_ERROR_HANDLE = undef;
56  
57 # References to the filehandles to send output to. These are normally STDOUT
58 # and STDERR.
59 25 $OUTPUT_HANDLE = undef;
60 25 $ERROR_HANDLE = undef;
61  
62 # Used to store the old tie'd variables, if any. (Under mod_perl,
63 # STDOUT is tie'd to the Apache module.) Undef means that there is no
64 # old tie.
65 25 my $OLD_STDOUT_TIE = undef;
66 25 my $OLD_STDERR_TIE = undef;
67  
68 # Overwrite the CORE warn and die. Sometime after 5.6.1, modules like
69 # CGI::Carp started using CORE::GLOBAL::die instead of $SIG{__DIE__} to
70 # override the default die. This "use subs" will handle this new way of doing
71 # things. In addition, we later point $SIG{__DIE__} to our die implementation.
72 # NOTE: I'm not sure what will happen if someone sets CORE::GLOBAL::die *and*
73 # $SIG{__DIE__}
74 25 ▶use subs qw( warn die );
Subroutine BEGIN: called CC=1 SCAR=0.0
75  
76 # The original warn and die handlers
77 25 my $OLD_WARN_SIG = undef;
78 25 my $OLD_DIE_SIG = undef;
79  
80 # --------------------------------------------------------------------------
81  
82 sub warn
83 {
84 0 ▶ $CALLED_WARN_OR_DIE = 1;
Subroutine warn: not called CC=2 SCAR=17.9
85  
86 # $OLD_WARN_SIG will be defined if the previously defined handler was set
87 # using signals. Otherwise it will have no effect.
88 0 ▶ if ($OLD_WARN_SIG)
Branch: 1 branch
BranchTrueFalseTotal
if ($OLD_WARN_SIG) { } 0 0 0
89 {
90 0 &$OLD_WARN_SIG(@_);
91 }
92 else
93 {
94 0 CORE::warn(@_);
95 }
96 }
97  
98 # --------------------------------------------------------------------------
99  
100 sub die
101 {
102 1 ▶ $CALLED_WARN_OR_DIE = 1;
Subroutine die: called CC=2 SCAR=7.6
103  
104 # $OLD_DIE_SIG will be defined if the previously defined handler was set
105 # using signals. Otherwise it will have no effect.
106 1 ▶ if ($OLD_DIE_SIG)
Branch: 1 branch
BranchTrueFalseTotal
if ($OLD_DIE_SIG) { } 1 0 1
107 {
108 1 &$OLD_DIE_SIG(@_);
109 }
110 else
111 {
112 0 CORE::die(@_);
113 }
114 }
115  
116 # --------------------------------------------------------------------------
117  
118 # This end block ensures that the captured output will be written to a
119 # file if the CGI script exits before calling stop(). However, stop()
120 # will not automatically be called if the script is exiting via a die
121  
122 END
123 {
124 24 ▶ return unless $CAPTURE_STARTED;
Subroutine END: called CC=5 SCAR=16.1
Branch: 1 branch
BranchTrueFalseTotal
unless $CAPTURE_STARTED 14 10 24
125  
126 # Unfortunately, die() writes to STDERR in a magical way that doesn't allow
127 # us to catch it. In this case we check $? for an error code.
128 10 ▶ if ( $CALLED_WARN_OR_DIE || $WROTE_TO_STDERR || $? == 2 )
Branch: 1 branch
BranchTrueFalseTotal
if ($CALLED_WARN_OR_DIE or $CGI::Cache::WROTE_TO_STDERR or $? == 2) { } 4 6 10
Condition83%5/6
$CALLED_WARN_OR_DIE or $CGI::Cache::WROTE_TO_STDERR or $? == 2
l!l&&r!l&&!r
406
$CALLED_WARN_OR_DIE or $CGI::Cache::WROTE_TO_STDERR
l!l&&r!l&&!r
136
MC/DC66%2/3
$CALLED_WARN_OR_DIE or $CGI::Cache::WROTE_TO_STDERR or $? == 2
$CALLED_WARN_OR_DIE $CGI::Cache::WROTE_TO_STDERR $? == 2
Truth table75%3/4
A or B or C
A= $CALLED_WARN_OR_DIEB= $CGI::Cache::WROTE_TO_STDERRC= $? == 2
ABCresult
1XX1
01X1
0011
0000
129 {
130 4 stop( 0 );
131 }
132 else
133 {
134 6 stop( 1 );
135 }
136 }
137  
138 # --------------------------------------------------------------------------
139  
140 # Initialize the cache
141  
142 sub setup
143 {
144 33 ▶ my $options = shift;
Subroutine setup: called CC=5 SCAR=16.4
Pod documented
145  
146 33 ▶ $options = {} unless defined $options;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options 1 32 33
147  
148 33 ▶ die "CGI::Cache::setup() takes a single hash reference for options"
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($options, "HASH") and not @_ 0 33 33
Condition33%1/3
UNIVERSAL::isa($options, "HASH") and not @_
!ll&&!rl&&r
0033
MC/DC0%0/2
UNIVERSAL::isa($options, "HASH") and not @_
UNIVERSAL::isa($options, "HASH") not @_
Truth table33%1/3
A and not(B)
A= UNIVERSAL::isa($options, "HASH")B= not @_
ABresult
0X0
100
111
149 unless UNIVERSAL::isa($options, 'HASH') && !@_;
150  
151 33 $options = _set_defaults( $options );
152  
153 33 $THE_CACHE = new Cache::SizeAwareFileCache( $options->{cache_options} );
154 33 ▶ die "Cache::SizeAwareFileCache::new failed\n" unless defined $THE_CACHE;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $CGI::Cache::THE_CACHE 0 33 33
155  
156 33 $WATCHED_OUTPUT_HANDLE = $options->{watched_output_handle};
157 33 $WATCHED_ERROR_HANDLE = $options->{watched_error_handle};
158  
159 33 $OUTPUT_HANDLE = $options->{output_handle};
160 33 $ERROR_HANDLE = $options->{error_handle};
161  
162 33 $ENABLE_OUTPUT = $options->{enable_output};
163  
164 33 return 1;
165 }
166  
167 # --------------------------------------------------------------------------
168  
169 sub _set_defaults
170 {
171 33 ▶ my $options = shift;
Subroutine _set_defaults: called CC=6 SCAR=17.9
172  
173 $options->{cache_options} =
174 33 _set_cache_defaults( $options->{cache_options} );
175  
176 $options->{watched_output_handle} = \*STDOUT
177 33 ▶ unless defined $options->{watched_output_handle};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"watched_output_handle"} 25 8 33
178  
179 $options->{watched_error_handle} = \*STDERR
180 33 ▶ unless defined $options->{watched_error_handle};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"watched_error_handle"} 27 6 33
181  
182 $options->{output_handle} = $options->{watched_output_handle}
183 33 ▶ unless defined $options->{output_handle};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"output_handle"} 24 9 33
184  
185 $options->{error_handle} = $options->{watched_error_handle}
186 33 ▶ unless defined $options->{error_handle};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"error_handle"} 27 6 33
187  
188 $options->{enable_output} = 1
189 33 ▶ unless defined $options->{enable_output};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"enable_output"} 31 2 33
190  
191 33 return $options;
192 }
193  
194 # --------------------------------------------------------------------------
195  
196 sub _set_cache_defaults
197 {
198 33 ▶ my $cache_options = shift;
Subroutine _set_cache_defaults: called CC=6 SCAR=17.9
199  
200 # Set default value for namespace
201 33 ▶ unless ( defined $cache_options->{namespace} )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cache_options->{"namespace"}) 32 1 33
202 {
203 # Script name may not be defined if we are running in off-line mode
204 32 ▶ if ( defined $ENV{SCRIPT_NAME} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{'SCRIPT_NAME'}) { } 31 1 32
205 {
206 ( undef, undef, $cache_options->{namespace} ) =
207 31 File::Spec->splitpath( $ENV{SCRIPT_NAME}, 0 );
208 }
209 else
210 {
211 1 ( undef, undef, $cache_options->{namespace} ) =
212 File::Spec->splitpath( $0, 0 );
213 }
214 }
215  
216 # Set default value for expires_in
217 $cache_options->{default_expires_in} = $Cache::Cache::EXPIRES_NEVER
218 33 ▶ unless defined $cache_options->{default_expires_in};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cache_options->{"default_expires_in"} 31 2 33
219  
220 # Set default value for cache root
221 $cache_options->{cache_root} = _compute_default_cache_root()
222 33 ▶ unless defined $cache_options->{cache_root};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cache_options->{"cache_root"} 1 32 33
223  
224 # Set default value for max_size
225 $cache_options->{max_size} = $Cache::SizeAwareFileCache::NO_MAX_SIZE
226 33 ▶ unless defined $cache_options->{max_size};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cache_options->{"max_size"} 30 3 33
227  
228 33 return $cache_options;
229 }
230  
231 # --------------------------------------------------------------------------
232  
233 sub _compute_default_cache_root
234 {
235 1 ▶ my $tmpdir = tmpdir() or
Subroutine _compute_default_cache_root: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
my $tmpdir = tmpdir() or CGI::Cache::die("No tmpdir() on this system. Send a bug report to the authors of File::Spec") 0 1 1
236 die( "No tmpdir() on this system. " .
237 "Send a bug report to the authors of File::Spec" );
238  
239 1 $CACHE_PATH = File::Spec->catfile( $tmpdir, 'CGI_Cache' );
240  
241 1 return $CACHE_PATH;
242 }
243  
244 # --------------------------------------------------------------------------
245  
246 sub set_key
247 {
248 33 ▶ my $key = \@_;
Subroutine set_key: called CC=1 SCAR=0.0
Pod documented
249  
250 33 $Storable::canonical = 'true';
251  
252 33 $THE_CACHE_KEY = freeze $key;
253  
254 33 return 1;
255 }
256  
257 # --------------------------------------------------------------------------
258  
259 sub start
260 {
261 16 ▶ die "Cache key must be defined before calling CGI::Cache::start()"
Subroutine start: called CC=3 SCAR=12.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless defined $CGI::Cache::THE_CACHE_KEY 0 16 16
262 unless defined $THE_CACHE_KEY;
263  
264 # First see if a cached file already exists
265 16 my $cached_output = $THE_CACHE->get( $THE_CACHE_KEY );
266  
267 16 ▶ if ( defined $cached_output )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cached_output) { } 0 16 16
268 {
269 0 print $OUTPUT_HANDLE $cached_output;
270 0 return 0;
271 }
272 else
273 {
274 16 _bind();
275  
276 16 $CAPTURE_STARTED = 1;
277  
278 16 return 1;
279 }
280 }
281  
282 # --------------------------------------------------------------------------
283  
284 sub stop
285 {
286 16 ▶ return 0 unless $CAPTURE_STARTED;
Subroutine stop: called CC=4 SCAR=13.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless $CAPTURE_STARTED 0 16 16
287  
288 16 my $cache_output = shift;
289 16 ▶ $cache_output = 1 unless defined $cache_output;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cache_output 6 10 16
290  
291 16 _unbind();
292  
293 # Cache the saved output if necessary
294 16 ▶ $THE_CACHE->set( $THE_CACHE_KEY, $THE_CAPTURED_OUTPUT ) if $cache_output;
Branch: 1 branch
BranchTrueFalseTotal
if $cache_output 12 4 16
295  
296 # May be important for mod_perl situations
297 16 $CAPTURE_STARTED = 0;
298 16 $THE_CAPTURED_OUTPUT = '';
299 16 $WROTE_TO_STDERR = 0;
300 16 $CALLED_WARN_OR_DIE = 0;
301 16 $THE_CACHE_KEY = undef;
302  
303 16 return 1;
304 }
305  
306 # --------------------------------------------------------------------------
307  
308 sub pause
309 {
310 # Nothing happens if capturing was not started, or you are not currently
311 # capturing
312 2 ▶ return 0 unless $CAPTURE_STARTED && $CAPTURING;
Subroutine pause: called CC=3 SCAR=12.5
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless $CAPTURE_STARTED and $CAPTURING 0 2 2
Condition33%1/3
$CAPTURE_STARTED and $CAPTURING
!ll&&!rl&&r
002
MC/DC0%0/2
$CAPTURE_STARTED and $CAPTURING
$CAPTURE_STARTED $CAPTURING
Truth table33%1/3
A and B
A= $CAPTURE_STARTEDB= $CAPTURING
ABresult
0X0
100
111
313  
314 2 _unbind( 'output' );
315  
316 2 return 1;
317 }
318  
319 # --------------------------------------------------------------------------
320  
321 sub continue
322 {
323 # Nothing happens unless capturing was started and you are currently
324 # not capturing
325 2 ▶ return 0 unless $CAPTURE_STARTED && !$CAPTURING;
Subroutine continue: called CC=3 SCAR=12.5
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless $CAPTURE_STARTED and not $CAPTURING 0 2 2
Condition33%1/3
$CAPTURE_STARTED and not $CAPTURING
!ll&&!rl&&r
002
MC/DC0%0/2
$CAPTURE_STARTED and not $CAPTURING
$CAPTURE_STARTED not $CAPTURING
Truth table33%1/3
A and not(B)
A= $CAPTURE_STARTEDB= not $CAPTURING
ABresult
0X0
100
111
326  
327 2 _bind( 'output' );
328  
329 2 return 1;
330 }
331  
332 # --------------------------------------------------------------------------
333  
334 sub _bind
335 {
336 40 ▶ my @handles = @_;
Subroutine _bind: called CC=12 SCAR=26.9
337  
338 40 ▶ @handles = ( 'output', 'error' ) unless @handles;
Branch: 1 branch
BranchTrueFalseTotal
unless @handles 16 24 40
339  
340 40 ▶ if (grep /output/, @handles)
Branch: 1 branch
BranchTrueFalseTotal
if (grep /output/, @handles) 37 3 40
341 {
342 37 $OLD_STDOUT_TIE = tied *$WATCHED_OUTPUT_HANDLE;
343  
344 # Tie the output handle to monitor output
345 37 tie ( *$WATCHED_OUTPUT_HANDLE, 'CGI::Cache::CatchSTDOUT' );
346  
347 37 $CAPTURING = 1;
348 }
349  
350 40 ▶ if (grep /error/, @handles)
Branch: 1 branch
BranchTrueFalseTotal
if (grep /error/, @handles) 19 21 40
351 {
352 19 $OLD_STDERR_TIE = tied *$WATCHED_ERROR_HANDLE;
353  
354 # Monitor STDERR to see if the script has any problems
355 19 tie ( *$WATCHED_ERROR_HANDLE, 'CGI::Cache::MonitorSTDERR' );
356  
357 # Store the previous warn() and die() handlers, unless they are ours. (We
358 # don't want to call ourselves if the user calls setup twice!)
359 19 ▶ if ( exists $main::SIG{__WARN__} && defined $main::SIG{__WARN__} && $main::SIG{__WARN__} ne \&warn )
Branch: 1 branch
BranchTrueFalseTotal
if (exists $SIG{"__WARN__"} and defined $SIG{"__WARN__"} and $SIG{"__WARN__"} ne \&CGI::Cache::warn) 0 19 19
Condition50%3/6
exists $SIG{"__WARN__"} and defined $SIG{"__WARN__"} and $SIG{"__WARN__"} ne \&CGI::Cache::warn
!ll&&!rl&&r
1900
exists $SIG{"__WARN__"} and defined $SIG{"__WARN__"}
!ll&&!rl&&r
1810
MC/DC0%0/3
exists $SIG{"__WARN__"} and defined $SIG{"__WARN__"} and $SIG{"__WARN__"} ne \&CGI::Cache::warn
exists $SIG{"__WARN__"} defined $SIG{"__WARN__"} $SIG{"__WARN__"} ne \&CGI::Cache::warn
Truth table50%2/4
A and B and C
A= exists $SIG{"__WARN__"}B= defined $SIG{"__WARN__"}C= $SIG{"__WARN__"} ne \&CGI::Cache::warn
ABCresult
0XX0
10X0
1100
1111
360 {
361 0 ▶ $OLD_WARN_SIG = $main::SIG{__WARN__} if $main::SIG{__WARN__} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $SIG{"__WARN__"} ne "" 0 0 0
362 0 $main::SIG{__WARN__} = \&warn;
363 }
364  
365 19 ▶ if ( exists $main::SIG{__DIE__} && defined $main::SIG{__DIE__} && $main::SIG{__DIE__} ne \&die )
Branch: 1 branch
BranchTrueFalseTotal
if (exists $SIG{"__DIE__"} and defined $SIG{"__DIE__"} and $SIG{"__DIE__"} ne \&CGI::Cache::die) 1 18 19
Condition66%4/6
exists $SIG{"__DIE__"} and defined $SIG{"__DIE__"} and $SIG{"__DIE__"} ne \&CGI::Cache::die
!ll&&!rl&&r
1801
exists $SIG{"__DIE__"} and defined $SIG{"__DIE__"}
!ll&&!rl&&r
1801
MC/DC33%1/3
exists $SIG{"__DIE__"} and defined $SIG{"__DIE__"} and $SIG{"__DIE__"} ne \&CGI::Cache::die
exists $SIG{"__DIE__"} defined $SIG{"__DIE__"} $SIG{"__DIE__"} ne \&CGI::Cache::die
Truth table50%2/4
A and B and C
A= exists $SIG{"__DIE__"}B= defined $SIG{"__DIE__"}C= $SIG{"__DIE__"} ne \&CGI::Cache::die
ABCresult
0XX0
10X0
1100
1111
366 {
367 1 ▶ $OLD_DIE_SIG = $main::SIG{__DIE__} if $main::SIG{__DIE__} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $SIG{"__DIE__"} ne "" 1 0 1
368 1 $main::SIG{__DIE__} = \¨
369 }
370 }
371 }
372  
373 # --------------------------------------------------------------------------
374  
375 sub _unbind
376 {
377 40 ▶ my @handles = @_;
Subroutine _unbind: called CC=6 SCAR=17.9
378  
379 40 ▶ @handles = ( 'output', 'error' ) unless @handles;
Branch: 1 branch
BranchTrueFalseTotal
unless @handles 16 24 40
380  
381 40 ▶ if (grep /output/, @handles)
Branch: 1 branch
BranchTrueFalseTotal
if (grep /output/, @handles) 37 3 40
382 {
383 37 untie *$WATCHED_OUTPUT_HANDLE;
384  
385 37 tie *$WATCHED_OUTPUT_HANDLE, 'Tie::Restore', $OLD_STDOUT_TIE;
386  
387 37 $CAPTURING = 0;
388 }
389  
390 40 ▶ if (grep /error/, @handles)
Branch: 1 branch
BranchTrueFalseTotal
if (grep /error/, @handles) 19 21 40
391 {
392 19 untie *$WATCHED_ERROR_HANDLE;
393  
394 19 tie *$WATCHED_ERROR_HANDLE, 'Tie::Restore', $OLD_STDERR_TIE;
395  
396 19 ▶ $main::SIG{__DIE__} = $OLD_DIE_SIG if defined $OLD_DIE_SIG;
Branch: 1 branch
BranchTrueFalseTotal
if defined $OLD_DIE_SIG 1 18 19
397 19 undef $OLD_DIE_SIG;
398 19 ▶ $main::SIG{__WARN__} = $OLD_WARN_SIG if defined $OLD_WARN_SIG;
Branch: 1 branch
BranchTrueFalseTotal
if defined $OLD_WARN_SIG 0 19 19
399 19 undef $OLD_WARN_SIG;
400 }
401 }
402  
403 # --------------------------------------------------------------------------
404  
405 sub invalidate_cache_entry
406 {
407 1 ▶ $THE_CACHE->remove( $THE_CACHE_KEY );
Subroutine invalidate_cache_entry: called CC=1 SCAR=0.0
Pod documented
408  
409 1 return 1;
410 }
411  
412 # --------------------------------------------------------------------------
413  
414 sub clear_cache
415 {
416 0 ▶ $CGI::Cache::THE_CACHE->clear();
Subroutine clear_cache: not called CC=1 SCAR=6.9
Pod documented
417  
418 0 return 1;
419 }
420  
421 # --------------------------------------------------------------------------
422  
423 sub buffer
424 {
425 2 ▶ $THE_CAPTURED_OUTPUT = join( '', @_ ) if @_;
Subroutine buffer: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 1 2
426  
427 2 return $THE_CAPTURED_OUTPUT;
428 }
429  
430 25 1;
431  
432 # ##########################################################################
433  
434 package CGI::Cache::CatchSTDOUT;
435  
436 # These functions are for tie'ing the output filehandle
437  
438 sub TIEHANDLE
439 {
440 37 ▶ my $package = shift;
Subroutine TIEHANDLE: called CC=1 SCAR=0.0
441  
442 37 return bless {}, $package;
443 }
444  
445 sub WRITE
446 {
447 0 ▶ my( $r, $buff, $length, $offset ) = @_;
Subroutine WRITE: not called CC=1 SCAR=6.9
448  
449 0 my $send = substr( $buff, $offset, $length );
450 0 print $send;
451 }
452  
453 sub PRINT
454 {
455 20 ▶ my $r = shift;
Subroutine PRINT: called CC=2 SCAR=6.9
456  
457 # Temporarily disable warnings so that we don't get "untie attempted
458 # while 1 inner references still exist". Not sure what's the "right
459 # thing" to do here.
460 20 local $^W = 0;
461  
462 20 $CGI::Cache::THE_CAPTURED_OUTPUT .= join '', @_;
463  
464 # Temporarily untie the filehandle so that we won't recursively call
465 # ourselves
466 20 ▶ if ($CGI::Cache::ENABLE_OUTPUT)
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Cache::ENABLE_OUTPUT) 19 1 20
467 {
468 19 CGI::Cache::_unbind( 'output' );
469  
470 19 print $CGI::Cache::OUTPUT_HANDLE @_;
471  
472 19 CGI::Cache::_bind( 'output' );
473 }
474 }
475  
476 sub PRINTF
477 {
478 0 ▶ my $r = shift;
Subroutine PRINTF: not called CC=1 SCAR=6.9
479 0 my $fmt = shift;
480  
481 0 print sprintf( $fmt, @_ );
482 }
483  
484 25 1;
485  
486 ############################################################################
487  
488 package CGI::Cache::MonitorSTDERR;
489  
490 # These functions are for tie'ing the STDERR filehandle
491  
492 sub TIEHANDLE
493 {
494 19 ▶ my $package = shift;
Subroutine TIEHANDLE: called CC=1 SCAR=0.0
495  
496 19 return bless {}, $package;
497 }
498  
499 sub WRITE
500 {
501 0 ▶ my( $r, $buff, $length, $offset ) = @_;
Subroutine WRITE: not called CC=1 SCAR=6.9
502  
503 0 my $send = substr( $buff, $offset, $length );
504 0 print $send;
505 }
506  
507 sub PRINT
508 {
509 3 ▶ my $r = shift;
Subroutine PRINT: called CC=1 SCAR=0.0
510  
511 # Temporarily untie the filehandle so that we won't recursively call
512 # ourselves
513 3 CGI::Cache::_unbind( 'error' );
514  
515 3 print $CGI::Cache::ERROR_HANDLE @_;
516  
517 3 $CGI::Cache::WROTE_TO_STDERR = 1;
518  
519 3 CGI::Cache::_bind( 'error' );
520 }
521  
522 sub PRINTF
523 {
524 0 ▶ my $r = shift;
Subroutine PRINTF: not called CC=1 SCAR=6.9
525 0 my $fmt = shift;
526  
527 0 print sprintf( $fmt, @_ );
528 }
529  
530 25 1;
531  
532 # ---------------------------------------------------------------------------
533  
534 =head1 NAME
535  
536 CGI::Cache - Perl extension to help cache output of time-intensive CGI scripts
537  
538 =head1 WARNING
539  
540 The interface as of version 1.01 has changed considerably and is NOT
541 compatible with earlier versions. A smaller interface change also occurred in
542 version 1.20.
543  
544 =head1 SYNOPSIS
545  
546 Here's a simple example:
547  
548 #!/usr/bin/perl
549  
550 use CGI;
551 use CGI::Cache;
552  
553 # Set up cache
554 CGI::Cache::setup();
555  
556 my $cgi = new CGI;
557  
558 # CGI::Vars requires CGI version 2.50 or better
559 CGI::Cache::set_key($cgi->Vars);
560  
561 # This should short-circuit the rest of the loop if a cache value is
562 # already there
563 CGI::Cache::start() or exit;
564  
565 print $cgi->header, "\n";
566  
567 print <<EOF;
568 <html><body>
569 <p>
570 This prints to STDOUT, which will be cached.
571 If the next visit is within 24 hours, the cached STDOUT
572 will be served instead of executing this 'print'.
573 </body></html>
574 EOF
575  
576 Here's a more complex example:
577  
578 use CGI;
579 use CGI::Cache;
580  
581 my $query = new CGI;
582  
583 # Set up a cache in /tmp/CGI_Cache/demo_cgi, with publicly
584 # unreadable cache entries, a maximum size of 20 megabytes,
585 # and a time-to-live of 6 hours.
586 CGI::Cache::setup( { cache_options =>
587 { cache_root => '/tmp/CGI_Cache',
588 namespace => 'demo_cgi',
589 directory_umask => 077,
590 max_size => 20 * 1024 * 1024,
591 default_expires_in => '6 hours',
592 }
593 } );
594  
595 # CGI::Vars requires CGI version 2.50 or better
596 CGI::Cache::set_key( $query->Vars );
597 CGI::Cache::invalidate_cache_entry()
598 if $query->param( 'force_regenerate' ) eq 'true';
599 CGI::Cache::start() or exit;
600  
601 print "Content-type: text/html\n\n";
602  
603 print <<EOF;
604 <html><body>
605 <p>
606 This prints to STDOUT, which will be cached.
607 If the next visit is within 6 hours, the cached STDOUT
608 will be served instead of executing these 'prints'.
609 </p>
610 EOF
611  
612 CGI::Cache::pause();
613  
614 print <<EOF;
615 <p>This is not cached.</p>
616 EOF
617  
618 CGI::Cache::continue();
619  
620 print <<EOF;
621 </body></html>
622 EOF
623  
624 # Optional unless you're using mod_perl for FastCGI
625 CGI::Cache::stop();
626  
627 =head1 DESCRIPTION
628  
629 This module is intended to be used in a CGI script that may
630 benefit from caching its output. Some CGI scripts may take
631 longer to execute because the data needed in order to construct
632 the page may not be quickly computed. Such a script may need to
633 query a remote database, or may rely on data that doesn't arrive
634 in a timely fashion, or it may just be computationally intensive.
635 Nonetheless, if you can afford the tradeoff of showing older,
636 cached data vs. CGI execution time, then this module will perform
637 that function.
638  
639 This module was written such that any existing CGI code could benefit
640 from caching without really changing any of existing CGI code guts.
641 The CGI script can do just what it has always done, that is, construct
642 an html page and print it to the output file descriptor, then exit.
643 What you'll do in order to cache pages is include the module, specify
644 some cache options and the cache key, and then call start() to begin
645 caching output.
646  
647 Internally, the CGI::Cache module ties the output file descriptor (usually
648 STDOUT) to an internal variable to which all output is saved. When the user
649 calls stop() (or the END{} block of CGI::Cache is executed during script
650 shutdown) the contents of the variable are inserted into the cache using the
651 cache key the user specified earlier with set_key().
652  
653 Once a page has been cached in this fashion, a subsequent visit to that page
654 will invoke the start() function again, which will then check for an existing
655 cache entry for the given key before continuing through the code. If the cache
656 entry exists, then the cache entry's content is printed to the output
657 filehandle (usually STDOUT) and a 0 is returned to indicate that cached output
658 was used.
659  
660 =head2 CHOOSING A CACHE KEY
661  
662 The cache key is used by CGI::Cache to determine when cached
663 output can be used. The key should be a unique data structure
664 that fully describes the execution of the script. Conveniently,
665 CGI::Cache can take the CGI module's parameters (using
666 CGI::Vars) as the key. However, in some cases you may want to
667 specially construct the key.
668  
669 For example, say we have a CGI script "airport" that computes the
670 number of miles between major airports. You supply two airport codes
671 to the script and it builds a web page that reports the number of
672 miles by air between those two locations. In addition, there is a
673 third parameter which tells the script whether to write debugging
674 information to a log file. Suppose the URL for Indianapolis Int'l to
675 Chicago O'Hare looked like:
676  
677 http://www.some.machine/cgi/airport?from=IND&to=ORD&debug=1
678  
679 We might want to remove the debug parameter because the output from
680 the user's perspective is the same regardless of whether a log file is
681 written:
682  
683 my $params = $query->Vars;
684 delete $params->{'debug'};
685 CGI::Cache::set_key( $params );
686 CGI::Cache::start() or exit;
687  
688 =head2 THE CGI::CACHE ROUTINES
689  
690 =over 4
691  
692 =item setup(...)
693  
694 setup( { cache_options => \%cache_options,
695 [enable_output => 1],
696 [watched_output_handle => \*STDOUT],
697 [watched_error_handle => \*STDERR] );
698 [output_handle => <watched_output_handle>],
699 [error_handle => <watched_error_handle>] } );
700  
701 <enable_output> - used to disable output while caching
702 <cache_options> - options for configuration of the cache
703 <watched_output_handle> - the file handle to monitor for normal output
704 <watched_error_handle> - the file handle to monitor for error output
705 <output_handle> - the file handle to which to send normal output
706 <error_handle> - the file handle to which to send error output
707  
708 Sets up the module. The I<cache_options> parameter contains the same values as
709 the parameters for the Cache::SizeAwareFileCache module's new() method, with
710 the same defaults. Below is a brief overview of the options and their
711 defaults. This overview may be out of date with your version of
712 Cache::SizeAwareFileCache. Consult I<perldoc Cache::SizeAwareFileCache> for
713 more accurate information.
714  
715 =over 4
716  
717 =item $cache_options{cache_root}
718  
719 The cache_root is the file system location of the cache. Leaving this unset
720 will cause the cache to be created in a subdirectory of your temporary
721 directory called CGI_Cache.
722  
723 =item $cache_options{namespace}
724  
725 Namespaces provide isolation between cache objects. It is recommended
726 that you use a namespace that is unique to your script. That way you
727 can have multiple scripts whose output is cached by CGI::Cache, and
728 they will not collide. This value defaults to a subdirectory of your
729 temp directory whose name matches the name of your script (as reported
730 by $ENV{SCRIPT_NAME}, or $0 if $ENV{SCRIPT_NAME} is not defined).
731  
732 =item $cache_options{default_expires_in}
733  
734 If the "default_expires_in" option is set, all objects in this cache will be
735 cleared after that number of seconds. If this option is not provided, the
736 cache entry will never expire by default.
737  
738 =item $cache_options{max_size}
739  
740 "max_size" specifies the maximum size of the cache, in bytes. Cache objects
741 are removed during the set() operation in order to reduce the cache size
742 before the new cache value is added. The default size is unlimited.
743  
744 =back
745  
746 Normally CGI::Cache monitors STDOUT, storing output in a temporary buffer,
747 before printing it to the output filehandle. It also monitors STDERR in order
748 to determine if your CGI script has failed: if it has failed, then the buffer
749 is discarded. Otherwise, the buffered output is cached for a later execution
750 of your program.
751  
752 The enable_output option allows you to cache the output but not
753 send it to the output filehandle. This is useful, for example, if you want to
754 store the output, then use buffer() to access it for processing before calling
755 stop(), which stores the buffer in the cache.
756  
757 The remaining four optional parameters allow you to modify the filehandles
758 that CGI::Cache listens on and outputs to. The watched handles are the handles
759 which CGI::Cache will monitor for output. The output and error handles are the
760 handles to which CGI::Cache will send the output after it is cached. These
761 default to whatever the watched handles are. This feature is useful when
762 CGI::Cache is used to cache output to files:
763  
764 use CGI::Cache;
765  
766 open FH, ">TEST.OUT";
767  
768 CGI::Cache::setup( { watched_output_handle => \*FH } );
769 CGI::Cache::set_key( 'test key' );
770 CGI::Cache::start() or exit;
771  
772 # This is cached, and then sent to FH
773 print FH "Test output 1\n";
774  
775 CGI::Cache::stop();
776  
777 close FH;
778  
779 NOTE: If you plan to modify warn() or die() (i.e. redefine $SIG{__WARN__} or
780 $SIG{__DIE__}) so that they no longer print to STDERR, you must do so before
781 calling setup(). For example, if you do a "require CGI::Carp
782 qw(fatalsToBrowser)", make sure you do it before calling CGI::Cache::setup().
783  
784  
785 =item set_key ( <data> );
786  
787 set_key takes any type of data (e.g. a list, a string, a reference to
788 a complex data structure, etc.) and uses it to create a unique key to
789 use when caching the script's output.
790  
791  
792 =item start();
793  
794 Could you guess that the start() routine is what does all the work? It is this
795 call that actually looks for an existing cache file and prints the output if
796 it exists. If the cache file does not exist, then CGI::Cache captures the
797 output filehandle and redirects the CGI script's output to the cache file.
798  
799 This function returns 1 if caching has started, and 0 if the cached output was
800 printed. A common metaphor for using this function is:
801  
802 CGI::Cache::start() or exit;
803  
804 This function dies if you haven't yet defined your cache key.
805  
806  
807 =item $status = stop( [<cache_output>] );
808  
809 <cache_output> - do we write the captured output to a cache file?
810  
811 The stop() routine tells us to stop capturing output. The argument
812 "cache_output" tells us whether or not to store the captured output in
813 the cache. By default this argument is 1, since this is usually what
814 we want to do. In an error condition, however, we may not want to
815 cache the output. A cache_output argument of 0 is used in this case.
816  
817 You don't have to call the stop() routine if you simply want to catch
818 all output that the script generates for the duration of its
819 execution. If the script exits without calling stop(), CGI::Cache
820 will call it for you upon program exit. Note that CGI::Cache will
821 detect whether your script is exiting as the result of an error, and
822 will B<not> cache the output in this case.
823  
824 This function returns 0 if capturing has not been started (by a call
825 to start()), and 1 otherwise.
826  
827 =item $status = pause();
828  
829 Temporarily disable caching of output. Returns 0 if CGI::Cache
830 is not currently caching output, and 1 otherwise.
831  
832  
833 =item $status = continue();
834  
835 Re-enable caching of output. This function returns 0 if capturing has
836 not been started (by a call to start()) or if pause() was not
837 previously called, and 1 otherwise.
838  
839  
840 =item $scalar = buffer( [<content>] );
841  
842 The buffer method gives direct access to the buffer of cached output. The
843 optional <content> parameter allows you to set the contents using a list or
844 scalar. (The list will be joined into a scalar and stored in the buffer.) The
845 return value is the contents of the buffer after any changes.
846  
847  
848 =item $status = invalidate_cache_entry();
849  
850 Forces the cache entry to be invalidated. It is always successful, and always
851 returns 1. It doesn't make much sense to call this after calling start(), as
852 CGI::Cache will have already determined that the cache entry is invalid.
853  
854  
855 =item $status = clear_cache();
856  
857 Deletes the cache. It is always successful, and always returns 1.
858  
859 =back
860  
861  
862 =head1 CGI::Cache and Persistent Environments
863  
864 CGI::Cache supports persistent environments. The key is the return value from
865 start()---if the return value is 0, then cached output has been printed, and
866 your persistent script should not regenerate its output. Typically you would
867 do something like:
868  
869 use vars qw($COUNTER);
870  
871 while(NEW CONNECTION)
872 {
873 CGI::Cache::set_key(...);
874
875 $COUNTER++;
876  
877 CGI::Cache::start() or next;
878  
879 ... NORMAL OUTPUT ...
880 print $COUNTER;
881  
882 CGI::Cache::stop();
883 }
884  
885 When you invoke a CGI script like this using a URL like
886 http://www.some.machine/cgi-bin/scriptname.fcgi the output will report that
887 the counter is 1. If you reload this web page, you will get cached
888 information--even though the counter was incremented, the reloaded web page
889 will say that the counter is 1.
890  
891 However, if you change the parameters to the request by visiting
892 http://www.some.machine/cgi-bin/scriptname.fcgi?var=1 (assuming your cache key
893 is based on the parameters) you will get an updated web page. The counter
894 will show the correct value based on the number of times you reloaded the web
895 page. For example, if you did 2 reloads, the counter should be reported as
896 4---the first load, plus two reloads, plus the final load with changed
897 parameters.
898  
899 Finally, if you revisit http://www.some.machine/cgi-bin/scriptname.fcgi, you
900 will see the cached web page with the counter equal to 1.
901  
902 The next few subsections provide examples of how to use CGI::Cache with
903 different persistent CGI environments.
904  
905 =head2 CGI::Fast
906  
907 Here's an example with CGI::Fast:
908  
909 #!/usr/bin/perl
910  
911 use strict;
912  
913 use CGI::Fast;
914 use CGI::Cache;
915  
916 my $COUNTER = 0;
917  
918 # Set up cache
919 CGI::Cache::setup();
920  
921 while (my $cgi = new CGI::Fast)
922 {
923 CGI::Cache::set_key($cgi->Vars);
924  
925 $COUNTER++;
926  
927 # This should short-circuit the rest of the loop if a cache value is
928 # already there
929 CGI::Cache::start() or next;
930  
931 print $cgi->header, "\n";
932  
933 print<<EOF;
934 <html>
935 <head><title>FastCGI</title></head>
936 <body>Counter: $COUNTER PID: $$</body>
937 </html>
938 EOF
939  
940 CGI::Cache::stop();
941 }
942  
943 =head2 FCGI
944  
945 Here's an example with FCGI:
946  
947 #!/usr/bin/perl
948  
949 use strict;
950  
951 use FCGI;
952 use CGI::Cache;
953 use CGI;
954 use IO::Handle;
955  
956 my $COUNTER = 0;
957  
958 my $stdout = new IO::Handle;
959 my $stderr = new IO::Handle;
960  
961 my %env;
962  
963 my $request = FCGI::Request(\*STDIN, $stdout, $stderr, \%env);
964  
965 # Set up cache
966 if ($request->IsFastCGI())
967 {
968 CGI::Cache::setup( { output_handle => $stdout,
969 error_handle => $stderr } );
970 }
971 else
972 {
973 CGI::Cache::setup();
974 }
975  
976 while ($request->Accept() >= 0)
977 {
978 my $cgi = new CGI($env{QUERY_STRING});
979 CGI::Cache::set_key($cgi->Vars);
980  
981 $COUNTER++;
982  
983 # This should short-circuit the rest of the loop if a cache value is
984 # already there
985 CGI::Cache::start() or next;
986  
987 print $cgi->header, "\n";
988  
989 print<<EOF;
990 <html>
991 <head><title>FastCGI</title></head>
992 <body>Counter: $COUNTER PID: $$</body>
993 </html>
994 EOF
995  
996 CGI::Cache::stop();
997 }
998  
999  
1000 =head2 SpeedyCGI
1001  
1002 Here's an example with SpeedyCGI:
1003  
1004 #!/usr/bin/speedy
1005  
1006 use strict;
1007  
1008 use CGI;
1009 use CGI::Cache;
1010  
1011 use vars qw($COUNTER);
1012  
1013 # Set up cache
1014 CGI::Cache::setup();
1015  
1016 $COUNTER++;
1017  
1018 my $cgi = new CGI;
1019  
1020 CGI::Cache::set_key($cgi->Vars);
1021  
1022 # This should short-circuit the rest of the program if a cache value is
1023 # already there
1024 CGI::Cache::start() or exit;
1025  
1026 print $cgi->header, "\n";
1027  
1028 print<<EOF;
1029 <html>
1030 <head><title>SpeedyCGI</title></head>
1031 <body>Counter: $COUNTER PID: $$</body>
1032 </html>
1033 EOF
1034  
1035 CGI::Cache::stop();
1036  
1037 =head1 BUGS
1038  
1039 No known bugs.
1040  
1041 Contact the author for bug reports and suggestions.
1042  
1043 =head1 LICENSE
1044  
1045 This code is distributed under the GNU General Public License (GPL) Version 2.
1046 See the file LICENSE in the distribution for details.
1047  
1048 =head1 AUTHOR
1049  
1050 The original code (written before October 1, 2000) was written by Broc
1051 Seib, and is copyright (c) 1998 Broc Seib.
1052  
1053 The CGI::Cache namespace was donated by Terrance Brannon, who kindly allowed
1054 the current codebase to replace his.
1055  
1056 Maintenance of CGI::Cache is now being done by David Coppit
1057 E<lt>david@coppit.orgE<gt>.
1058  
1059 =head1 SEE ALSO
1060  
1061 L<Cache::SizeAwareFileCache>
1062  
1063 =cut
↑ Summary