HTTP-Cache-Transparent-1.1/0000755000175000017500000000000012042310655015316 5ustar mattiasmattiasHTTP-Cache-Transparent-1.1/Makefile.PL0000644000175000017500000000115211654316061017274 0ustar mattiasmattiasuse 5.006001; use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'HTTP::Cache::Transparent', VERSION_FROM => 'lib/HTTP/Cache/Transparent.pm', # finds $VERSION PREREQ_PM => { LWP => 0, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'lib/HTTP/Cache/Transparent.pm', # retrieve abstract from module AUTHOR => 'Mattias Holmlund ') : ()), ); HTTP-Cache-Transparent-1.1/META.yml0000644000175000017500000000110512042310655016564 0ustar mattiasmattias--- #YAML:1.0 name: HTTP-Cache-Transparent version: 1.1 abstract: Cache the result of http get-requests persistently. author: - Mattias Holmlund license: unknown distribution_type: module configure_requires: ExtUtils::MakeMaker: 0 build_requires: ExtUtils::MakeMaker: 0 requires: LWP: 0 no_index: directory: - t - inc generated_by: ExtUtils::MakeMaker version 6.55_02 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 HTTP-Cache-Transparent-1.1/Changes0000644000175000017500000000364312042310222016605 0ustar mattiasmattias2012-10-25 Mattias Holmlund Version 1.1 Unlink temporary cachefiles if we fail to give them a proper name Resolves https://rt.cpan.org/Ticket/Display.html?id=60065 Handle multiple simultaneous cache cleanups Hopefully resolves https://rt.cpan.org/Public/Bug/Display.html?id=77015 Handle caching of zero-size documents Resolves https://rt.cpan.org/Public/Bug/Display.html?id=76785 Populate $response->message with the default message for the code Patch from Graham Barr Ensure response has access to request when fetching from cache Patch from Graham Barr. Handle undefined content from servers. 2007-12-12 Mattias Holmlund Version 1.0 Add ApproveContent option. Add pod-tests. Mark internal methods with leading underscore. 2006-03-12 Mattias Holmlund Version 0.7 Add NoUpdate option. Remove Verbose output for HEAD requests. 2005-05-30 Mattias Holmlund Version 0.6 Handle invalid cache-directories. Create the cache directory if it doesn't exist. Store the headers Content-Type, Content-Length, Content-Encoding, Content-Range and Last-Modified in the cache and restore them when returning a cached response. Fix bug in ETag cache handling. 2004-12-08 Mattias Holmlund Version 0.5 Handle spaces in the path to the cache-dir. Handle multiple calls to init() without failing. 2004-10-24 Mattias Holmlund Version 0.4 Renamed from HTTP::TransparentCache to HTTP::Cache::Transparent on request from Brian D Foy on the modules@perl.org list. Add support for ranges. Added test-program from Nigel Horne. 2004-10-15 Mattias Holmlund Version 0.3 Support for libwww < 5.800 Only cache entries with response-code OK. Never delete files in cache with an invalid filename. Document cache format. 2004-10-11 Mattias Holmlund Release 0.2 Support initialization via use directive. Lower perl requirements to Perl 5.6.1. HTTP-Cache-Transparent-1.1/README0000644000175000017500000000271111752545151016207 0ustar mattiasmattias# HTTP-Cache-Transparent HTTP::Cache::Transparent is an implementation of http get that keeps a local cache of fetched pages to avoid fetching the same data from the server if it hasn't been updated. The cache is stored on disk and is thus persistent between invocations. The http-headers If-Modified-Since and ETag are used to let the server decide if the version in the cache is up-to-date or not. HTTP::Cache::Transparent was initially called HTTP::TransparentCache. It was renamed on request from modules@perl.org. ## Limitations This module has a number of limitations that you should be aware of before using it. They are documented in the POD-documentation for the module. ## Installation To install this module type the following: perl Makefile.PL make make test make install ## Dependencies LWP Storable (included with perl) Digest::MD5 (included with perl) All http-requests are made through the LWP module. Data is stored on disk by the Storable module. Digest::MD5 is used for creating a hash of the url. ## Git repository A git repository with the sourcecode for HTTP::Cache::Transparent can be found at https://github.com/mattiash/HTTP-Cache-Transparent. ## Copyright and license Copyright (C) 2004-2007 by Mattias Holmlund This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available. HTTP-Cache-Transparent-1.1/examples/0000755000175000017500000000000012042310654017133 5ustar mattiasmattiasHTTP-Cache-Transparent-1.1/examples/check_server_approve0000755000175000017500000000122311654316061023264 0ustar mattiasmattias#!/usr/bin/perl -w use strict; use LWP::Simple; use HTTP::Cache::Transparent; if( scalar( @ARGV ) != 1 ) { print << "EOD"; usage: check_server Fetches a url via the HTTP::Cache::Transparent module in verbose mode. Uses an ApproveContent sub that only approves responses with a successful response-code. EOD exit; } my( $url ) = @ARGV; HTTP::Cache::Transparent::init( { BasePath => "/tmp/cache", # Directory to store the cache in. Verbose => 1, # Print messages to STDERR. Default is 0. NoUpdate => 0, ApproveContent => sub { return $_[0]->is_success(); }, } ); # Fetch once my $data = get( $url ); print $data; HTTP-Cache-Transparent-1.1/examples/test-range0000755000175000017500000000422411654316061021142 0ustar mattiasmattias#!/usr/bin/perl -w # Copyright (C) 2002 Nigel Horne # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. use strict; use WWW::RobotRules::AnyDBM_File; use LWP::RobotUA; # for spidering and cache lookup use HTTP::Cache::Transparent; HTTP::Cache::Transparent::init( { BasePath => '/tmp/cache', Verbose => 1 } ); my $url = "http://www.bandsman.co.uk"; my $rules = WWW::RobotRules::AnyDBM_File->new('www.bandsman.co.uk/Spider', '/tmp/robots.cache'); my $robot = LWP::RobotUA->new('www.bandsman.co.uk/Spider', 'njh@despammed.com', $rules); $robot->timeout(20); # $robot->delay(1/60); # wait 1 second between accesses to same site $robot->delay(0); $robot->protocols_allowed(['http']); # disabling all others my $request = new HTTP::Request 'GET' => $url; $request->header('Accept' => 'text/html'); $robot->max_size(2048); $request->header('Accept-Encoding' => 'gzip; deflate', 'Referer' => 'http://www.bandsman.co.uk'); my $webdoc = $robot->simple_request($request); if(!$webdoc->is_success) { die $webdoc->status_line . "\n"; exit 1; } my $content = $webdoc->content; if(my $encoding = $webdoc->content_encoding) { if($encoding =~ /gzip/i) { $content = Compress::Zlib::memGunzip($content); if(!defined $content) { die "$url can't be gunziped\n"; } } elsif($encoding =~ /deflate/i) { $content = Compress::Zlib::uncompress($content); if(!defined $content) { die "$url can't be uncompressed\n"; } } } print "$url: " . length($content) . " bytes\n"; print $content . "\n"; HTTP-Cache-Transparent-1.1/examples/check_server0000755000175000017500000000271211654316061021534 0ustar mattiasmattias#!/usr/bin/perl -w use strict; use LWP::Simple; use HTTP::Cache::Transparent; if( scalar( @ARGV ) != 1 ) { print << "EOD"; usage: check_server Fetches a url via the HTTP::Cache::Transparent module in verbose mode. The url is fetched twice to see if the server supports caching or not. The first line of output will say that the url is fetched from the server (unless you have fetched this url before and it is already in the cache). The second line of output will tell you what happened when we tried to fetch the same url a second time: Fetching ... from server: The server returned a new page that was different from the page that was fetched the previous time. Caching didn't improve anything. Fetching ... unchanged from server: The server indicated that caching was not possible, but still returned the exact same page as the last time. Caching didn't improve anything. Fetching ... from cache: The server returned a short note saying that the contents of the cache was still up-to-date. If the page was big, the cache saved us a lot of bandwidth. The cache is stored in the directory /tmp/cache. This directory must exist and be empty before the command is run. EOD exit; } my( $url ) = @ARGV; HTTP::Cache::Transparent::init( { BasePath => "/tmp/cache", # Directory to store the cache in. Verbose => 1, # Print messages to STDERR. Default is 0. } ); # Fetch once my $data = get( $url ); # and twice. $data = get( $url ); HTTP-Cache-Transparent-1.1/t/0000755000175000017500000000000012042310654015560 5ustar mattiasmattiasHTTP-Cache-Transparent-1.1/t/pod-coverage.t0000644000175000017500000000024411654316061020326 0ustar mattiasmattiasuse Test::More; eval "use Test::Pod::Coverage 1.00"; plan skip_all => "Test::Pod::Coverage 1.00 required for testing POD coverage" if $@; all_pod_coverage_ok(); HTTP-Cache-Transparent-1.1/t/pod.t0000644000175000017500000000020011654316061016525 0ustar mattiasmattiasuse Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();HTTP-Cache-Transparent-1.1/t/HTTP-Cache-Transparent.t0000644000175000017500000000076011654316061022035 0ustar mattiasmattias# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl HTTP-Cache-Transparent.t' ######################### # change 'tests => 1' to 'tests => last_test_to_print'; use Test::More tests => 1; BEGIN { use_ok('HTTP::Cache::Transparent') }; ######################### # Insert your test code below, the Test::More module is use()ed here so read # its man page ( perldoc Test::More ) for help writing this test script. HTTP-Cache-Transparent-1.1/MANIFEST0000644000175000017500000000041511654316061016454 0ustar mattiasmattiasChanges Makefile.PL MANIFEST README t/HTTP-Cache-Transparent.t t/pod.t t/pod-coverage.t lib/HTTP/Cache/Transparent.pm examples/check_server examples/check_server_approve examples/test-range META.yml Module meta-data (added by MakeMaker) HTTP-Cache-Transparent-1.1/lib/0000755000175000017500000000000012042310653016062 5ustar mattiasmattiasHTTP-Cache-Transparent-1.1/lib/HTTP/0000755000175000017500000000000012042310653016641 5ustar mattiasmattiasHTTP-Cache-Transparent-1.1/lib/HTTP/Cache/0000755000175000017500000000000012042310653017644 5ustar mattiasmattiasHTTP-Cache-Transparent-1.1/lib/HTTP/Cache/Transparent.pm0000644000175000017500000003313212042310566022510 0ustar mattiasmattiaspackage HTTP::Cache::Transparent; use strict; our $VERSION = '1.1'; =head1 NAME HTTP::Cache::Transparent - Cache the result of http get-requests persistently. =head1 SYNOPSIS use LWP::Simple; use HTTP::Cache::Transparent; HTTP::Cache::Transparent::init( { BasePath => '/tmp/cache', } ); my $data = get( 'http://www.sn.no' ); =head1 DESCRIPTION An implementation of http get that keeps a local cache of fetched pages to avoid fetching the same data from the server if it hasn't been updated. The cache is stored on disk and is thus persistent between invocations. Uses the http-headers If-Modified-Since and ETag to let the server decide if the version in the cache is up-to-date or not. The cache is implemented by modifying the LWP::UserAgent class to seamlessly cache the result of all requests that can be cached. =head1 INITIALIZING THE CACHE HTTP::Cache::Transparent provides an init-method that sets the parameters for the cache and overloads a method in LWP::UserAgent to activate the cache.After init has been called, the normal LWP-methods (LWP::Simple as well as the more full-fledged LWP::Request methods) should be used as usual. =over 4 =cut use Carp; use LWP::UserAgent; use HTTP::Status qw/RC_NOT_MODIFIED RC_OK RC_PARTIAL_CONTENT status_message/; use Digest::MD5 qw/md5_hex/; use IO::File; use File::Copy; use File::Path; use Cwd; # These are the response-headers that we should store in the # cache-entry and recreate when we return a cached response. my @cache_headers = qw/Content-Type Content-Encoding Content-Length Content-Range Last-Modified/; my $basepath; my $maxage; my $verbose; my $noupdate; my $approvecontent; my $org_simple_request; =item init Initialize the HTTP cache. Takes a single parameter which is a hashref containing named arguments to the object. HTTP::Cache::Transparent::init( { # Directory to store the cache in. BasePath => "/tmp/cache", # How many hours should items be kept in the cache # after they were last requested? # Default is 8*24. MaxAge => 8*24, # Print progress-messages to STDERR. # Default is 0. Verbose => 1, # If a request is made for a url that has been requested # from the server less than NoUpdate seconds ago, the # response will be generated from the cache without # contacting the server. # Default is 0. NoUpdate => 15*60, # When a url has been downloaded and the response indicates that # has been modified compared to the content in the cache, # the ApproveContent callback is called with the HTTP::Response. # The callback shall return true if the response shall be used and # stored in the cache or false if the response shall be discarded # and the response in the cache used instead. # This mechanism can be used to work around servers that return errors # intermittently. The default is to accept all responses. ApproveContent => sub { return $_[0]->is_success }, } ); The directory where the cache is stored must be writable. It must also only contain files created by HTTP::Cache::Transparent. =cut my $initialized = 0; sub init { my( $arg ) = @_; defined( $arg->{BasePath} ) or croak( "You must specify a BasePath" ); $basepath = $arg->{BasePath}; if( not -d $basepath ) { eval { mkpath($basepath) }; if ($@) { print STDERR "$basepath is not a directory and cannot be created: $@\n"; exit 1; } } # Append a trailing slash if it is missing. $basepath =~ s%([^/])$%$1/%; $maxage = $arg->{MaxAge} || 8*24; $verbose = $arg->{Verbose} || 0; $noupdate = $arg->{NoUpdate} || 0; $approvecontent = $arg->{ApproveContent} || sub { return 1; }; # Make sure that LWP::Simple does not use its simplified # get-method that bypasses LWP::UserAgent. $LWP::Simple::FULL_LWP++; unless ($initialized++) { $org_simple_request = \&LWP::UserAgent::simple_request; no warnings; *LWP::UserAgent::simple_request = \&_simple_request_cache } } =item Initializing from use-line An alternative way of initializing HTTP::Cache::Transparent is to supply parameters in the use-line. This allows you to write use HTTP::Cache::Transparent ( BasePath => '/tmp/cache' ); which is exactly equivalent to use HTTP::Cache::Transparent; HTTP::Cache::Transparent::init( BasePath => '/tmp/cache' ); The advantage to using this method is that you can do perl -MHTTP::Cache::Transparent=BasePath,/tmp/cache myscript.pl or even set the environment variable PERL5OPT PERL5OPT=-MHTTP::Cache::Transparent=BasePath,/tmp/cache myscript.pl and have all the http-requests performed by myscript.pl go through the cache without changing myscript.pl =back =cut sub import { my( $module, %args ) = @_; return if (scalar(keys(%args)) == 0); HTTP::Cache::Transparent::init( \%args ); } END { _remove_old_entries(); } sub _simple_request_cache { my($self, $r, $content_cb, $read_size_hint) = @_; my $res; if( $r->method eq "GET" and not defined( $r->header( 'If-Modified-Since' ) ) and not defined( $content_cb ) ) { print STDERR "Fetching " . $r->uri if( $verbose ); my $url = $r->uri->as_string; my $key = $url; $key .= "\n" . $r->header('Range') if defined $r->header('Range'); my $filename = $basepath . _urlhash( $url ); my $fh; my $meta; if( -s $filename ) { $fh = new IO::File "< $filename" or die "Failed to read from $filename"; $meta = _read_meta( $fh ); if( $meta->{Url} eq $url ) { $meta->{'Range'} = "" unless defined( $meta->{'Range'} ); # Check that the Range is the same for this request as # for the one in the cache. if( (not defined( $r->header( 'Range' ) ) ) or $r->header( 'Range' ) eq $meta->{'Range'} ) { $r->header( 'If-Modified-Since', $meta->{'Last-Modified'} ) if exists( $meta->{'Last-Modified'} ); $r->header( 'If-None-Match', $meta->{ETag} ) if( exists( $meta->{ETag} ) ); } } else { warn "Cache collision: $url and $meta->{Url} have the same md5sum"; } } if( defined( $meta->{'X-HCT-LastUpdated'} ) and $noupdate > (time - $meta->{'X-HCT-LastUpdated'} ) ) { print STDERR " from cache without checking with server.\n" if $verbose; $res = HTTP::Response->new( $meta->{Code} ); $res->request($r); _get_from_cachefile( $filename, $fh, $res, $meta ); $fh->close() if defined $fh;; return $res; } $res = &$org_simple_request( $self, $r ); if( $res->code == RC_NOT_MODIFIED ) { print STDERR " from cache.\n" if( $verbose ); _get_from_cachefile( $filename, $fh, $res, $meta ); $fh->close() if defined $fh;; # We need to rewrite the cache-entry to update X-HCT-LastUpdated _write_cache_entry( $filename, $url, $r, $res ); return $res; } elsif( defined( $meta->{'X-HCT-LastUpdated'} ) and not &{$approvecontent}( $res ) ) { print STDERR " from cache since the response was not approved.\n" if( $verbose ); _get_from_cachefile( $filename, $fh, $res, $meta ); $fh->close() if defined $fh;; # Do NOT update the cache! return $res; } else { $fh->close() if defined $fh;; my $content = $res->content; $content = "" if not defined $content; if( defined( $meta->{MD5} ) and md5_hex( $content ) eq $meta->{MD5} ) { $res->header( "X-Content-Unchanged", 1 ); print STDERR " unchanged" if( $verbose ); } print STDERR " from server.\n" if( $verbose ); _write_cache_entry( $filename, $url, $r, $res ) if( $res->code == RC_OK or $res->code == RC_PARTIAL_CONTENT ); } } else { # We won't try to cache this request. $res = &$org_simple_request( $self, $r, $content_cb, $read_size_hint ); } return $res; } sub _get_from_cachefile { my( $filename, $fh, $res, $meta ) = @_; my $content; my $buf; while ( $fh->read( $buf, 1024 ) > 0 ) { $content .= $buf; } $fh->close(); $content = "" if not defined $content; # Set last-accessed for cache-entry. my $mtime = time; utime( $mtime, $mtime, $filename ); # modify response if( $HTTP::Message::VERSION >= 1.44 ) { $res->content_ref( \$content ); } else { $res->content( $content ); } # For HTTP::Cache::Transparent earlier than 0.4, # there is no Code in the cache. if( defined( $meta->{Code} ) ) { $res->code( $meta->{Code} ); } else { $res->code( RC_OK ); } $res->message(status_message($res->code) || "Unknown code"); foreach my $h (@cache_headers) { $res->header( $h, $meta->{$h} ) if defined( $meta->{ $h } ); } $res->header( "X-Cached", 1 ); $res->header( "X-Content-Unchanged", 1 ); } # Read metadata and position filehandle at start of data. sub _read_meta { my( $fh ) = @_; my %meta; my( $key, $value ); do { my $line = <$fh>; ( $key, $value ) = ($line =~ /(\S+)\s+(.*)[\n\r]*/); $meta{$key} = $value if( defined $value ); } while( defined( $value ) ); return \%meta; } # Write metadata and position filehandle where data should be written. sub _write_meta { my( $fh, $meta ) = @_; foreach my $key (sort keys( %{$meta} ) ) { print $fh "$key $meta->{$key}\n"; } print $fh "\n"; } sub _write_cache_entry { my( $filename, $url, $req, $res ) = @_; my $out_filename = "$filename.tmp$$"; my $fh = new IO::File "> $out_filename" or die "Failed to write to $out_filename"; my $meta; $meta->{Url} = $url; $meta->{ETag} = $res->header('ETag') if defined( $res->header('ETag') ); my $content = $res->content; $content = "" if not defined $content; $meta->{MD5} = md5_hex( $content ); $meta->{Range} = $req->header('Range') if defined( $req->header('Range') ); $meta->{Code} = $res->code; $meta->{'X-HCT-LastUpdated'} = time; foreach my $h (@cache_headers) { $meta->{$h} = $res->header( $h ) if defined $res->header( $h ); } _write_meta( $fh, $meta ); print $fh $content; $fh->close; move( $out_filename, $filename ) || unlink $out_filename; } sub _urlhash { my( $url ) = @_; return md5_hex( $url ); } sub _remove_old_entries { if( defined( $basepath ) and -d( $basepath ) ) { my $oldcwd = getcwd(); chdir( $basepath ); my @files = glob("*"); foreach my $file (@files) { if( $file !~ m%^[0-9a-f]{32}$% ) { print STDERR "HTTP::Cache::Transparent: Unknown file found in cache directory: $basepath$file\n"; } else { my $age = (-M $file); # The file may have disappeared if another process has cleaned # the cache. if( defined($age) && ( $age*24 > $maxage ) ) { print STDERR "Deleting $file.\n" if( $verbose ); unlink( $file ); } } } chdir( $oldcwd ); } } =head1 INSPECTING CACHE BEHAVIOR The HTTP::Cache::Transparent inserts two special headers in the HTTP::Response object. These can be accessed via the HTTP::Response::header()-method. =over 4 =item X-Cached This header is inserted and set to 1 if the response is delivered from the cache instead of from the server. =item X-Content-Unchanged This header is inserted and set to 1 if the content returned is the same as the content returned the last time this url was fetched. This header is always inserted and set to 1 when the response is delivered from the cache. =back =head1 LIMITATIONS This module has a number of limitations that you should be aware of before using it. =over 4 =item - There is no upper limit to how much diskspace the cache requires. The only limiting mechanism is that data for urls that haven't been requested in the last MaxAge hours will be removed from the cache the next time the program exits. =item - Currently, only get-requests that store the result in memory (i.e. do not use the option to have the result stored directly in a file or delivered via a callback) is cached. I intend to remove this limitation in a future version. =item - The support for Ranges is a bit primitive. It creates a new object in the cache for each unique combination of url and range. This will work ok as long as you always request the same range(s) for a url. =item - The cache doesn't properly check and store all headers in the HTTP request and response. Therefore, if you request the same url repeatedly with different sets of headers (cookies, accept-encoding etc), and these headers affect the response from the server, the cache may return the wrong response. =back =head1 CACHE FORMAT The cache is stored on disk as one file per cached object. The filename is equal to the md5sum of the url and the Range-header if it exists. The file contains a set of key/value-pairs with metadata (one entry per line) followed by a blank line and then the actual data returned by the server. The last modified date of the cache file is set to the time when the cache object was last requested by a user. =head1 AUTHOR Mattias Holmlund, E$firstname -at- $lastname -dot- seE L =head1 GIT REPOSITORY A git repository containing the source for this module can be found via http://git.holmlund.se/ =head1 COPYRIGHT AND LICENSE Copyright (C) 2004-2007 by Mattias Holmlund This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available. =cut 1;