EnsEMBL/Utils/Cache.pm untested

filter: Statementstmt 0.0% 0 / 237 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 45 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 440 CC 60 SCAR 41.8
CC
60
Cov
0%
FETCH
156.0
STORE
110.0
TIEHASH
90.0
CRAP 65.5
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
5  
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9  
10 http://www.apache.org/licenses/LICENSE-2.0
11  
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17  
18 =cut
19  
20  
21 =head1 CONTACT
22  
23 Please email comments or questions to the public Ensembl
24 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
25  
26 Questions may also be sent to the Ensembl help desk at
27 <http://www.ensembl.org/Help/Contact>.
28  
29 =cut
30  
31 # This package, originally distributed by CPAN, has been modified from
32 # its original version in order to be used by the ensembl project.
33 #
34 # 8 July 2002 - changed package name
35 #
36  
37 package Bio::EnsEMBL::Utils::Cache;
38 $Bio::EnsEMBL::Utils::Cache::VERSION = '114.0.0_50'; # TRIAL
39 $Bio::EnsEMBL::Utils::Cache::VERSION = '114.0.050';
40 use strict;
41 use vars qw(
42 $VERSION $Debug $STRUCT_SIZE $REF_SIZE
43 $BEFORE $AFTER $KEY $VALUE $BYTES $DIRTY
44 );
45  
46 $VERSION = .17;
47 $Debug = 0; # set to 1 for summary, 2 for debug output
48 $STRUCT_SIZE = 240; # per cached elem bytes overhead, approximate
49 $REF_SIZE = 16;
50  
51 # NODE ARRAY STRUCT
52 $KEY = 0;
53 $VALUE = 1;
54 $BYTES = 2;
55 $BEFORE = 3;
56 $AFTER = 4;
57 $DIRTY = 5;
58  
59 =pod
60  
61 =head1 NAME
62  
63 Tie::Cache - LRU Cache in Memory
64  
65 =head1 SYNOPSIS
66  
67 use Tie::Cache;
68 tie %cache, 'Tie::Cache', 100, { Debug => 1 };
69 tie %cache2, 'Tie::Cache', { MaxCount => 100, MaxBytes => 50000 };
70 tie %cache3, 'Tie::Cache', 100, { Debug => 1 , WriteSync => 0};
71  
72 # Options ##################################################################
73 #
74 # Debug => 0 - DEFAULT, no debugging output
75 # 1 - prints cache statistics upon destroying
76 # 2 - prints detailed debugging info
77 #
78 # MaxCount => Maximum entries in cache.
79 #
80 # MaxBytes => Maximum bytes taken in memory for cache based on approximate
81 # size of total cache structure in memory
82 #
83 # There is approximately 240 bytes used per key/value pair in the cache for
84 # the cache data structures, so a cache of 5000 entries would take
85 # at approximately 1.2M plus the size of the data being cached.
86 #
87 # MaxSize => Maximum size of each cache entry. Larger entries are not cached.
88 # This helps prevent much of the cache being flushed when
89 # you set an exceptionally large entry. Defaults to MaxBytes/10
90 #
91 # WriteSync => 1 - DEFAULT, write() when data is dirtied for
92 # TRUE CACHE (see below)
93 # 0 - write() dirty data as late as possible, when leaving
94 # cache, or when cache is being DESTROY'd
95 #
96 ############################################################################
97  
98 # cache supports normal tied hash functions
99 $cache{1} = 2; # STORE
100 print "$cache{1}\n"; # FETCH
101  
102 # FIRSTKEY, NEXTKEY
103 while(($k, $v) = each %cache) { print "$k: $v\n"; }
104
105 delete $cache{1}; # DELETE
106 %cache = (); # CLEAR
107  
108 =head1 DESCRIPTION
109  
110 This module implements a least recently used (LRU) cache in memory
111 through a tie interface. Any time data is stored in the tied hash,
112 that key/value pair has an entry time associated with it, and
113 as the cache fills up, those members of the cache that are
114 the oldest are removed to make room for new entries.
115  
116 So, the cache only "remembers" the last written entries, up to the
117 size of the cache. This can be especially useful if you access
118 great amounts of data, but only access a minority of the data a
119 majority of the time.
120  
121 The implementation is a hash, for quick lookups,
122 overlaying a doubly linked list for quick insertion and deletion.
123 On a WinNT PII 300, writes to the hash were done at a rate
124 3100 per second, and reads from the hash at 6300 per second.
125 Work has been done to optimize refreshing cache entries that are
126 frequently read from, code like $cache{entry}, which moves the
127 entry to the end of the linked list internally.
128  
129 =cut
130  
131 sub TIEHASH {
132 my($class, $max_count, $options) = @_;
133  
134 if(ref($max_count)) {
135 $options = $max_count;
136 $max_count = $options->{MaxCount};
137 }
138
139 unless($max_count || $options->{MaxBytes}) {
140 die('you must specify cache size with either MaxBytes or MaxCount');
141 }
142  
143 my $sync = exists($options->{WriteSync}) ? $options->{WriteSync} : 1;
144  
145 my $self = bless
146 {
147 # how many items to cache
148 max_count=> $max_count,
149
150 # max bytes to cache
151 max_bytes => $options->{MaxBytes},
152
153 # max size (in bytes) of an individual cache entry
154 max_size => $options->{MaxSize} || ($options->{MaxBytes} ? (int($options->{MaxBytes}/10) + 1) : 0),
155
156 # class track, so know if overridden subs should be used
157 'class' => $class,
158 'subclass' => $class ne 'Tie::Cache' ? 1 : 0,
159
160 # current sizes
161 count=>0,
162 bytes=>0,
163
164 # inner structures
165 head=>0,
166 tail=>0,
167 nodes=>{},
168 'keys'=>[],
169
170 # statistics
171 hit => 0,
172 miss => 0,
173
174 # config
175 sync => $sync,
176 dbg => $options->{Debug} || $Debug
177
178
179 }, $class;
180
181 if (($self->{max_bytes} && ! $self->{max_size})) {
182 die("MaxSize must be defined when MaxBytes is");
183 }
184  
185 if($self->{max_bytes} and $self->{max_bytes} < 1000) {
186 die("cannot set MaxBytes to under 1000, each raw entry takes $STRUCT_SIZE bytes alone");
187 }
188  
189 if($self->{max_size} && $self->{max_size} < 3) {
190 die("cannot set MaxSize to under 3 bytes, assuming error in config");
191 }
192  
193 $self;
194 }
195  
196 # override to write data leaving cache
197 sub write { undef; }
198 # commented this section out for speed
199 # my($self, $key, $value) = @_;
200 # 1;
201 #}
202  
203 # override to get data if not in cache, should return $value
204 # associated with $key
205 sub read { undef; }
206 # commented this section out for speed
207 # my($self, $key) = @_;
208 # undef;
209 #}
210  
211 sub FETCH {
212 my($self, $key) = @_;
213  
214 my $node = $self->{nodes}{$key};
215 if($node) {
216 # refresh node's entry
217 $self->{hit}++; # if $self->{dbg};
218  
219 # we used to call delete then insert, but we streamlined code
220 if(my $after = $node->[$AFTER]) {
221 $self->{dbg} > 1 and $self->print("update() node $node to tail of list");
222 # reconnect the nodes
223 my $before = $after->[$BEFORE] = $node->[$BEFORE];
224 if($before) {
225 $before->[$AFTER] = $after;
226 } else {
227 $self->{head} = $after;
228 }
229  
230 # place at the end
231 $self->{tail}[$AFTER] = $node;
232 $node->[$BEFORE] = $self->{tail};
233 $node->[$AFTER] = undef;
234 $self->{tail} = $node; # always true after this
235 } else {
236 # if there is nothing after node, then we are at the end already
237 # so don't do anything to move the nodes around
238 die("this node is the tail, so something's wrong")
239 unless($self->{tail} eq $node);
240 }
241  
242 $self->print("FETCH [$key, $node->[$VALUE]]") if ($self->{dbg} > 1);
243 $node->[$VALUE];
244 } else {
245 # we have a cache miss here
246 $self->{miss}++; # if $self->{dbg};
247  
248 # its fine to always insert a node, even when we have an undef,
249 # because even if we aren't a sub-class, we should assume use
250 # that would then set the entry. This model works well with
251 # sub-classing and reads() that might want to return undef as
252 # a valid value.
253 my $value;
254 if ($self->{subclass}) {
255 $self->print("read() for key $key") if $self->{dbg} > 1;
256 $value = $self->read($key);
257 }
258  
259 if(defined $value) {
260 my $length;
261 if($self->{max_size}) {
262 # check max size of entry, that it not exceed max size
263 $length = &_get_data_length(\$key, \$value);
264 if($length > $self->{max_size}) {
265 $self->print("direct read() [$key, $value]") if ($self->{dbg} > 1);
266 return $value;
267 }
268 }
269 # if we get here, we should insert the new node
270 $node = &create_node($self, \$key, \$value, $length);
271 &insert($self, $node);
272 $value;
273 } else {
274 undef;
275 }
276 }
277 }
278  
279 sub STORE {
280 my($self, $key, $value) = @_;
281 my $node;
282  
283 $self->print("STORE [$key,$value]") if ($self->{dbg} > 1);
284  
285 # do not cache undefined values
286 defined($value) || return(undef);
287  
288 # check max size of entry, that it not exceed max size
289 my $length;
290 if($self->{max_size}) {
291 $length = &_get_data_length(\$key, \$value);
292 if($length > $self->{max_size}) {
293 if ($self->{subclass}) {
294 $self->print("direct write() [$key, $value]") if ($self->{dbg} > 1);
295 $self->write($key, $value);
296 }
297 return $value;
298 }
299 }
300  
301 # do we have node already ?
302 if($self->{nodes}{$key}) {
303 $node = &delete($self, $key);
304 # $node = &delete($self, $key);
305 # $node->[$VALUE] = $value;
306 # $node->[$BYTES] = $length || &_get_data_length(\$key, \$value);
307 }
308  
309 # insert new node
310 $node = &create_node($self, \$key, \$value, $length);
311 # $node ||= &create_node($self, \$key, \$value, $length);
312 &insert($self, $node);
313  
314 # if the data is sync'd call write now, otherwise defer the data
315 # writing, but mark it dirty so it can be cleanup up at the end
316 if ($self->{subclass}) {
317 if($self->{sync}) {
318 $self->print("sync write() [$key, $value]") if $self->{dbg} > 1;
319 $self->write($key, $value);
320 } else {
321 $node->[$DIRTY] = 1;
322 }
323 }
324  
325 $value;
326 }
327  
328 sub DELETE {
329 my($self, $key) = @_;
330  
331 $self->print("DELETE $key") if ($self->{dbg} > 1);
332 my $node = $self->delete($key);
333 $node ? $node->[$VALUE] : undef;
334 }
335  
336 sub CLEAR {
337 my($self) = @_;
338  
339 $self->print("CLEAR CACHE") if ($self->{dbg} > 1);
340  
341 if($self->{subclass}) {
342 my $flushed = $self->flush();
343 $self->print("FLUSH COUNT $flushed") if ($self->{dbg} > 1);
344 }
345  
346 my $node;
347 while($node = $self->{head}) {
348 $self->delete($self->{head}[$KEY]);
349 }
350  
351 1;
352 }
353  
354 sub EXISTS {
355 my($self, $key) = @_;
356 exists $self->{nodes}{$key};
357 }
358
359 # firstkey / nextkey emulate keys() and each() behavior by
360 # taking a snapshot of all the nodes at firstkey, and
361 # iterating through the keys with nextkey
362 #
363 # this method therefore will only supports one each() / keys()
364 # happening during any given time.
365 #
366 sub FIRSTKEY {
367 my($self) = @_;
368  
369 $self->{'keys'} = [];
370 my $node = $self->{head};
371 while($node) {
372 push(@{$self->{'keys'}}, $node->[$KEY]);
373 $node = $node->[$AFTER];
374 }
375  
376 shift @{$self->{'keys'}};
377 }
378  
379 sub NEXTKEY {
380 my($self, $lastkey) = @_;
381 shift @{$self->{'keys'}};
382 }
383  
384 sub DESTROY {
385 my($self) = @_;
386  
387 # if debugging, snapshot cache before clearing
388 if($self->{dbg}) {
389 if($self->{hit} || $self->{miss}) {
390 $self->{hit_ratio} =
391 sprintf("%4.3f", $self->{hit} / ($self->{hit} + $self->{miss}));
392 }
393 $self->print($self->pretty_self());
394 if($self->{dbg} > 1) {
395 $self->print($self->pretty_chains());
396 }
397 }
398
399 $self->print("DESTROYING") if $self->{dbg} > 1;
400 $self->CLEAR();
401
402 1;
403 }
404  
405 ####PERL##LRU##TIE##CACHE##PERL##LRU##TIE##CACHE##PERL##LRU##TIE##CACHE
406 ## Helper Routines
407 ####PERL##LRU##TIE##CACHE##PERL##LRU##TIE##CACHE##PERL##LRU##TIE##CACHE
408  
409 # we use scalar_refs for the data for speed
410 sub create_node {
411 my($self, $key, $value, $length) = @_;
412 (defined($$key) && defined($$value))
413 || die("need more localized data than $$key and $$value");
414
415 # max_size always defined when max_bytes is
416 if (($self->{max_size})) {
417 $length = defined $length ? $length : &_get_data_length($key, $value)
418 } else {
419 $length = 0;
420 }
421
422 # ORDER SPECIFIC, see top for NODE ARRAY STRUCT
423 my $node = [ $$key, $$value, $length ];
424 }
425  
426 sub _get_data_length {
427 my($key, $value) = @_;
428 my $length = 0;
429 my %refs;
430  
431 my @data = ($$key, $$value);
432 while(my $elem = shift @data) {
433 next if $refs{$elem};
434 $refs{$elem} = 1;
435 if(ref $elem && $elem =~ /(SCALAR|HASH|ARRAY)/) {
436 my $type = $1;
437 $length += $REF_SIZE; # guess, 16 bytes per ref, probably more
438 if (($type eq 'SCALAR')) {
439 $length += length($$elem);
440 } elsif (($type eq 'HASH')) {
441 while (my($k,$v) = each %$elem) {
442 for my $kv($k,$v) {
443 if ((ref $kv)) {
444 push(@data, $kv);
445 } else {
446 $length += length($kv);
447 }
448 }
449 }
450 } elsif (($type eq 'ARRAY')) {
451 for my $val (@$elem){
452 if ((ref $val)) {
453 push(@data, $val);
454 } else {
455 $length += length($val);
456 }
457 }
458 }
459 } else {
460 $length += length($elem);
461 }
462 }
463  
464 $length;
465 }
466  
467 sub insert {
468 my($self, $new_node) = @_;
469
470 $new_node->[$AFTER] = 0;
471 $new_node->[$BEFORE] = $self->{tail};
472 $self->print("insert() [$new_node->[$KEY], $new_node->[$VALUE]]") if ($self->{dbg} > 1);
473
474 $self->{nodes}{$new_node->[$KEY]} = $new_node;
475  
476 # current sizes
477 $self->{count}++;
478 $self->{bytes} += $new_node->[$BYTES] + $STRUCT_SIZE;
479  
480 if($self->{tail}) {
481 $self->{tail}[$AFTER] = $new_node;
482 } else {
483 $self->{head} = $new_node;
484 }
485 $self->{tail} = $new_node;
486  
487 ## if we are too big now, remove head
488 while(($self->{max_count} && ($self->{count} > $self->{max_count})) ||
489 ($self->{max_bytes} && ($self->{bytes} > $self->{max_bytes})))
490 {
491 if($self->{dbg} > 1) {
492 $self->print("current/max: ".
493 "bytes ($self->{bytes}/$self->{max_bytes}) ".
494 "count ($self->{count}/$self->{max_count}) "
495 );
496 }
497 my $old_node = $self->delete($self->{head}[$KEY]);
498 if ($self->{subclass}) {
499 if($old_node->[$DIRTY]) {
500 $self->print("dirty write() [$old_node->[$KEY], $old_node->[$VALUE]]")
501 if ($self->{dbg} > 1);
502 $self->write($old_node->[$KEY], $old_node->[$VALUE]);
503 }
504 }
505 # if($self->{dbg} > 1) {
506 # $self->print("after delete - bytes $self->{bytes}; count $self->{count}");
507 # }
508 }
509
510 1;
511 }
512  
513 sub delete {
514 my($self, $key) = @_;
515 my $node = $self->{nodes}{$key} || return;
516 # return unless $node;
517  
518 $self->print("delete() [$key, $node->[$VALUE]]") if ($self->{dbg} > 1);
519  
520 my $before = $node->[$BEFORE];
521 my $after = $node->[$AFTER];
522  
523 # my($before, $after) = $node->{before,after};
524 if($before) {
525 ($before->[$AFTER] = $after);
526 } else {
527 $self->{head} = $after;
528 }
529  
530 if($after) {
531 ($after->[$BEFORE] = $before);
532 } else {
533 $self->{tail} = $before;
534 }
535  
536 delete $self->{nodes}{$key};
537 $self->{bytes} -= ($node->[$BYTES] + $STRUCT_SIZE);
538 $self->{count}--;
539
540 $node;
541 }
542  
543 sub flush {
544 my $self = shift;
545  
546 $self->print("FLUSH CACHE") if ($self->{dbg} > 1);
547  
548 my $node = $self->{head};
549 my $flush_count = 0;
550 while($node) {
551 if($node->[$DIRTY]) {
552 $self->print("flush dirty write() [$node->[$KEY], $node->[$VALUE]]")
553 if ($self->{dbg} > 1);
554 $self->write($node->[$KEY], $node->[$VALUE]);
555 $node->[$DIRTY] = 0;
556 $flush_count++;
557 }
558 $node = $node->[$AFTER];
559 }
560  
561 $flush_count;
562 }
563  
564 sub print {
565 my($self, $msg) = @_;
566 print "$self: $msg\n";
567 }
568  
569 sub pretty_self {
570 my($self) = @_;
571
572 my(@prints);
573 for(sort keys %{$self}) {
574 next unless defined $self->{$_};
575 push(@prints, "$_=>$self->{$_}");
576 }
577  
578 "{ " . join(", ", @prints) . " }";
579 }
580  
581 sub pretty_chains {
582 my($self) = @_;
583 my($str);
584 my $k = $self->FIRSTKEY();
585  
586 $str .= "[head]->";
587 my($curr_node) = $self->{head};
588 while($curr_node) {
589 $str .= "[$curr_node->[$KEY],$curr_node->[$VALUE]]->";
590 $curr_node = $curr_node->[$AFTER];
591 }
592 $str .= "[tail]->";
593  
594 $curr_node = $self->{tail};
595 while($curr_node) {
596 $str .= "[$curr_node->[$KEY],$curr_node->[$VALUE]]->";
597 $curr_node = $curr_node->[$BEFORE];
598 }
599 $str .= "[head]";
600  
601 $str;
602 }
603  
604 1;
605  
606 __END__