[RFC PATCHv2 04/10] gitweb: Use Cache::Cache compatibile (get, set) output caching
This commit actually adds output caching to gitweb, as we have now minimal features required for it in GitwebCache::SimpleFileCache (a 'dumb' but fast file-based cache engine). To enable cache you need at least set $caching_enabled to true in gitweb config, and copy cache.pm from gitweb/ alongside gitweb.cgi - this is described in more detail in the new "Gitweb caching" section in gitweb/README
Currently cache support related subroutines in cache.pm (which are outside GitwebCache::SimpleFileCache package) are not well separated from gitweb script itself; cache.pm lacks encapsulation. cache.pm assumes that there are href() subroutine and %actions variable, and that there exist $actions{$action} (where $action is parameter passed to cache_fetch), and it is a code reference (see also comments in t/t9503/test_cache_interface.pl). This is remaining artifact from the original patch by J.H. (which also had cache_fetch() subroutine).
Gitweb itself uses directly only cache_fetch, to get page from cache or to generate page and save it to cache, and cache_stop, to be used in die_error subroutine, as currently error pages are not cached.
The cache_fetch subroutine captures output (from STDOUT only, as STDERR is usually logged) using either ->push_layer()/->pop_layer() from PerlIO::Util submodule (if it is available), or by setting and restoring *STDOUT. Note that only the former could be tested reliably to be reliable in t9503 test!
Enabling caching causes the following additional changes to gitweb
output:
* Disables content-type negotiation (choosing between 'text/html'
mimetype and 'application/xhtml+xml') when caching, as there is no
content-type negotiation done when retrieving page from cache.
Use 'text/html' mimetype that can be used by all browsers.
* Disable timing info (how much time it took to generate original
page, and how many git commands it took), and in its place show when
page was originally generated (in GMT / UTC timezone).
Add basic tests of caching support to t9500-gitweb-standalone-no-errors test: set $caching_enabled to true and check for errors for first time run (generating cache) and second time run (retrieving from cache) for a single view - summary view for a project.
If PerlIO::Util is available (see comments), test that cache_fetch behaves correctly, namely that it saves and restores action output in cache, and that it prints generated output or cached output.
To be implemented (from original patch by J.H.):
* adaptive cache expiration, based on average system load
* optional locking interface, where only one process can update cache
(using flock)
* server-side progress indicator when waiting for filling cache,
which in turn requires separating situations (like snapshots and
other non-HTML responses) where we should not show 'please wait'
message
Inspired-by-code-by: John 'Warthog9' Hawley <warthog9@kernel.org>
Signed-off-by: Jakub Narebski <jnareb@gmail.com>
---
Differences from v1:
* Commit message is present
* When caching is enabled gitweb outputs the time when page was generated in
place of timing info (time it took to generate page). In previous version
'timed' feature wasn't supported (it was disabled) when caching was turned
on.
The 'timed' feature is turned off when caching is enabled for 'blame_data'
(used by 'blame_incremental' view).
* Capturing gitweb output is done without need to modify gitweb to always
print explicitly to $out filehandle. Turning caching off in die_error()
is now done using cache_stop() subroutine from cache.pm. See also
description of capturing output below.
* Description of $caching_enabled variable in "Gitweb config file variables"
section in gitweb/README and adding "Gitweb caching" section.
* No need for changing $/, _input_ record separator, when printing (output).
* $cache can be now set not only to caching engine object (initialized
instance), but also to class name.
Pass Cache::Cache ('default_expires_in') and CHI ('root_dir', 'depth')
compatible aliases for cache options to the $cache->new(), which is
invoked when $cache is undefined (GitwebCache::SimpleFileCache is used)
or when it is class name.* You can override cache options in $GITWEB_CONFIG by modifying
%cache_options hash. All cache options are described in detail in
comments.
* Gitweb dies with appropriate error message when caching is enabled, but
$cache_pm cannot be found. (Note that if the change that automatically
escapes error message in die_error goes in, this would have to be changed
to not escape $cache_pm in error message in caller.)
* t/t9500-gitweb-standalone-no-errors.sh tests also the case when data
is retrieved from cache, not only when it is saved to cache (for
that expire time is set to never expire).
* t9503 tests also cache_fetch() subroutine, using the same capturing
mechanism as cache.pm / cache_fetch() itself to check if it produces
correct output. As noted in comments, I could make tests only for the
situation where both tests and cache.pm used PerlIO::Util module (not
among Perl core modules).
The need for mockup of gitweb's href() and %actions shows that
cache_fetch() is not properly encapsulated / separated from inner workings
of gitweb code.
Differences from relevant parts of J.H. patch:
* cache_fetch() subroutine is much, much simpler. Well, it lacks most of
the features of original cache_fetch() by J.H.: it doesn't have adaptive
cache lifetime, nor locking to prevent 'stampeding herd' problem, nor
serving stale data when waiting for cache regeneration, nor background
data generation, nor activity indicator... but the cache_fetch() itself
doesn't change much, as those features are added mainly via methods
and subroutines cache_fetch() calls.
* Capturing gitweb output is done without need to modify gitweb to either
save generated output into $output variable and print it or save in cache
after it is generated in full (original J.H. patch in "Gitweb caching v2"),
or changing all print statements to print to explicit filehandle which
points to STDOUT if caching is disabled and to in-memory file if caching
is enabled (modified J.H. patch in "Gitweb caching v5"). See also below.
* It introduces $cache_pm variable, to be able to test caching in
t/t9500-gitweb-standalone-no-errors.sh, but also to be able to install
cache.pm in some other place than along gitweb.cgi. There would be no
such problems if we used 'require GitwebCache' or somesuch, in place of
'do "cache.pm"' like in original patch by J.H.
Currently however cache.pm is not independent of gitweb.perl; it requires
href() subroutine and appropriate %actions hash for dispatch. Therefore
we must use 'do $cache_pm;' instead of e.g. 'use cache;'.
* Instead of using "binary" (sic!) valued $cache_enable (which means 0 or 1
valued $cache_enable), a set of two variables is used. The $cache
variable can be used to select alternate caching engine / caching class.
The $caching_enabled variable is used to actually enable/disable cache.
* The information about the time when page was generated is shown only if
'timed' feature is enabled in gitweb config, and it is shown in place of
usual time it took to generate page (shown when caching is not enabled).
This means tha change to gitweb/gitweb.css was not needed.
* cache_fetch() is run only when $caching_enabled. Some of cache
initializations are in gitweb.perl, and not at beginning of cache_fetch()
* Cache options are contained in %cache_options hash, instead of individual
global variables (which were using non-Perlish camelCase notation).
* There is information about caching in gitweb in gitweb/README
* There are tests of gitweb caching in t9500, and caching API in t9503
Capturing gitweb output ======================= When output (response) caching is enabled, the caching mechanism has to capture gitweb output (perhaps while printing it to standard output) to save it to cache, unless the data is available in cache and not expired.
Because die_error uses 'exit', and because it uses git_header_html and other printing subroutines (which output has to be captured in other situations), it needs to disable caching, unless we are "tee"-ing. Otherwise we would get no output from die_error (because it is captured), but also we would not get data to be saved in cache and printed, because 'exit' in die_error would exit capture, too. This restricts methods and modules that can be used to capture output.
Below there are presented various considered and used ways of capturing the output, or "tee"-ing it (capturing while printing), with their advantages and disadvantages.
Capturing output (capture) ~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Modify gitweb to save its output to variable before printing it, which
means changing 'print <sth>' to '$output .= <sth>', and 'printf <sth>'
to '$output .= sprintf <sth>'.
This was the approach taken in last patch in "Gitweb caching v2" series
by J.H. It has the disadvantage of requiring large patch to gitweb;
it also makes gitweb output data only after it is generated in full,
even if caching is disabled (data is streamed now). It also requires
taking care of printing in die_error and after running action, and
using correct mode (':utf8' or ':raw' aka binary mode) both when printing
to cache file, and when printing to STDOUT in die_error. This approach got superceded by the next method.
2. Modify gitweb to print to explicit filehandle (instead of implicitly to
STDOUT), which means changing 'print <sth>' to 'print $out <sth>' (or to
'print {$out} <sth>', 'printf <sth>' to 'printf $out <sth>', and last
'binmode STDOUT <mode>' to 'binmode $out <mode>'. This was the approach taken in previous version of this series, and also
in last patch in "Gitewb caching v5" by J.H. It has the disadvantage of
requiring large patch to gitweb, but on the other hand the base change
itself is just simple mechanical change (plus optionally whitespace-only
reindent change, and optionally re-wrapping too long lines). It is very
easy to capture output: just set $out to in-memory file opened for
reading (or even point $out directly to cache file / temporary file). It
is also easy to stop capturing: just set $out to \*STDOUT (or *STDOUT).
Should we chose this method (now that it is shown that you can do without
changes to gitweb, and what needs then to be done to capture output)?
3. The recommended module for capturing output in Perl is Capture::Tiny. It
has nice and simple API: to capture output you use 'capture \&code',
which is prototyped to allow to be called in block form:
($stdout, $stderr) = capture {
# your code here ...
}; It is a minor annoyance that it captures all output also in scalar
context, i.e. when called as '$stdout = capture \&code;', so one would
need to 'print STDERR $stderr;' after capture. But what is more
important is the fact that it doesn't offer any mechanism to turn off
capturing inside called code... which is required for die_error, at least
the way it works now (see above).
Nevertheless the API is clean and I think worth emulating, which I did
with cache_capture(&) subroutine in cache.pm. Also the problems vanish
in "tee" mode, i.e. for '$stdout = tee \&code;', see the next subsection.
Capture::Tiny distribution is only 28K packed. There exist
perl-Capture-Tiny RPM for Fedora:
http://spreadsheets.google.com/pub?key=tVoSlaYU1SGovwwjV0fqt9Q&output=html4. I have found PerlIO::Util as a way of capturing output when searching the
way to tee output: PerlIO::Util distribution contains PerlIO::tee module.
Actually 'scalar' layer to write to in-memory file is implemented in
PerlIO, which is a core Perl module. Unfortunately PerlIO lacks API to
add layer which needs parameters. You can open in-memory file using
open my $data_fh, '>', \$data you can request using given output layer on output with e.g. '>:utf8'
as mode, you can add a layer with binmode, e.g. 'binmode $out, ":utf8";'
but you can't add layer which requires extra parameter which is not
a string (like in the case of ':encoding(<encoding>)' layer). So you
can't just add scalar layer to STDOUT to redirect it to in-memory file
(to a scalar variable). For that you need PerlIO::Util.
The PerlIO manpage talks about ':pop' pseudo layer, and how "a more
elegant (and safer) interface is needed." - PerlIO::Util is such
interface.
To start capturing output to a scalar variable (in-memory file) with
PerlIO::Util, you just need to
*STDOUT->push_layer(scalar => \$data);
To stop capturing you do
*STDOUT->pop_layer();
Pushing yet another layer works as it should, therefore my tests of
cache_fetch() subroutine in t9503 require PerlIO::Util (and do not run if
it is not present) - I couldn't get to do the test with capture within
capture using he method described below. (There is Test::Output module
that could have been used in tests, or I could have used Capture::Tiny.)
I haven't found RPM module for PerlIO::Util (but nowadays I install
modules from CPAN using local::lib and cpan client).
5. Without 'print <sth>' to 'print $out <sth>' change to gitweb, one can try
manipulating *STDOUT directly, first saving *STDOUT or \*STDOUT to some
variable, then setting *STDOUT = $data_fh, where $data_fh is filehandle
opened to in-memory file.
This seems to work, does not require large patch to gitweb, and does not
require extra (non-core) Perl module. Nevertheless it seems fragile with
respect to restoring STDOUT, and even though basic tests (not included)
of this mechanism producted expected result, I wasn't able to write
working tests when using this method.
We could probably examine how Capture::Tiny does it, and reuse (copy)
relevant parts of code, perhaps duplicating STDOUT, closing it and then
reopening as in-memory filehandle.
YMMV (Your Mileage May Vary).
Saving output while printing (tee) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Instead of capturing gitweb output (except die_error, which displays error and exists), and then saving it to cache and displaying it, we can capture (save) output while it is being displayed, somewhat similar to what tee(1) UNIX (coreutils) command does.
This has the advantage that for the client that generates data (see further commit in series about using locking to avoid cache miss stampede) that it serves as acrivity indicator by itself. On the other hand achieving this effect in other processes that wait for the data to be generated would be, I think, quite complicated (a `tail -f' like behavior).
Because the original patch by J.H. (both versions) did capturing then displaying, "tee"-ing data was not added to this series. Nevetheless this is something to consider for the future.
1. While using 'capture' from Capture::Tiny would have difficulties (if it
was at all possible) for gitweb as it is now, using 'tee' from the same
module would be quite simple:
$data = tee {
# generate gitweb output
};
# save $data to cache die_error would not be a problem in this situation: data would be
displayed, even if not saved to cache.
2. One of the easiest way of adding output (response) caching to a CGI
script in Perl is in my opinion using CGI::Cache module. Modifying
CGI.pm script (like gitweb) to make use of CGI::Cache requires adding
only a few lines to script source.
While relying on non-core module (which I have not found RPM for) makes
this solution less feasible, its use of slow Cache::SizeAwareFileCache
(from Cache::Cache) makes its not good for gitweb. Also CGI::Cache
requires Tie::Restore to be able to restore ties to filehandles it
watches... something that gitweb doesn't need.
Nevetheless we can borrow some code from CGI::Cache, replacing cache
engine with something more efficient. CGI::Cache is GPL licensed.
Internally, the CGI::Cache module ties the output file descriptor
(usually STDOUT) to an internal variable to which all output is saved.
And that leads us to the next method.
3. tie filehandle (*STDOUT or $out) so that when we are printing to
filehandle, it would also save data in a scalar variable (or duplicate it
to other filehandle). See perltie(1) and Tie::Handle.
4. Multiplexing output stream like tee(1) with PerlIO::tee from PerlIO::Util
is very simple: to start saving output while it is being printed, just do
*STDOUT->push_layer(tee => \$data);
The source, beside scalar reference as above, may be a file name, or a
filehandle. To stop multiplexing, just do
*STDOUT->pop_layer();
I haven't found RPM module for PerlIO::Util (which includes PerlIO::tee).
gitweb/README | 70 +++++++++++++++++++++
gitweb/cache.pm | 78 +++++++++++++++++++++++
gitweb/gitweb.perl | 106 ++++++++++++++++++++++++++++----
t/gitweb-lib.sh | 2 +
t/t9500-gitweb-standalone-no-errors.sh | 19 ++++++
t/t9503/test_cache_interface.pl | 93 ++++++++++++++++++++++++++++
6 files changed, 355 insertions(+), 13 deletions(-)