blib/lib/Email/Fingerprint/Cache.pm

filter: Statementstmt 100% 84 / 84 Branchbran 100% 20 / 20 Conditioncond 100% 10 / 10 MC/DCmcdc 100% 6 / 6 Subroutinesub 100% 19 / 19 Podpod 100% 10 / 10 totaltotal 100% 149 / 149 SCAR 28.3
CC
17
Cov
100%
BUILD
7.0
purge
5.0
set_file
3.0
CRAP 17.0
« blib/lib/Email/Fingerprint.pm ↑ Summary blib/lib/Email/Fingerprint/Cache/AnyDBM.pm »
1 package Email::Fingerprint::Cache;
2 4 ▶use Class::Std;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 4 ▶use Carp qw( croak cluck );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Scalar::Util qw( reftype blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Email::Fingerprint::Cache - Cache observed email fingerprints
13  
14 =head1 VERSION
15  
16 Version 0.01
17  
18 =cut
19  
20 3 our $VERSION = '0.01';
21  
22 =head1 SYNOPSIS
23  
24 use Email::Fingerprint::Cache;
25  
26 my %fingerprints; # To access cache contents
27  
28 # Create a cache
29 my $cache = new Email::Fingerprint::Cache(
30 backend => "AnyDBM",
31 hash => \%fingerprints,
32 file => $file, # Created if doesn't exist
33 ttl => 3600 * 24 * 7, # Purge records after one week
34 );
35  
36 # Prepare it for use
37 $cache->lock or die "Couldn't lock: $!"; # Waits for lock
38 $cache->open or die "Couldn't open: $!";
39  
40 # Work with fingerprints
41 for my (@message_fingerprints) {
42  
43 if ($fingerprints{$_}) {
44 print "Fingerprint found: $_\n";
45 next;
46 }
47  
48 my $now = time;
49 $fingerprints{$_} = $now;
50  
51 print "Fingerprint added: $_\n";
52 }
53  
54 # Get rid of old records
55 $cache->purge;
56  
57 # Print a listing of all fingerprints
58 $cache->dump;
59  
60 # Finish up
61 $cache->close;
62 $cache->unlock;
63  
64 =head1 ATTRIBUTES
65  
66 =cut
67  
68 3 my %hash :ATTR( :get<hash> ) = ();
69 3 my %ttl :ATTR( :name<ttl> :default(604800) ) = ();
70 3 my %backend :ATTR( :init_arg<backend> :default('AnyDBM') ) = ();
71  
72 =head1 METHODS
73  
74 =head2 new
75  
76 my $fingerprint = new Email::Fingerprint::Cache(
77 file => $file, # Default: .maildups
78 backend => "AnyDBM", # Default: "AnyDBM"
79 ttl => $sec, # Default: 3600*24*7
80 hash => $ref, # Optional
81 );
82  
83 Returns a new Email::Fingerprint::Cache. The cache must still be opened
84 before it can be used.
85  
86 =head2 BUILD
87  
88 Internal helper method; never called directly by users.
89  
90 =cut
91  
92 sub BUILD {
93 16 ▶ my ( $self, $ident, $args ) = @_;
Subroutine BUILD: called CC=7 SCAR=19.5
Pod documented
94  
95 # Default hash is a fresh-n-tasty anonymous hash
96 15 ▶ $hash{$ident} = defined $args->{hash} ? $args->{hash} : {};
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'hash'} ? : 7 8 15
97  
98 # Backend will also need access to the hash
99 15 $args->{hash} = $hash{$ident};
100  
101 # Default backend is AnyDBM
102 16 ▶ my $backend = defined $args->{backend} ? $args->{backend} : 'AnyDBM';
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'backend'} ? : 5 10 15
103  
104 # Default cache file
105 15 ▶ $args->{file} ||= '.maildups';
Condition100%2/2
$args->{"file"} ||= ".maildups"
l!l
87
MC/DC100%1/1
$args->{"file"} ||= ".maildups"
$args->{"file"}
Truth table100%2/2
A
A= $args->{"file"}
Aresult
11
00
106  
107 # Try accessing package as a subclass of Email::Fingerprint::Cache
108 15 my $package = __PACKAGE__ . "::" . $backend;
109 16 ▶ eval "use $package"; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
110  
111 # Try accessing package using the given name exactly. If this fails,
112 # we try constructing a backend anyway, in case the module is already
113 # imported--or, e.g., defined in the script file itself.
114 15 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 4 11 15
115 4 $package = $backend;
116 5 eval "use $package"; ## no critic
117 }
118  
119 16 undef $backend;
120  
121 # Perhaps the correct module was loaded by our caller;
122 # try instantiating the backend even if the above steps
123 # all failed.
124 16 eval {
125 $backend = $package->new({
126 file => $args->{file},
127 hash => $args->{hash},
128 16 });
129 };
130  
131 # It's a fatal error if the backend doesn't load
132 16 ▶ croak "Can't load backend module" if $@ or not $backend;
Branch: 1 branch
BranchTrueFalseTotal
if $@ or not $backend 2 13 15
Condition100%3/3
$@ or not $backend
l!l&&r!l&&!r
1113
MC/DC100%2/2
$@ or not $backend
$@ not $backend
Truth table100%3/3
A or not(B)
A= $@B= not $backend
ABresult
1X1
011
000
133  
134 14 $backend{$ident} = $backend;
135 }
136  
137 =head2 set_file
138  
139 $file = $cache->set_file( 'foo' ) or die "Failed to set filename";
140 # now $file eq 'foo.db' or 'foo.dir', etc., depending on the backend;
141 # it is almost certainly NOT 'foo'.
142  
143 Sets the file to be used for the cache. Returns the actual filename
144 on success; false on failure.
145  
146 The actual filename will probably differ from the 'foo', because
147 the backend will usually add an extension or otherwise munge it.
148  
149 C<set_file> has I<no> effect while the cache file is locked or open!
150  
151 =cut
152  
153 sub set_file {
154 6 ▶ my ($self, $file) = @_;
Subroutine set_file: called CC=3 SCAR=11.0
Pod documented
155  
156 # Validation
157 6 ▶ return if $self->get_backend->is_locked;
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_backend->is_locked 1 4 5
158 5 ▶ return if $self->get_backend->is_open;
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_backend->is_open 1 3 4
159  
160 # OK, there's no harm in changing the file attribute
161 4 $self->get_backend->set_file($file);
162  
163 4 1;
164 }
165  
166 =head2 get_backend
167  
168 Returns the backend object for this cache.
169  
170 =cut
171  
172 sub get_backend :PRIVATE() {
173 75 ▶ my $self = shift;
Subroutine get_backend: called CC=1 SCAR=0.0
Pod documented
174 75 return $backend{ident $self};
175 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
176  
177 =head2 dump
178  
179 # Be a good citizen
180 $cache->lock;
181 $cache->open;
182  
183 $cache->dump;
184  
185 # Be a good neighbor
186 $cache->close;
187 $cache->unlock;
188  
189 Dump a human-readable version of the contents of the cache. Data is
190 printed in timestamp order.
191  
192 The cache I<must> first be opened, and I<should> first be locked.
193  
194 =cut
195  
196 sub dump {
197 2 ▶ my $self = shift;
Subroutine dump: called CC=2 SCAR=6.9
Pod documented
198 2 my $hash = $self->get_hash;
199  
200 2 for my $key ( sort { $hash->{$a} <=> $hash->{$b} } keys %$hash )
201 {
202 5001 my $value = $hash->{$key};
203 5001 print "$value\t", scalar gmtime $value, "\t$key\n";
204 }
205 }
206  
207 =head2 open
208  
209 $cache->open or die;
210  
211 Open the cache file, and tie it to a hash. This is delegated to the
212 backend.
213  
214 =cut
215  
216 sub open {
217 11 ▶ my $self = shift;
Subroutine open: called CC=1 SCAR=0.0
Pod documented
218  
219 11 return $self->_delegate( "open", @_ );
220 }
221  
222 =head2 close
223  
224 $cache->close;
225  
226 Close the cache file and untie the hash.
227  
228 =cut
229  
230 sub close {
231 9 ▶ my $self = shift;
Subroutine close: called CC=1 SCAR=0.0
Pod documented
232  
233 9 return $self->_delegate( "close", @_ );
234 }
235  
236 =head2 lock
237  
238 $cache->lock or die; # returns immediately
239 $cache->lock( block => 1 ) or die; # Waits for a lock
240 $cache->lock( %opts ) or die; # Backend-specific options
241  
242 Lock the DB file to guarantee exclusive access.
243  
244 =cut
245  
246 sub lock {
247 7 ▶ my $self = shift;
Subroutine lock: called CC=1 SCAR=0.0
Pod documented
248  
249 7 return $self->_delegate( "lock", @_ );
250 }
251  
252 =head2 unlock
253  
254 $cache->unlock or warn "Unlock failed";
255  
256 Unlock the DB file.
257  
258 =cut
259  
260 sub unlock {
261 20 ▶ my $self = shift;
Subroutine unlock: called CC=1 SCAR=0.0
Pod documented
262 20 return $self->_delegate( "unlock", @_ );
263 }
264  
265 =head2 purge
266  
267 $cache->purge; # Use default TTL
268 $cache->purge( ttl => 3600 ); # Everything older than 1 hour
269  
270 Purge the cache of old entries. This reduces the risk of false positives
271 from things like reused message IDs, but increases the risk of false
272 negatives.
273  
274 The default is one week. Dedicated spam-fighters might prefer to use a
275 longer TTL.
276  
277 =cut
278  
279 sub purge {
280 6 ▶ my $self = shift;
Subroutine purge: called CC=5 SCAR=16.1
Pod documented
281 6 my %opts = @_;
282  
283 6 my $hash = $self->get_hash;
284 6 ▶ my $ttl = defined $opts{ttl} ? $opts{ttl} : $self->get_ttl;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'ttl'} ? : 4 2 6
285 6 my $now = time;
286  
287 6 for my $key ( keys %$hash )
288 {
289 3104 ▶ my $timestamp = $hash->{$key} || 0; # Also clobbers bad data like undef
Condition100%2/2
$hash->{$key} || 0
l!l
31013
MC/DC100%1/1
$hash->{$key} || 0
$hash->{$key}
Truth table100%2/2
A
A= $hash->{$key}
Aresult
11
00
290 3104 ▶ delete $hash->{$key} if ($now - $timestamp) > $ttl;
Branch: 1 branch
BranchTrueFalseTotal
if $now - $timestamp > $ttl 1603 1501 3104
291 }
292  
293 6 1;
294 }
295  
296 =head2 DESTROY
297  
298 Clean up the module. If the hash is still tied, we warn the user and call
299 C<close()> on C<$self>.
300  
301 =head2 DEMOLISH
302  
303 Internal helper method, never called directly by user.
304  
305 =cut
306  
307 sub DEMOLISH {
308 15 ▶ my $self = shift;
Subroutine DEMOLISH: called CC=3 SCAR=11.0
Pod documented
309  
310 15 my $backend = $self->get_backend;
311  
312 # Failing to close() the cache is bad: data won't be
313 # committed to disk.
314 15 ▶ if ( $backend and $backend->is_open )
Branch: 1 branch
BranchTrueFalseTotal
if ($backend and $backend->is_open) 2 13 15
Condition100%3/3
$backend and $backend->is_open
!ll&&!rl&&r
2112
MC/DC100%2/2
$backend and $backend->is_open
$backend $backend->is_open
Truth table100%3/3
A and B
A= $backendB= $backend->is_open
ABresult
0X0
100
111
315 {
316 2 cluck "Cache DESTROY()ed before it was close()ed";
317 2 $self->close;
318 }
319  
320 # Failure to unlock() is rude, but we don't say anything.
321 15 $self->unlock;
322 }
323  
324 =head2 _delegate
325  
326 Delegate the specified method to the backend. Internal method.
327  
328 =cut
329  
330 sub _delegate :PRIVATE() {
331 46 ▶ my ($self, $method, @args) = @_;
Subroutine _delegate: called CC=2 SCAR=6.9
332  
333 46 my $backend = $self->get_backend;
334 46 ▶ return unless $backend;
Branch: 1 branch
BranchTrueFalseTotal
unless $backend 2 44 46
335  
336 44 return $backend->$method(@args);
337 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
338  
339 =head1 AUTHOR
340  
341 Len Budney, C<< <lbudney at pobox.com> >>
342  
343 =head1 BUGS
344  
345 The C<dump()> method assumes that Perl's C<time()> function returns
346 seconds since the UNIX epoch, 00:00:00 UTC, January 1, 1970. The
347 module will work on architectures with non-standard epochs, but the
348 automated tests will fail.
349  
350 Please report any bugs or feature requests to
351 C<bug-email-fingerprint at rt.cpan.org>, or through the web interface at
352 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Email-Fingerprint>.
353 I will be notified, and then you'll automatically be notified of progress on
354 your bug as I make changes.
355  
356 =head1 SUPPORT
357  
358 You can find documentation for this module with the perldoc command.
359  
360 perldoc Email::Fingerprint::Cache
361  
362 You can also look for information at:
363  
364 =over 4
365  
366 =item * AnnoCPAN: Annotated CPAN documentation
367  
368 L<http://annocpan.org/dist/Email-Fingerprint>
369  
370 =item * CPAN Ratings
371  
372 L<http://cpanratings.perl.org/d/Email-Fingerprint>
373  
374 =item * RT: CPAN's request tracker
375  
376 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Email-Fingerprint>
377  
378 =item * Search CPAN
379  
380 L<http://search.cpan.org/dist/Email-Fingerprint>
381  
382 =back
383  
384 =head1 ACKNOWLEDGEMENTS
385  
386 Email::Fingerprint::Cache is based on caching code in the
387 C<eliminate_dups> script by Peter Samuel and available at
388 L<http://www.qmail.org/>.
389  
390 =head1 COPYRIGHT & LICENSE
391  
392 Copyright 2006-2011 Len Budney, all rights reserved.
393  
394 This program is free software; you can redistribute it and/or modify it
395 under the same terms as Perl itself.
396  
397 =cut
398  
399 3 1;
« blib/lib/Email/Fingerprint.pm ↑ Summary blib/lib/Email/Fingerprint/Cache/AnyDBM.pm »