gitweb/lib - Use CHI compatibile (compute method) caching interface
[git/jnareb-git.git] / gitweb / lib / GitwebCache / CacheOutput.pm
blob4a96ac9e573641e6b5babda6a21df683a8506dcf
1 # gitweb - simple web interface to track changes in git repositories
3 # (C) 2010, Jakub Narebski <jnareb@gmail.com>
4 # (C) 2006, John 'Warthog9' Hawley <warthog19@eaglescrag.net>
6 # This program is licensed under the GPLv2
9 # Capturing and caching (gitweb) output
12 # Capture output, save it in cache and print it, or retrieve it from
13 # cache and print it.
15 package GitwebCache::CacheOutput;
17 use strict;
18 use warnings;
20 use Exporter qw(import);
21 our @EXPORT = qw(cache_output capture_stop);
22 our %EXPORT_TAGS = (all => [ @EXPORT ]);
24 # cache_output($cache, $capture, $key, $action_code);
26 # Attempts to get $key from $cache; if successful, prints the value.
27 # Otherwise, calls $action_code, capture its output using $capture,
28 # and use the captured output as the new value for $key in $cache,
29 # then print captured output.
31 # It is assumed that captured data is already converted and it is
32 # in ':raw' format (and thus restored in ':raw' from cache)
34 # default capture class (engine), if none provided
35 our $DEFAULT_CAPTURE_CLASS = 'GitwebCache::Capture::Simple';
36 sub cache_output {
37 my ($cache, $capture, $key, $code) = @_;
39 $capture = setup_capture($capture);
41 my $data;
42 if ($cache->can('compute')) {
43 $data = cache_output_compute($cache, $capture, $key, $code);
44 } else {
45 $data = cache_output_get_set($cache, $capture, $key, $code);
48 if (defined $data) {
49 binmode STDOUT, ':raw';
50 print $data;
53 return $data;
56 # for $cache which can ->compute($key, $code)
57 sub cache_output_compute {
58 my ($cache, $capture, $key, $code) = @_;
60 my $data = $cache->compute($key, sub {
61 $capture->capture($code);
62 });
64 return $data;
67 # for $cache which can ->get($key) and ->set($key, $data)
68 sub cache_output_get_set {
69 my ($cache, $capture, $key, $code) = @_;
71 # check if data is in the cache
72 my $data = $cache->get($key);
74 # capture and cache output, if there was nothing in the cache
75 if (!defined $data) {
76 $data = $capture->capture($code);
77 $cache->set($key, $data) if defined $data;
80 return $data;
83 # capture_stop($cache, $capture);
85 # Stops capturing output; to be used in die_error, so that error pages
86 # are not cached (not captured and cached).
87 sub capture_stop {
88 my ($cache, $capture) = @_;
90 if (defined $capture) {
91 return $capture->capture_stop();
93 return;
96 # ......................................................................
97 # helper subroutines
99 # setup capture engine
100 sub setup_capture {
101 my $capture = shift;
103 $capture ||= $DEFAULT_CAPTURE_CLASS;
104 if (!ref($capture)) {
105 eval "require $capture;" or die $@;
106 $capture = $capture->new();
109 return $capture;
113 __END__
114 # end of package GitwebCache::CacheOutput