root/branches/feature-server/plagger/lib/Plagger/Cache.pm

Revision 856 (checked in by miyagawa, 6 years ago)

merge from trunk to plagger-server for Enclosures support and such. Sorry for the big commit

  • Property svn:keywords set to Id Revision
Line 
1 package Plagger::Cache;
2 use strict;
3 use File::Path;
4 use File::Spec;
5 use HTTP::Cookies;
6 use UNIVERSAL::require;
7
8 sub new {
9     my($class, $conf, $name) = @_;
10
11     mkdir $conf->{base}, 0700 unless -e $conf->{base} && -d_;
12
13     # Cache default configuration
14     $conf->{class}  ||= 'Cache::FileCache';
15     $conf->{params} ||= {
16         cache_root => File::Spec->catfile($conf->{base}, 'cache'),
17     };
18
19     $conf->{class}->require;
20
21     # If class is not loadable, falls back to on memory cache
22     if ($@) {
23         Plagger->context->log(error => "Can't load $conf->{class}. Fallbacks to Plagger::Cache::Null");
24         require Plagger::Cache::Null;
25         $conf->{class} = 'Plagger::Cache::Null';
26     }
27
28     my $self = bless {
29         base  => $conf->{base},
30         cache => $conf->{class}->new($conf->{params}),
31     }, $class;
32 }
33
34 sub path_to {
35     my($self, @path) = @_;
36     if (@path > 1) {
37         my @chunk = @path[0..$#path-1];
38         mkpath(File::Spec->catfile($self->{base}, @chunk), 0, 0700);
39     }
40     File::Spec->catfile($self->{base}, @path);
41 }
42
43 sub get {
44     my $self = shift;
45
46     my $value;
47     if ( $self->{cache}->isa('Cache') ) {
48         eval { $value = $self->{cache}->thaw(@_) };
49         if ($@ && $@ =~ /Storable binary/) {
50             $value = $self->{cache}->get(@_);
51         }
52     } else {
53         $value = $self->{cache}->get(@_);
54     }
55
56     my $hit_miss = defined $value ? "HIT" : "MISS";
57     Plagger->context->log(debug => "Cache $hit_miss: $_[0]");
58
59     $value;
60 }
61
62 sub get_callback {
63     my $self = shift;
64     my($key, $callback, $expiry) = @_;
65
66     my $data = $self->get($key);
67     if (defined $data) {
68         return $data;
69     }
70
71     $data = $callback->();
72     if (defined $data) {
73         $self->set($key => $data, $expiry);
74     }
75
76     $data;
77 }
78
79 sub set {
80     my $self = shift;
81     my($key, $value, $expiry) = @_;
82
83     my $setter = $self->{cache}->isa('Cache') && ref $value ? 'freeze' : 'set';
84     $self->{cache}->$setter(@_);
85 }
86
87 sub remove {
88     my $self = shift;
89     $self->{cache}->remove(@_);
90 }
91
92 sub cookie_jar {
93     my($self, $ns) = @_;
94     my $file = $ns ? "$ns.dat" : "global.dat";
95
96     my $dir = File::Spec->catfile($self->{base}, 'cookies');
97     mkdir $dir, 0700 unless -e $dir && -d _;
98
99     return HTTP::Cookies->new(
100         file => File::Spec->catfile($dir, $file),
101         autosave => 1,
102     );
103 }
104
105 1;
Note: See TracBrowser for help on using the browser.