blib/lib/Cache/FastMmap.pm

filter: Statementstmt 88.9% 377 / 424 Branchbran 70.7% 222 / 314 Conditioncond 70.7% 104 / 147 MC/DCmcdc 54.2% 45 / 83 Subroutinesub 82.5% 33 / 40 Podpod 84.2% 16 / 19 totaltotal 77.6% 797 / 1027 CC 219 SCAR 39.0
CC
219
Cov
79%
new
186.9
get
32.6
set
26.2
CRAP 49.6
↑ Summary unix.c »
1 package Cache::FastMmap;
2  
3 =head1 NAME
4  
5 Cache::FastMmap - Uses an mmap'ed file to act as a shared memory interprocess cache
6  
7 =head1 SYNOPSIS
8  
9 use Cache::FastMmap;
10  
11 # Uses vaguely sane defaults
12 $Cache = Cache::FastMmap->new();
13  
14 # Uses Storable to serialize $Value to bytes for storage
15 $Cache->set($Key, $Value);
16 $Value = $Cache->get($Key);
17  
18 $Cache = Cache::FastMmap->new(serializer => '');
19  
20 # Stores stringified bytes of $Value directly
21 $Cache->set($Key, $Value);
22 $Value = $Cache->get($Key);
23  
24 =head1 ABSTRACT
25  
26 A shared memory cache through an mmap'ed file. It's core is written
27 in C for performance. It uses fcntl locking to ensure multiple
28 processes can safely access the cache at the same time. It uses
29 a basic LRU algorithm to keep the most used entries in the cache.
30  
31 =head1 DESCRIPTION
32  
33 In multi-process environments (eg mod_perl, forking daemons, etc),
34 it's common to want to cache information, but have that cache
35 shared between processes. Many solutions already exist, and may
36 suit your situation better:
37  
38 =over 4
39  
40 =item *
41  
42 L<MLDBM::Sync> - acts as a database, data is not automatically
43 expired, slow
44  
45 =item *
46  
47 L<IPC::MM> - hash implementation is broken, data is not automatically
48 expired, slow
49  
50 =item *
51  
52 L<Cache::FileCache> - lots of features, slow
53  
54 =item *
55  
56 L<Cache::SharedMemoryCache> - lots of features, VERY slow. Uses
57 IPC::ShareLite which freeze/thaws ALL data at each read/write
58  
59 =item *
60  
61 L<DBI> - use your favourite RDBMS. can perform well, need a
62 DB server running. very global. socket connection latency
63  
64 =item *
65  
66 L<Cache::Mmap> - similar to this module, in pure perl. slows down
67 with larger pages
68  
69 =item *
70  
71 L<BerkeleyDB> - very fast (data ends up mostly in shared memory
72 cache) but acts as a database overall, so data is not automatically
73 expired
74  
75 =back
76  
77 In the case I was working on, I needed:
78  
79 =over 4
80  
81 =item *
82  
83 Automatic expiry and space management
84  
85 =item *
86  
87 Very fast access to lots of small items
88  
89 =item *
90  
91 The ability to fetch/store many items in one go
92  
93 =back
94  
95 Which is why I developed this module. It tries to be quite
96 efficient through a number of means:
97  
98 =over 4
99  
100 =item *
101  
102 Core code is written in C for performance
103  
104 =item *
105  
106 It uses multiple pages within a file, and uses Fcntl to only lock
107 a page at a time to reduce contention when multiple processes access
108 the cache.
109  
110 =item *
111  
112 It uses a dual level hashing system (hash to find page, then hash
113 within each page to find a slot) to make most C<get()> calls O(1) and
114 fast
115  
116 =item *
117  
118 On each C<set()>, if there are slots and page space available, only
119 the slot has to be updated and the data written at the end of the used
120 data space. If either runs out, a re-organisation of the page is
121 performed to create new slots/space which is done in an efficient way
122  
123 =back
124  
125 The class also supports read-through, and write-back or write-through
126 callbacks to access the real data if it's not in the cache, meaning that
127 code like this:
128  
129 my $Value = $Cache->get($Key);
130 if (!defined $Value) {
131 $Value = $RealDataSource->get($Key);
132 $Cache->set($Key, $Value)
133 }
134  
135 Isn't required, you instead specify in the constructor:
136  
137 Cache::FastMmap->new(
138 ...
139 context => $RealDataSourceHandle,
140 read_cb => sub { $_[0]->get($_[1]) },
141 write_cb => sub { $_[0]->set($_[1], $_[2]) },
142 );
143  
144 And then:
145  
146 my $Value = $Cache->get($Key);
147  
148 $Cache->set($Key, $NewValue);
149  
150 Will just work and will be read/written to the underlying data source as
151 needed automatically.
152  
153 =head1 PERFORMANCE
154  
155 If you're storing relatively large and complex structures into
156 the cache, then you're limited by the speed of the Storable module.
157 If you're storing simple structures, or raw data, then
158 Cache::FastMmap has noticeable performance improvements.
159  
160 See L<http://cpan.robm.fastmail.fm/cache_perf.html> for some
161 comparisons to other modules.
162  
163 =head1 COMPATIBILITY
164  
165 Cache::FastMmap uses mmap to map a file as the shared cache space,
166 and fcntl to do page locking. This means it should work on most
167 UNIX like operating systems.
168  
169 Ash Berlin has written a Win32 layer using MapViewOfFile et al. to
170 provide support for Win32 platform.
171  
172 =head1 MEMORY SIZE
173  
174 Because Cache::FastMmap mmap's a shared file into your processes memory
175 space, this can make each process look quite large, even though it's just
176 mmap'd memory that's shared between all processes that use the cache,
177 and may even be swapped out if the cache is getting low usage.
178  
179 However, the OS will think your process is quite large, which might
180 mean you hit some BSD::Resource or 'ulimits' you set previously that you
181 thought were sane, but aren't anymore, so be aware.
182  
183 =head1 CACHE FILES AND OS ISSUES
184  
185 Because Cache::FastMmap uses an mmap'ed file, when you put values into
186 the cache, you are actually "dirtying" pages in memory that belong to
187 the cache file. Your OS will want to write those dirty pages back to
188 the file on the actual physical disk, but the rate it does that at is
189 very OS dependent.
190  
191 In most cases, people are not actually concerned about the persistence
192 of data in the cache, and so are happy to disable writing of any cache
193 data back to disk at all. Baically what they want is an in memory only
194 shared cache. The best way to do that is to use a "tmpfs" filesystem
195 and put all cache files on there.
196  
197 For instance, all our machines have a /tmpfs mount point that we
198 create in /etc/fstab as:
199  
200 none /tmpfs tmpfs defaults,noatime,size=1000M 0 0
201  
202 And we put all our cache files on there. The tmpfs filesystem is smart
203 enough to only use memory as required by files actually on the tmpfs,
204 so making it 1G in size doesn't actually use 1G of memory, it only uses
205 as much as the cache files we put on it. In all cases, we ensure that
206 we never run out of real memory, so the cache files effectively act
207 just as named access points to shared memory.
208  
209 If you do put the cache file on a filesystem backed by a real disk,
210 in Linux you have some control over how the OS writes those pages
211 back using a number of parameters in /proc/sys/vm
212  
213 dirty_background_ratio
214 dirty_expire_centisecs
215 dirty_ratio
216 dirty_writeback_centisecs
217  
218 How you tune these depends heavily on your setup.
219  
220 Some people have suggested using anonymous mmaped memory. Unfortunately
221 we need a file descriptor to do the fcntl locking on, so we'd have
222 to create a separate file on a filesystem somewhere anyway. It seems
223 easier to just create an explicit "tmpfs" filesystem.
224  
225 =head1 PAGE SIZE AND KEY/VALUE LIMITS
226  
227 To reduce lock contention, Cache::FastMmap breaks up the file
228 into pages. When you get/set a value, it hashes the key to get a page,
229 then locks that page, and uses a hash table within the page to
230 get/store the actual key/value pair.
231  
232 One consequence of this is that you cannot store values larger than
233 a page in the cache at all. Attempting to store values larger than
234 a page size will fail (the set() function will return false).
235  
236 Also keep in mind that each page has it's own hash table, and that we
237 store the key and value data of each item. So if you are expecting to
238 store large values and/or keys in the cache, you should use page sizes
239 that are definitely larger than your largest key + value size + a few
240 kbytes for the overhead.
241  
242 =head1 USAGE
243  
244 Because the cache uses shared memory through an mmap'd file, you have
245 to make sure each process connects up to the file. There's probably
246 two main ways to do this:
247  
248 =over 4
249  
250 =item *
251  
252 Create the cache in the parent process, and then when it forks, each
253 child will inherit the same file descriptor, mmap'ed memory, etc and
254 just work. This is the recommended way. (BEWARE: This only works under
255 UNIX as Win32 has no concept of forking)
256  
257 =item *
258  
259 Explicitly connect up in each forked child to the share file. In this
260 case, make sure the file already exists and the children connect with
261 init_file => 0 to avoid deleting the cache contents. Also be careful
262 that multiple children may race to create the file at the same time,
263 each overwriting and corrupting content. Use a separate lock file if
264 you must to ensure only one child creates the file. (This is the only
265 possible way under Win32)
266  
267 =back
268  
269 The first way is usually the easiest. If you're using the cache in a
270 Net::Server based module, you'll want to open the cache in the
271 C<pre_loop_hook>, because that's executed before the fork, but after
272 the process ownership has changed and any chroot has been done.
273  
274 In mod_perl, just open the cache at the global level in the appropriate
275 module, which is executed as the server is starting and before it
276 starts forking children, but you'll probably want to chmod or chown
277 the file to the permissions of the apache process.
278  
279 =head1 RELIABILITY
280  
281 Cache::FastMmap is being used in an extensive number of systems at
282 L<www.fastmail.com> and is regarded as extremely stable and reliable.
283 Development has in general slowed because there are currently no
284 known bugs and no additional needed features at this time.
285  
286 =head1 KILLED WRITERS AND PAGE REPAIR
287  
288 Every update to a page (set, remove, expunge, and the header write at
289 unlock) happens while the process holds that page's fcntl lock, but
290 the update itself is a series of ordinary stores into the mmap'ed
291 file, so a process killed with SIGKILL (or dying of a segfault, or
292 losing power to the box, if the file isn't on tmpfs) part way through
293 leaves the page structurally inconsistent. The kernel releases its
294 lock, the next process to lock the page trusts what it finds, and with
295 bad slot offsets or lengths that used to mean a crash.
296  
297 Since 1.64 the page's start marker doubles as an in-progress flag. A
298 process clears the marker's low bit before it changes any structure on
299 the page and sets it again just before unlocking. A process that
300 acquires the lock and finds the bit still clear knows the previous
301 holder died mid-update; it reinitialises the page (all entries on it
302 are lost, which for a cache is a miss) and carries on. Slot offsets
303 and entry lengths are also checked against the page bounds whenever
304 they are followed, and a page that fails is treated as a miss and
305 reinitialised at unlock, so a page corrupted by something else (an
306 older module version killed mid-update, say) can't crash the process
307 either.
308  
309 Each repair is reported with C<warn>, naming the page, the file and
310 the reason, so it can be logged and looked into; C<repaired_pages()>
311 gives the count for this process. Repairs should be rare. If they are
312 not, something is killing processes while they hold a page lock, and
313 that, rather than the cache, is what needs fixing.
314  
315 The marker's two values are the old magic value and one differing in
316 the low bit, so files are compatible in both directions. An older
317 module version that locks a page a 1.64 process is mid-update on (only
318 possible if that process was killed) fails with "magic page start
319 marker not found" instead of reading the inconsistent page, which is
320 the safer outcome; a 1.64 process finds and repairs a page an older
321 version was killed on if a bounds check catches it, but a header
322 inconsistency left by an older version is only caught by the header
323 checks at lock time.
324  
325 =head1 TOMBSTONES AND MODSEQS
326  
327 These features close a stale write-back race in cache invalidation.
328 The race: process A reads a value from the cache and is using it when
329 an invalidation arrives (some other process changed the underlying
330 data and called remove()). If A now stores its in-memory copy back -
331 explicitly, or via a read-compute-store pattern that raced the
332 invalidation - the out of date value is re-cached, and no further
333 invalidation is coming.
334  
335 The fix is to give changes a monotonically increasing 64 bit sequence
336 number (a "modseq") and make invalidation leave a marker instead of
337 just deleting:
338  
339 =over 4
340  
341 =item *
342  
343 C<< $fc->remove($Key, { modseq => $ModSeq }) >> deletes the value but
344 leaves a B<tombstone> recording the modseq of the invalidating change.
345 get()/exists() treat tombstones as misses. A tombstone never has its
346 modseq lowered by a remove with an older modseq.
347  
348 =item *
349  
350 C<< $fc->set($Key, $Value, { modseq => $ModSeq }) >> is a
351 B<conditional store>: it's refused (returning false) if the key holds
352 a tombstone with a newer modseq, or a live value with a newer modseq.
353 Otherwise the value is stored with its modseq (readable back via
354 C<< get($Key, { modseq => \my $ms }) >>).
355  
356 =item *
357  
358 A plain set() with no modseq is refused by I<any> tombstone. This is
359 what you want for values computed from several underlying sources
360 whose modseqs aren't mutually comparable: they can't prove freshness,
361 so any pending invalidation blocks re-caching until the tombstone
362 expires. The checks happen inside the existing slot lookup in the C
363 layer, so none of this costs anything extra per operation.
364  
365 =back
366  
367 Tombstones expire like normal entries (see C<tombstone_expire_time>)
368 and can be evicted under LRU pressure, in which case behaviour
369 degrades to plain delete semantics - so they need only be trusted as
370 an optimisation window, sized to cover in-flight requests. A plain
371 remove() with no modseq deletes tombstones like any other entry.
372  
373 Internally a tombstone is an entry flag plus an 8 byte packed modseq
374 in the value area, and a live value with a modseq carries it as an 8
375 byte prefix, all managed by the C layer - the cache file format is
376 unchanged, but older versions of this module will misread I<entries
377 that use these features>, so upgrade all processes sharing a cache
378 file before writing any.
379  
380 =head1 METHODS
381  
382 =over 4
383  
384 =cut
385  
386 # Modules/Export/XSLoader {{{
387 25 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
388 25 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
389 25 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
390 25 ▶use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
391  
392 25 our $VERSION = '1.64';
393  
394 25 require XSLoader;
395 25 XSLoader::load('Cache::FastMmap', $VERSION);
396  
397 # Track currently live caches so we can cleanup in END {}
398 # if we have empty_on_exit set
399 25 our %LiveCaches;
400  
401 # Global time override for testing
402 25 my $time_override;
403  
404 25 ▶use constant FC_ISDIRTY => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
405  
406 25 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
407  
408 # }}}
409  
410 =item I<new(%Opts)>
411  
412 Create a new Cache::FastMmap object.
413  
414 Basic global parameters are:
415  
416 =over 4
417  
418 =item * B<share_file>
419  
420 File to mmap for sharing of data.
421 default on unix: /tmp/sharefile-$pid-$time-$random
422 default on windows: %TEMP%\sharefile-$pid-$time-$random
423  
424 =item * B<init_file>
425  
426 Clear any existing values and re-initialise file. Useful to do in a
427 parent that forks off children to ensure that file is empty at the start
428 (default: 0)
429  
430 B<Note:> Since 1.64 a page left half-updated by a killed process is
431 detected and reinitialised by the next process to lock it (see
432 L</KILLED WRITERS AND PAGE REPAIR>), so init_file is no longer needed
433 for safety, only when you want to start from an empty cache. Before
434 1.64 a killed writer could leave the file in a state that crashed
435 later readers, and init_file in the parent was the only protection.
436  
437 =item * B<serializer>
438  
439 Use a serialization library to serialize perl data structures before
440 storing in the cache. If not set, the raw value in the variable passed
441 to set() is stored as a string. You must set this if you want to store
442 anything other than basic scalar values. Supported values are:
443  
444 '' for none
445 'storable' for 'Storable'
446 'sereal' for 'Sereal'
447 'json' for 'JSON'
448 [ $s, $d ] for custom serializer/de-serializer
449  
450 If this parameter has a value the module will attempt to load the
451 associated package and then use the API of that package to serialize data
452 before storing in the cache, and deserialize it upon retrieval from the
453 cache. (default: 'storable')
454  
455 You can use a custom serializer/de-serializer by passing an array-ref
456 with two values. The first should be a subroutine reference that takes
457 the data to serialize as a single argument and returns an octet stream
458 to store. The second should be a subroutine reference that takes the
459 octet stream as a single argument and returns the original data structure.
460  
461 One thing to note, the data structure passed to the serializer is always
462 a *scalar* reference to the original data passed in to the ->set(...)
463 call. If your serializer doesn't support that, you might need to
464 dereference it first before storing, but rembember to return a reference
465 again in the de-serializer.
466  
467 (Note: Historically this module only supported a boolean value for the
468 `raw_values` parameter and defaulted to 0, which meant it used Storable
469 to serialze all values.)
470  
471 =item * B<raw_values>
472  
473 Deprecated. Use B<serializer> above
474  
475 =item * B<compressor>
476  
477 Compress the value (but not the key) before storing into the cache, using
478 the compression package identified by the value of the parameter. Supported
479 values are:
480  
481 'zlib' for 'Compress::Zlib'
482 'lz4' for 'Compress::LZ4'
483 'snappy' for 'Compress::Snappy'
484 [ $c, $d ] for custom compressor/de-compressor
485  
486 If this parameter has a value the module will attempt to load the
487 associated package and then use the API of that package to compress data
488 before storing in the cache, and uncompress it upon retrieval from the
489 cache. (default: undef)
490  
491 You can use a custom compressor/de-compressor by passing an array-ref
492 with two values. The first should be a subroutine reference that takes
493 the data to compress as a single octet stream argument and returns an
494 octet stream to store. The second should be a subroutine reference that
495 takes the compressed octet stream as a single argument and returns the
496 original uncompressed data.
497  
498 (Note: Historically this module only supported a boolean value for the
499 `compress` parameter and defaulted to use Compress::Zlib. The note for the
500 old `compress` parameter stated: "Some initial testing shows that the
501 uncompressing tends to be very fast, though the compressing can be quite
502 slow, so it's probably best to use this option only if you know values in
503 the cache are long-lived and have a high hit rate."
504  
505 Comparable test results for the other compression tools are not yet available;
506 submission of benchmarks welcome. However, the documentation for the 'Snappy'
507 library (http://google.github.io/snappy/) states: For instance, compared to
508 the fastest mode of zlib, Snappy is an order of magnitude faster for most
509 inputs, but the resulting compressed files are anywhere from 20% to 100%
510 bigger. )
511  
512 =item * B<compress>
513  
514 Deprecated. Please use B<compressor>, see above.
515  
516 =item * B<enable_stats>
517  
518 Enable some basic statistics capturing. When enabled, every read to
519 the cache is counted, and every read to the cache that finds a value
520 in the cache is also counted. You can then retrieve these values
521 via the get_statistics() call. This causes every read action to
522 do a write on a page, which can cause some more IO, so it's
523 disabled by default. (default: 0)
524  
525 =item * B<expire_time>
526  
527 Maximum time to hold values in the cache in seconds. A value of 0
528 means does no explicit expiry time, and values are expired only based
529 on LRU usage. Can be expressed as 1m, 1h, 1d for minutes/hours/days
530 respectively. (default: 0)
531  
532 =item * B<tombstone_expire_time>
533  
534 Default expiry time for tombstones written by remove() with a modseq,
535 in the same format as expire_time. Tombstones only need to outlive
536 in-flight users of the old value, so this is typically short (e.g.
537 '1m'). If 0/unset, tombstones use the cache's default expire_time.
538 (default: 0)
539  
540 =back
541  
542 You may specify the cache size as:
543  
544 =over 4
545  
546 =item * B<cache_size>
547  
548 Size of cache. Can be expresses as 1k, 1m for kilobytes or megabytes
549 respectively. Automatically guesses page size/page count values.
550  
551 =back
552  
553 Or specify explicit page size/page count values. If none of these are
554 specified, the values page_size = 64k and num_pages = 89 are used.
555  
556 =over 4
557  
558 =item * B<page_size>
559  
560 Size of each page. Must be a power of 2 between 4k and 1024k. If not,
561 is rounded to the nearest value.
562  
563 =item * B<num_pages>
564  
565 Number of pages. Should be a prime number for best hashing
566  
567 =back
568  
569 The cache allows the use of callbacks for reading/writing data to an
570 underlying data store.
571  
572 =over 4
573  
574 =item * B<context>
575  
576 Opaque reference passed as the first parameter to any callback function
577 if specified
578  
579 =item * B<read_cb>
580  
581 Callback to read data from the underlying data store. Called as:
582  
583 $read_cb->($context, $Key)
584
585 Should return the value to use. This value will be saved in the cache
586 for future retrievals. Return undef if there is no value for the
587 given key
588  
589 =item * B<write_cb>
590  
591 Callback to write data to the underlying data store.
592 Called as:
593  
594 $write_cb->($context, $Key, $Value, $ExpiryTime)
595
596 In 'write_through' mode, it's always called as soon as a I<set(...)>
597 is called on the Cache::FastMmap class. In 'write_back' mode, it's
598 called when a value is expunged from the cache if it's been changed
599 by a I<set(...)> rather than read from the underlying store with the
600 I<read_cb> above.
601  
602 Note: Expired items do result in the I<write_cb> being
603 called if 'write_back' caching is enabled and the item has been
604 changed. You can check the $ExpiryTime against C<time()> if you only
605 want to write back values which aren't expired.
606  
607 Also remember that I<write_cb> may be called in a different process
608 to the one that placed the data in the cache in the first place
609  
610 =item * B<delete_cb>
611  
612 Callback to delete data from the underlying data store. Called as:
613  
614 $delete_cb->($context, $Key)
615  
616 Called as soon as I<remove(...)> is called on the Cache::FastMmap class
617  
618 =item * B<cache_not_found>
619  
620 If set to true, then if the I<read_cb> is called and it returns
621 undef to say nothing was found, then that information is stored
622 in the cache, so that next time a I<get(...)> is called on that
623 key, undef is returned immediately rather than again calling
624 the I<read_cb>
625  
626 =item * B<write_action>
627  
628 Either 'write_back' or 'write_through'. (default: write_through)
629  
630 =item * B<allow_recursive>
631  
632 If you're using a callback function, then normally the cache is not
633 re-enterable, and attempting to call a get/set on the cache will
634 cause an error. By setting this to one, the cache will unlock any
635 pages before calling the callback. During the unlock time, other
636 processes may change data in current cache page, causing possible
637 unexpected effects. You shouldn't set this unless you know you
638 want to be able to recall to the cache within a callback.
639 (default: 0)
640  
641 =item * B<empty_on_exit>
642  
643 When you have 'write_back' mode enabled, then
644 you really want to make sure all values from the cache are expunged
645 when your program exits so any changes are written back.
646  
647 The trick is that we only want to do this in the parent process,
648 we don't want any child processes to empty the cache when they exit.
649 So if you set this, it takes the PID via $$, and only calls
650 empty in the DESTROY method if $$ matches the pid we captured
651 at the start. (default: 0)
652  
653 =item * B<unlink_on_exit>
654  
655 Unlink the share file when the cache is destroyed.
656  
657 As with empty_on_exit, this will only unlink the file if the
658 DESTROY occurs in the same PID that the cache was created in
659 so that any forked children don't unlink the file.
660  
661 This value defaults to 1 if the share_file specified does
662 not already exist. If the share_file specified does already
663 exist, it defaults to 0.
664  
665 =item * B<catch_deadlocks>
666  
667 Sets an alarm(10) before each page is locked via fcntl(F_SETLKW) to catch
668 any deadlock. This used to be the default behaviour, but it's not really
669 needed in the default case and could clobber sub-second Time::HiRes
670 alarms setup by other code. Defaults to 0.
671  
672 =back
673  
674 =cut
675 sub new {
676 8068 ▶ my $Proto = shift;
Subroutine new: called CC=51 SCAR=52.3
Pod documented
677 8068 ▶ my $Class = ref($Proto) || $Proto;
Condition33%1/3
ref $Proto || $Proto
l!l&&r!l&&!r
080680
MC/DC0%0/2
ref $Proto || $Proto
ref $Proto $Proto
Truth table33%1/3
A || B
A= ref $ProtoB= $Proto
ABresult
1X1
011
000
678  
679 # If first item is a hash ref, use it as arguments
680 8068 ▶ my %Args = ref($_[0]) eq 'HASH' ? %{shift()} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 8068 8068
681  
682 8068 my $Self = {};
683 8068 bless ($Self, $Class);
684  
685 # Work out cache file and whether to init
686 8068 my $share_file = $Args{share_file};
687 8068 ▶ if (!$share_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($share_file) 8068 0 8068
688 8068 my $tmp_dir = File::Spec->tmpdir;
689 8068 $share_file = File::Spec->catfile($tmp_dir, "sharefile");
690 8068 $share_file .= "-" . $$ . "-" . time . "-" . int(rand(100000));
691 }
692 8068 ▶ !ref($share_file) || die "share_file argument was a reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $share_file and die "share_file argument was a reference" 0 8068 8068
693 8068 $Self->{share_file} = $share_file;
694 8068 my $permissions = $Args{permissions};
695  
696 8068 ▶ my $init_file = $Args{init_file} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Args{'init_file'} ? : 4066 4002 8068
697 8068 ▶ my $test_file = $Args{test_file} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Args{'test_file'} ? : 0 8068 8068
698 8068 ▶ my $enable_stats = $Args{enable_stats} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Args{'enable_stats'} ? : 1 8067 8068
699 8068 ▶ my $catch_deadlocks = $Args{catch_deadlocks} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Args{'catch_deadlocks'} ? : 0 8068 8068
700  
701 # Worth out unlink default if not specified
702 8068 ▶ if (!exists $Args{unlink_on_exit}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $Args{"unlink_on_exit"}) 8068 0 8068
703 8068 ▶ $Args{unlink_on_exit} = -f($share_file) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
-f $share_file ? : 0 8068 8068
704 }
705  
706 # Serialise stored values?
707 8068 my $serializer = $Args{serializer};
708 8068 ▶ $serializer = ($Args{raw_values} ? '' : 'storable') if !defined $serializer;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $serializer 10 8058 8068
$Args{'raw_values'} ? : 0 10 10
709  
710 8068 ▶ if ($serializer) {
Branch: 1 branch
BranchTrueFalseTotal
if ($serializer) 14 8054 8068
711 14 ▶ if (ref $serializer eq 'ARRAY') {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $serializer eq 'ARRAY') { } 4 10 14
elsif ($serializer eq 'storable') { } 10 0 10
elsif ($serializer eq 'sereal') { } 0 0 0
elsif ($serializer eq 'json') { } 0 0 0
712 4 $Self->{serialize} = $serializer->[0];
713 4 $Self->{deserialize} = $serializer->[1];
714 } elsif ($serializer eq 'storable') {
715 10 ▶ eval "require Storable;"
Branch: 1 branch
BranchTrueFalseTotal
eval "require Storable;" or die "Could not load serialization package: Storable : $@" 0 10 10
716 || die "Could not load serialization package: Storable : $@";
717 10 $Self->{serialize} = Storable->can("freeze");
718 10 $Self->{deserialize} = Storable->can("thaw");
719 } elsif ($serializer eq 'sereal') {
720 0 ▶ eval "require Sereal::Encoder; require Sereal::Decoder;"
Branch: 1 branch
BranchTrueFalseTotal
eval "require Sereal::Encoder; require Sereal::Decoder;" or die "Could not load serialization package: Sereal : $@" 0 0 0
721 || die "Could not load serialization package: Sereal : $@";
722 0 my $SerealEnc = Sereal::Encoder->new();
723 0 my $SerealDec = Sereal::Decoder->new();
724 0 ▶ $Self->{serialize} = sub { $SerealEnc->encode(@_); };
Subroutine __ANON__: not called CC=1 SCAR=6.9
725 0 ▶ $Self->{deserialize} = sub { $SerealDec->decode(@_); };
Subroutine __ANON__: not called CC=1 SCAR=6.9
726 } elsif ($serializer eq 'json') {
727 0 ▶ eval "require JSON;"
Branch: 1 branch
BranchTrueFalseTotal
eval "require JSON;" or die "Could not load serialization package: JSON : $@" 0 0 0
728 || die "Could not load serialization package: JSON : $@";
729 0 my $JSON = JSON->new->utf8->allow_nonref;
730 0 ▶ $Self->{serialize} = sub { $JSON->encode(${$_[0]}); };
Subroutine __ANON__: not called CC=1 SCAR=6.9
731 0 ▶ $Self->{deserialize} = sub { \$JSON->decode($_[0]); };
Subroutine __ANON__: not called CC=1 SCAR=6.9
732 } else {
733 0 die "Unrecognized value >$serializer< for `serializer` parameter";
734 }
735 }
736  
737 # Compress stored values?
738 8068 my $compressor = $Args{compressor};
739 8068 ▶ $compressor = ($Args{compress} ? 'zlib' : 0) if !defined $compressor;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $compressor 8067 1 8068
$Args{'compress'} ? : 3 8064 8067
740  
741 8068 my %known_compressors = (
742 zlib => 'Compress::Zlib',
743 lz4 => 'Compress::LZ4',
744 snappy => 'Compress::Snappy',
745 );
746  
747 8068 ▶ if ( $compressor ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($compressor) 4 8064 8068
748 4 ▶ if (ref $compressor eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $compressor eq 'ARRAY') { } 0 4 4
elsif (my $compressor_module = $known_compressors{$compressor}) { } 4 0 4
749 0 $Self->{compress} = $compressor->[0];
750 0 $Self->{uncompress} = $compressor->[1];
751 } elsif (my $compressor_module = $known_compressors{$compressor}) {
752 4 ▶ eval "require $compressor_module;"
Branch: 1 branch
BranchTrueFalseTotal
eval "require $compressor_module;" or die "Could not load compression package: $compressor_module : $@" 0 4 4
753 || die "Could not load compression package: $compressor_module : $@";
754  
755 # LZ4 and Snappy use same API
756 4 ▶ if ($compressor_module eq 'Compress::LZ4' || $compressor_module eq 'Compress::Snappy') {
Branch: 2 branches
BranchTrueFalseTotal
if ($compressor_module eq 'Compress::LZ4' or $compressor_module eq 'Compress::Snappy') { } 0 4 4
elsif ($compressor_module eq 'Compress::Zlib') { } 4 0 4
Condition33%1/3
$compressor_module eq "Compress::LZ4" or $compressor_module eq "Compress::Snappy"
l!l&&r!l&&!r
004
MC/DC0%0/2
$compressor_module eq "Compress::LZ4" or $compressor_module eq "Compress::Snappy"
$compressor_module eq "Compress::LZ4" $compressor_module eq "Compress::Snappy"
Truth table33%1/3
A or B
A= $compressor_module eq "Compress::LZ4"B= $compressor_module eq "Compress::Snappy"
ABresult
1X1
011
000
757 0 $Self->{compress} = $compressor_module->can("compress");
758 0 $Self->{uncompress} = $compressor_module->can("uncompress");
759 } elsif ($compressor_module eq 'Compress::Zlib') {
760 4 $Self->{compress} = $compressor_module->can("memGzip");
761 # (gunzip from tmp var: https://rt.cpan.org/Ticket/Display.html?id=72945)
762 4 my $uncompress = $compressor_module->can("memGunzip");
763 4 ▶ $Self->{uncompress} = sub { &$uncompress(my $Tmp = shift) };
Subroutine __ANON__: called CC=1 SCAR=0.0
764 }
765 } else {
766 0 die "Unrecognized value >$compressor< for `compressor` parameter";
767 }
768 }
769  
770 # If using empty_on_exit, need to track used caches
771 8068 ▶ my $empty_on_exit = $Self->{empty_on_exit} = int($Args{empty_on_exit} || 0);
Condition100%2/2
$Args{'empty_on_exit'} || 0
l!l
38065
MC/DC100%1/1
$Args{'empty_on_exit'} || 0
$Args{'empty_on_exit'}
Truth table100%2/2
A
A= $Args{'empty_on_exit'}
Aresult
11
00
772  
773 # Need Scalar::Util::weaken to track open caches
774 8068 ▶ if ($empty_on_exit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($empty_on_exit) 3 8065 8068
775 3 ▶ eval "use Scalar::Util qw(weaken); 1;"
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
eval "use Scalar::Util qw(weaken); 1;" or die "Could not load Scalar::Util module: $@" 0 3 3
776 || die "Could not load Scalar::Util module: $@";
777 }
778  
779 # Work out expiry time in seconds
780 8068 my $expire_time = $Self->{expire_time} = parse_expire_time($Args{expire_time});
781  
782 # Default expiry for tombstones left by remove() with a modseq (see
783 # TOMBSTONES AND MODSEQS)
784 8068 $Self->{tombstone_expire_time} = parse_expire_time($Args{tombstone_expire_time});
785  
786 # Function rounds to the nearest power of 2
787 8068 ▶ sub RoundPow2 { return int(2 ** int(log($_[0])/log(2)) + 0.1); }
Subroutine RoundPow2: called CC=1 SCAR=0.0
Pod undocumented
788  
789 # Work out cache size
790 8068 my ($cache_size, $num_pages, $page_size);
791  
792 8068 my %Sizes = (k => 1024, m => 1024*1024);
793 8068 ▶ if ($cache_size = $Args{cache_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache_size = $Args{'cache_size'}) { } 0 8068 8068
794 0 ▶ $cache_size *= $Sizes{lc($1)} if $cache_size =~ s/([km])$//i;
Branch: 1 branch
BranchTrueFalseTotal
if $cache_size =~ s/([km])$//i 0 0 0
795  
796 0 ▶ if ($num_pages = $Args{num_pages}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num_pages = $Args{'num_pages'}) { } 0 0 0
797 0 $page_size = RoundPow2($cache_size / $num_pages);
798 0 ▶ $page_size = 4096 if $page_size < 4096;
Branch: 1 branch
BranchTrueFalseTotal
if $page_size < 4096 0 0 0
799  
800 } else {
801 0 ▶ $page_size = $Args{page_size} || 65536;
Condition0%0/2
$Args{'page_size'} || 65536
l!l
00
MC/DC0%0/1
$Args{'page_size'} || 65536
$Args{'page_size'}
Truth table0%0/2
A
A= $Args{'page_size'}
Aresult
11
00
802 0 ▶ $page_size *= $Sizes{lc($1)} if $page_size =~ s/([km])$//i;
Branch: 1 branch
BranchTrueFalseTotal
if $page_size =~ s/([km])$//i 0 0 0
803 0 ▶ $page_size = 4096 if $page_size < 4096;
Branch: 1 branch
BranchTrueFalseTotal
if $page_size < 4096 0 0 0
804  
805 # Increase num_pages till we exceed
806 0 $num_pages = 89;
807 0 ▶ if ($num_pages * $page_size <= $cache_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num_pages * $page_size <= $cache_size) { } 0 0 0
808 0 ▶ while ($num_pages * $page_size <= $cache_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num_pages * $page_size <= $cache_size) 0 0 0
809 0 $num_pages = $num_pages * 2 + 1;
810 }
811 } else {
812 0 ▶ while ($num_pages * $page_size > $cache_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num_pages * $page_size > $cache_size) 0 0 0
813 0 $num_pages = int(($num_pages-1) / 2);
814 }
815 0 $num_pages = $num_pages * 2 + 1;
816 }
817  
818 }
819  
820 } else {
821 8068 ($num_pages, $page_size) = @Args{qw(num_pages page_size)};
822 8068 ▶ $num_pages ||= 89;
Condition100%2/2
$num_pages ||= 89
l!l
804325
MC/DC100%1/1
$num_pages ||= 89
$num_pages
Truth table100%2/2
A
A= $num_pages
Aresult
11
00
823 8068 ▶ $page_size ||= 65536;
Condition100%2/2
$page_size ||= 65536
l!l
804424
MC/DC100%1/1
$page_size ||= 65536
$page_size
Truth table100%2/2
A
A= $page_size
Aresult
11
00
824 8068 ▶ $page_size *= $Sizes{lc($1)} if $page_size =~ s/([km])$//i;
Branch: 1 branch
BranchTrueFalseTotal
if $page_size =~ s/([km])$//i 0 8068 8068
825 8068 $page_size = RoundPow2($page_size);
826 }
827  
828 8068 $cache_size = $num_pages * $page_size;
829 8068 @$Self{qw(cache_size num_pages page_size)}
830 = ($cache_size, $num_pages, $page_size);
831  
832 # Number of slots to start in each page
833 8068 ▶ my $start_slots = int($Args{start_slots} || 0) || 89;
Condition100%4/4
int($Args{'start_slots'} || 0) || 89
l!l
18067
$Args{'start_slots'} || 0
l!l
18067
MC/DC100%1/1
int($Args{'start_slots'} || 0) || 89
$Args{'start_slots'}
Truth table100%2/2
A
A= $Args{'start_slots'}
Aresult
11
00
834  
835 # Save read through/write back/write through details
836 8068 ▶ my $write_back = ($Args{write_action} || 'write_through') eq 'write_back';
Condition100%2/2
$Args{'write_action'} || 'write_through'
l!l
801157
MC/DC100%1/1
$Args{'write_action'} || 'write_through'
$Args{'write_action'}
Truth table100%2/2
A
A= $Args{'write_action'}
Aresult
11
00
837 @$Self{qw(context read_cb write_cb delete_cb)}
838 8068 = @Args{qw(context read_cb write_cb delete_cb)};
839 @$Self{qw(cache_not_found allow_recursive write_back)}
840 8068 = (@Args{qw(cache_not_found allow_recursive)}, $write_back);
841 @$Self{qw(unlink_on_exit enable_stats)}
842 8068 = (@Args{qw(unlink_on_exit)}, $enable_stats);
843  
844 # Save pid
845 8068 $Self->{pid} = $$;
846  
847 # Initialise C cache code
848 8068 my $Cache = fc_new();
849  
850 8068 $Self->{Cache} = $Cache;
851  
852 # Setup cache parameters
853 8068 fc_set_param($Cache, 'init_file', $init_file);
854 8068 fc_set_param($Cache, 'test_file', $test_file);
855 8068 fc_set_param($Cache, 'page_size', $page_size);
856 8068 fc_set_param($Cache, 'num_pages', $num_pages);
857 8068 fc_set_param($Cache, 'expire_time', $expire_time);
858 8068 fc_set_param($Cache, 'share_file', $share_file);
859 8068 ▶ fc_set_param($Cache, 'permissions', $permissions) if defined $permissions;
Branch: 1 branch
BranchTrueFalseTotal
if defined $permissions 2 8066 8068
860 8068 fc_set_param($Cache, 'start_slots', $start_slots);
861 8068 fc_set_param($Cache, 'catch_deadlocks', $catch_deadlocks);
862 8068 fc_set_param($Cache, 'enable_stats', $enable_stats);
863  
864 # And initialise it
865 8068 fc_init($Cache);
866  
867 # Track cache if need to empty on exit
868 8068 ▶ weaken($LiveCaches{"$Self"} = $Self)
Branch: 1 branch
BranchTrueFalseTotal
if $empty_on_exit 3 8065 8068
869 if $empty_on_exit;
870  
871 # All done, return PERL hash ref as class
872 8068 return $Self;
873 }
874  
875 =item I<get($Key, [ \%Options ])>
876  
877 Search cache for given Key. Returns undef if not found. If
878 I<read_cb> specified and not found, calls the callback to try
879 and find the value for the key, and if found (or 'cache_not_found'
880 is set), stores it into the cache and returns the found value.
881  
882 Keys holding a tombstone report as not found, and a value found by
883 I<read_cb> is returned but not stored back over a tombstone (see
884 L</TOMBSTONES AND MODSEQS>).
885  
886 I<%Options> is optional. Pass C<< modseq => \my $ModSeq >> to receive
887 the stored modseq of the value (undef if it was stored without one).
888 Other entries are used by get_and_set() to control the locking
889 behaviour. For now, you should probably ignore them unless you read
890 the code to understand how it works
891  
892 =cut
893 sub get {
894 186038 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine get: called CC=32 SCAR=34.9
Pod documented
895  
896 186038 ▶ my $SkipUnlock = $_[2] && $_[2]->{skip_unlock};
Condition100%3/3
$_[2] && $_[2]{'skip_unlock'}
!ll&&!rl&&r
166009820021
MC/DC100%2/2
$_[2] && $_[2]{'skip_unlock'}
$_[2] $_[2]{'skip_unlock'}
Truth table100%3/3
A && B
A= $_[2]B= $_[2]{'skip_unlock'}
ABresult
0X0
100
111
897 186038 my $Locked = 0;
898  
899 # Hash value, lock page, read result
900 186038 my ($HashPage, $HashSlot) = fc_hash($Cache, $_[1]);
901 186038 fc_lock($Cache, $HashPage);
902 186037 $Locked = 1;
903  
904 186037 my ($Val, $Flags, $Found, $ExpireOn, $ModSeq);
905 186037 my $Err;
906 eval {
907 186037 ($Val, $Flags, $Found, $ExpireOn, $ModSeq) = fc_read($Cache, $HashSlot, $_[1]);
908  
909 # Value not found, check underlying data store
910 186037 ▶ if (!$Found && (my $read_cb = $Self->{read_cb})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $Found and my $read_cb = $Self->{"read_cb"}) 23317 162720 186037
Condition100%3/3
not $Found and my $read_cb = $Self->{"read_cb"}
!ll&&!rl&&r
1465671615323317
MC/DC100%2/2
not $Found and my $read_cb = $Self->{"read_cb"}
not $Found my $read_cb = $Self->{"read_cb"}
Truth table100%3/3
not(A) and B
A= not $FoundB= my $read_cb = $Self->{"read_cb"}
ABresult
0X0
100
111
911  
912 # Callback to read from underlying data store
913 # (unlock page first if we allow recursive calls)
914 23317 ▶ if ($Self->{allow_recursive}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{'allow_recursive'}) { } 2 23315 23317
915 2 fc_unlock($Cache);
916 2 $Val = eval { $read_cb->($Self->{context}, $_[1]); };
917 2 my $CbErr = $@;
918 2 fc_lock($Cache, $HashPage);
919 2 ▶ die $CbErr if $CbErr;
Branch: 1 branch
BranchTrueFalseTotal
if $CbErr 1 1 2
920 } else {
921 23315 $Val = $read_cb->($Self->{context}, $_[1]);
922 }
923  
924 # If we found it, or want to cache not-found, store back into our cache
925 23314 ▶ if (defined $Val || $Self->{cache_not_found}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Val or $Self->{"cache_not_found"}) 12585 10729 23314
Condition100%3/3
defined $Val or $Self->{"cache_not_found"}
l!l&&r!l&&!r
12583210729
MC/DC100%2/2
defined $Val or $Self->{"cache_not_found"}
defined $Val $Self->{"cache_not_found"}
Truth table100%3/3
A or B
A= defined $ValB= $Self->{"cache_not_found"}
ABresult
1X1
011
000
926  
927 # Are we doing writeback's? If so, need to mark as dirty in cache
928 12585 my $write_back = $Self->{write_back};
929  
930 12585 ▶ $Val = $Self->{serialize}(\$Val) if $Self->{serialize};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"serialize"} 2 12583 12585
931 12585 ▶ $Val = $Self->{compress}($Val) if $Self->{compress};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"compress"} 0 12585 12585
932  
933 # Get key/value len (we've got 'use bytes'), and do expunge check to
934 # create space if needed
935 12585 ▶ my $KVLen = length($_[1]) + (defined($Val) ? length($Val) : 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $Val ? : 12584 1 12585
936 12585 $Self->_expunge_page(2, 1, $KVLen);
937  
938 # A tombstone refuses this store, and rightly so: the value we
939 # just computed may predate the invalidating change. It's
940 # still returned to the caller, just not cached
941 12585 fc_write($Cache, $HashSlot, $_[1], $Val, -1, 0);
942 }
943 }
944 186034 1;
945 186037 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { () = &fc_read($Cache, $HashSlot, $_[1]); if (not $Found and my $read_cb = $Self->{"read_cb"}) { if ($Self->{"allow_recursive"}) { &fc_unlock($Cache); $Val = eval { do { &$read_cb($Self->{"context"}, $_[1]) } }; my $CbErr = $@; &fc_lock($Cache, $HashPage); die $CbErr if $CbErr; } else { $Val = &$read_cb($Self->{"context"}, $_[1]); } ; if (defined $Val or $Self->{"cache_not_found"}) { my $write_back = $Self->{"write_back"}; $Val = $Self->{"serialize"}->(\$Val) if $Self->{"serialize"}; $Val = $Self->{"compress"}->($Val) if $Self->{"compress"}; my $KVLen = length($_[1]) + (defined $Val ? length $Val : 0); $Self->_expunge_page(2, 1, $KVLen); &fc_write($Cache, $HashSlot, $_[1], $Val, -1, 0); } ; } ; 1 } } or do { $Err = $@ || "unknown error" } 3 186034 186037
946 3 ▶ $Err = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
30
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
947 };
948  
949 # On error, always unlock (caller can't clean up after a thrown exception).
950 # On success, unlock unless caller asked us to leave the page locked.
951 186037 ▶ if (defined $Err) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Err) 3 186034 186037
952 3 ▶ fc_unlock($Cache) if $Locked && fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if $Locked and &fc_is_locked($Cache) 3 0 3
Condition33%1/3
$Locked and &fc_is_locked($Cache)
!ll&&!rl&&r
003
MC/DC0%0/2
$Locked and &fc_is_locked($Cache)
$Locked &fc_is_locked($Cache)
Truth table33%1/3
A and B
A= $LockedB= &fc_is_locked($Cache)
ABresult
0X0
100
111
953 3 die $Err;
954 }
955 186034 ▶ if (!$SkipUnlock) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($SkipUnlock) 166013 20021 186034
956 166013 fc_unlock($Cache);
957 166013 $Locked = 0;
958 }
959  
960 # If not using raw values, use thaw() to turn data back into object
961 eval {
962 186034 ▶ $Val = $Self->{uncompress}($Val) if defined($Val) && $Self->{compress};
Branch: 1 branch
BranchTrueFalseTotal
if defined $Val and $Self->{"compress"} 2 186032 186034
Condition100%3/3
defined $Val and $Self->{"compress"}
!ll&&!rl&&r
287661572662
MC/DC100%2/2
defined $Val and $Self->{"compress"}
defined $Val $Self->{"compress"}
Truth table100%3/3
A and B
A= defined $ValB= $Self->{"compress"}
ABresult
0X0
100
111
963 186034 ▶ $Val = ${$Self->{deserialize}($Val)} if defined($Val) && $Self->{deserialize};
Branch: 1 branch
BranchTrueFalseTotal
if defined $Val and $Self->{"deserialize"} 99312 86722 186034
Condition100%3/3
defined $Val and $Self->{"deserialize"}
!ll&&!rl&&r
287665795699312
MC/DC100%2/2
defined $Val and $Self->{"deserialize"}
defined $Val $Self->{"deserialize"}
Truth table100%3/3
A and B
A= defined $ValB= $Self->{"deserialize"}
ABresult
0X0
100
111
964 186033 1;
965 186034 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $Val = $Self->{"uncompress"}->($Val) if defined $Val and $Self->{"compress"}; $Val = ${$Self->{"deserialize"}->($Val);} if defined $Val and $Self->{"deserialize"}; 1 } } or do { $Err = $@ || "unknown error" } 1 186033 186034
966 1 ▶ $Err = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
967 };
968 186034 ▶ if (defined $Err) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Err) 1 186033 186034
969 1 ▶ fc_unlock($Cache) if $Locked && fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if $Locked and &fc_is_locked($Cache) 1 0 1
Condition33%1/3
$Locked and &fc_is_locked($Cache)
!ll&&!rl&&r
001
MC/DC0%0/2
$Locked and &fc_is_locked($Cache)
$Locked &fc_is_locked($Cache)
Truth table33%1/3
A and B
A= $LockedB= &fc_is_locked($Cache)
ABresult
0X0
100
111
970 1 die $Err;
971 }
972  
973 # Report the value's stored modseq if the caller asked for it
974 186033 ▶ if (my $ModSeqOut = $_[2] && $_[2]->{modseq}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ModSeqOut = $_[2] && $_[2]{"modseq"}) 8 186025 186033
Condition100%3/3
$_[2] && $_[2]{'modseq'}
!ll&&!rl&&r
166005200208
MC/DC100%2/2
$_[2] && $_[2]{'modseq'}
$_[2] $_[2]{'modseq'}
Truth table100%3/3
A && B
A= $_[2]B= $_[2]{'modseq'}
ABresult
0X0
100
111
975 8 ▶ ref($ModSeqOut) eq 'SCALAR' || die "get modseq option must be a scalar ref";
Branch: 1 branch
BranchTrueFalseTotal
ref $ModSeqOut eq "SCALAR" or die "get modseq option must be a scalar ref" 0 8 8
976 8 $$ModSeqOut = $ModSeq;
977 }
978  
979 # If explicitly asked to skip unlocking, return a sentinel so callers
980 # using the old 3-tuple unpack still work (slot 2 is now a placeholder).
981 186033 ▶ return ($Val, 1, {
Branch: 3 branches
BranchTrueFalseTotal
if $SkipUnlock 20020 166013 186033
$Found ? : 17674 2346 20020
defined $ModSeq ? : 1 20019 20020
982 $Found ? (expire_on => $ExpireOn) : (),
983 defined $ModSeq ? (modseq => $ModSeq) : (),
984 }) if $SkipUnlock;
985  
986 166013 return $Val;
987 }
988  
989 =item I<set($Key, $Value, [ \%Options ])>
990  
991 Store specified key/value pair into cache
992  
993 I<%Options> is optional. If it's not a hash reference, it's
994 assumed to be an explicit expiry time for the key being set,
995 this is to make set() compatible with the Cache::Cache interface
996  
997 If a hash is passed, the useful entries are expire_on to
998 set an explicit expiry time for this entry (epoch seconds), expire_time
999 to set an explicit relative future expiry time for this entry in
1000 seconds/minutes/days in the same format as passed to the new constructor,
1001 or modseq to make this a conditional store (see
1002 L</TOMBSTONES AND MODSEQS>): the value is stored tagged with the given
1003 64 bit unsigned modseq, unless the key holds a tombstone or live value
1004 with a newer modseq, in which case nothing is stored and false is
1005 returned. A set() without modseq is refused by any tombstone.
1006  
1007 Some other options are used internally, such as by get_and_set()
1008 to control the locking behaviour. For now, you should probably ignore
1009 it unless you read the code to understand how it works
1010  
1011 This method returns true if the value was stored in the cache,
1012 false otherwise. See the PAGE SIZE AND KEY/VALUE LIMITS section
1013 for more details.
1014  
1015 =cut
1016 sub set {
1017 91122 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine set: called CC=26 SCAR=32.6
Pod documented
1018  
1019 # Get opts, make compatible with Cache::Cache interface
1020 91122 ▶ my $Opts = defined($_[3]) ? (ref($_[3]) ? $_[3] : { expire_time => $_[3] }) : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $_[3] ? : 15057 76065 91122
ref $_[3] ? : 15035 22 15057
1021 # expire_on takes precedence, otherwise use expire_time if present
1022 my $expire_on = defined($Opts) ? (
1023 defined $Opts->{expire_on} ? $Opts->{expire_on} :
1024 91122 ▶ (defined $Opts->{expire_time} ? parse_expire_time($Opts->{expire_time}, _time()): -1)
Branch: 3 branches
BranchTrueFalseTotal
defined $Opts ? : 15057 76065 91122
defined $Opts->{'expire_on'} ? : 3 15054 15057
defined $Opts->{'expire_time'} ? : 23 15031 15054
1025 ) : -1;
1026  
1027 # Are we doing writeback's? If so, need to mark as dirty in cache
1028 91122 my $write_back = $Self->{write_back};
1029  
1030 91122 ▶ my $ModSeq = $Opts ? $Opts->{modseq} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$Opts ? : 15057 76065 91122
1031 91122 ▶ !defined($ModSeq) || $ModSeq =~ /^\d+$/
Branch: 1 branch
BranchTrueFalseTotal
not defined $ModSeq or $ModSeq =~ /^\d+$/ or die "set modseq option must be an unsigned integer" 0 91122 91122
Condition66%2/3
not defined $ModSeq or $ModSeq =~ /^\d+$/
l!l&&r!l&&!r
91103190
MC/DC0%0/2
not defined $ModSeq or $ModSeq =~ /^\d+$/
not defined $ModSeq $ModSeq =~ /^\d+$/
Truth table66%2/3
not(A) or B
A= not defined $ModSeqB= $ModSeq =~ /^\d+$/
ABresult
1X1
011
000
1032 or die "set modseq option must be an unsigned integer";
1033  
1034 # Hash value, lock page (unless caller already holds the lock)
1035 91122 my ($HashPage, $HashSlot) = fc_hash($Cache, $_[1]);
1036 91122 ▶ fc_lock($Cache, $HashPage) unless $Opts && $Opts->{_locked};
Branch: 1 branch
BranchTrueFalseTotal
unless $Opts and $Opts->{"_locked"} 76105 15017 91122
Condition100%3/3
$Opts and $Opts->{"_locked"}
!ll&&!rl&&r
760654015017
MC/DC100%2/2
$Opts and $Opts->{"_locked"}
$Opts $Opts->{"_locked"}
Truth table100%3/3
A and B
A= $OptsB= $Opts->{"_locked"}
ABresult
0X0
100
111
1037  
1038 91122 my ($DidStore, $Err);
1039 eval {
1040 91122 ▶ my $Val = $Self->{serialize} ? $Self->{serialize}(\$_[2]) : $_[2];
Branch: 1 branch
BranchTrueFalseTotal
$Self->{'serialize'} ? : 3514 87608 91122
1041 91121 ▶ $Val = $Self->{compress}($Val) if $Self->{compress};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"compress"} 2 91119 91121
1042  
1043 # Get key/value len (we've got 'use bytes'), and do expunge check to
1044 # create space if needed
1045 91121 ▶ my $KVLen = length($_[1]) + (defined($Val) ? length($Val) : 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $Val ? : 83099 8022 91121
1046 91121 $Self->_expunge_page(2, 1, $KVLen);
1047  
1048 # Now store into cache. 1 = stored, 0 = no space, -1 = conditional
1049 # store refused (see TOMBSTONES AND MODSEQS)
1050 91121 ▶ $DidStore = fc_write($Cache, $HashSlot, $_[1], $Val, $expire_on,
Branch: 1 branch
BranchTrueFalseTotal
$write_back ? : 56218 34903 91121
1051 $write_back ? FC_ISDIRTY : 0, $ModSeq);
1052 91121 1;
1053 91122 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $Val = $Self->{"serialize"} ? $Self->{"serialize"}->(\$_[2]) : $_[2]; $Val = $Self->{"compress"}->($Val) if $Self->{"compress"}; my $KVLen = length($_[1]) + (defined $Val ? length $Val : 0); $Self->_expunge_page(2, 1, $KVLen); $DidStore = &fc_write($Cache, $HashSlot, $_[1], $Val, $expire_on, $write_back ? 1 : 0, $ModSeq); 1 } } or do { $Err = $@ || "unknown error" } 1 91121 91122
1054 1 ▶ $Err = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1055 };
1056 91122 ▶ my $RefusedStore = $DidStore && $DidStore < 0;
Condition100%3/3
$DidStore && $DidStore < 0
!ll&&!rl&&r
6911097
MC/DC100%2/2
$DidStore && $DidStore < 0
$DidStore $DidStore < 0
Truth table100%3/3
A && B
A= $DidStoreB= $DidStore < 0
ABresult
0X0
100
111
1057 91122 ▶ $DidStore = $DidStore && $DidStore > 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$DidStore && $DidStore > 0 ? : 91109 13 91122
Condition100%3/3
$DidStore and $DidStore > 0
!ll&&!rl&&r
6791109
MC/DC100%2/2
$DidStore and $DidStore > 0
$DidStore $DidStore > 0
Truth table100%3/3
A and B
A= $DidStoreB= $DidStore > 0
ABresult
0X0
100
111
1058  
1059 # Always unlock — caller passed _locked to transfer ownership
1060 91122 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 91122 0 91122
1061 91122 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 1 91121 91122
1062  
1063 # If we're doing write-through, or write-back and didn't get into cache,
1064 # write back to the underlying store. Not for refused stores: the
1065 # whole point of the refusal is that our value is out of date
1066 91121 ▶ if (!$RefusedStore
Branch: 1 branch
BranchTrueFalseTotal
if (not $RefusedStore || $write_back && $DidStore and my $write_cb = $Self->{"write_cb"}) 3000 88121 91121
Condition88%8/9
not $RefusedStore || $write_back && $DidStore and my $write_cb = $Self->{"write_cb"}
!ll&&!rl&&r
56225318963000
$RefusedStore || $write_back && $DidStore
l!l&&r!l&&!r
75621834896
$write_back and $DidStore
!ll&&!rl&&r
34896056218
MC/DC75%3/4
not $RefusedStore || $write_back && $DidStore and my $write_cb = $Self->{"write_cb"}
$RefusedStore $write_back $DidStore my $write_cb = $Self->{"write_cb"}
Truth table66%4/6
not(A || B and C) and D
A= $RefusedStoreB= $write_backC= $DidStoreD= my $write_cb = $Self->{"write_cb"}
ABCDresult
1XXX0
011X0
00X00
01000
00X11
01011
1067 && (!$write_back || !$DidStore) && (my $write_cb = $Self->{write_cb})) {
1068 3000 eval { $write_cb->($Self->{context}, $_[1], $_[2], $expire_on); };
1069 }
1070  
1071 91121 return $DidStore;
1072 }
1073  
1074 =item I<get_and_set($Key, $AtomicSub)>
1075  
1076 Atomically retrieve and set the value of a Key.
1077  
1078 The page is locked while retrieving the $Key and is unlocked only after
1079 the value is set, thus guaranteeing the value does not change between
1080 the get and set operations.
1081  
1082 $AtomicSub is a reference to a subroutine that is called to calculate the
1083 new value to store. $AtomicSub gets $Key, the current value from the
1084 cache, and an options hash as paramaters. Currently the only option
1085 passed is the expire_on of the item.
1086  
1087 It should return the new value to set in the cache for the given $Key,
1088 and an optional hash of arguments in the same format as would be passed
1089 to a C<set()> call.
1090  
1091 If $AtomicSub returns an empty list, no value is stored back
1092 in the cache. This avoids updating the expiry time on an entry
1093 if you want to do a "get if in cache, store if not present" type
1094 callback.
1095  
1096 For example:
1097  
1098 =over 4
1099  
1100 =item *
1101  
1102 To atomically increment a value in the cache
1103  
1104 $Cache->get_and_set($Key, sub { return $_[1]+1; });
1105  
1106 =item *
1107  
1108 To add an item to a cached list and set the expiry time
1109 depending on the size of the list
1110  
1111 $Cache->get_and_set($Key, sub ($, $v) {
1112 push @$v, $item;
1113 return ($v, { expire_time => @$v > 2 ? '10s' : '2m' });
1114 });
1115  
1116 =item *
1117  
1118 To update a counter, but maintain the original expiry time
1119  
1120 $Cache->get_and_set($Key, sub {
1121 return ($_[1]+1, { expire_on => $_[2]->{expire_on} );
1122 });
1123  
1124  
1125 =back
1126  
1127 In scalar context the return value from C<get_and_set()>, is the
1128 *new* value stored back into the cache.
1129  
1130 In list context, a two item array is returned; the new value stored
1131 back into the cache and a boolean that's true if the value was stored
1132 in the cache, false otherwise. See the PAGE SIZE AND KEY/VALUE LIMITS
1133 section for more details.
1134  
1135 Notes:
1136  
1137 =over 4
1138  
1139 =item *
1140  
1141 Do not perform any get/set operations from the callback sub, as these
1142 operations lock the page and you may end up with a dead lock!
1143  
1144 =item *
1145  
1146 If your sub does a die/throws an exception, the page will correctly
1147 be unlocked (1.15 onwards)
1148  
1149 =back
1150  
1151 =cut
1152 sub get_and_set {
1153 15021 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine get_and_set: called CC=10 SCAR=23.0
Pod documented
1154  
1155 15021 my ($Value, $DidStore, $Err);
1156 eval {
1157 15021 ($Value, undef, my $Opts) = $Self->get($_[1], { skip_unlock => 1 });
1158 # Page is still locked here.
1159  
1160 15020 my @NewValue = $_[2]->($_[1], $Value, $Opts);
1161  
1162 15019 $DidStore = 0;
1163 15019 ▶ if (@NewValue) {
Branch: 1 branch
BranchTrueFalseTotal
if (@NewValue) { } 15018 1 15019
1164 15018 ($Value, my $SetOpts) = @NewValue;
1165 15018 ▶ die "get_and_set callback options must be a hash reference"
Branch: 1 branch
BranchTrueFalseTotal
if defined $SetOpts and ref $SetOpts ne "HASH" 1 15017 15018
Condition100%3/3
defined $SetOpts and ref $SetOpts ne "HASH"
!ll&&!rl&&r
1501161
MC/DC100%2/2
defined $SetOpts and ref $SetOpts ne "HASH"
defined $SetOpts ref $SetOpts ne "HASH"
Truth table100%3/3
A and B
A= defined $SetOptsB= ref $SetOpts ne "HASH"
ABresult
0X0
100
111
1166 if defined($SetOpts) && ref($SetOpts) ne 'HASH';
1167  
1168 # set() with _locked=>1 takes ownership of the lock and unlocks at end.
1169 15017 ▶ $DidStore = $Self->set($_[1], $Value, { _locked => 1, %{$SetOpts || {}} });
Branch: 1 branch
BranchTrueFalseTotal
$SetOpts or {} 15011 6 15017
1170 } else {
1171 1 fc_unlock($Cache);
1172 }
1173 15017 1;
1174 15021 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { ($Value, undef, my $Opts) = $Self->get($_[1], {"skip_unlock", 1}); my(@NewValue) = $_[2]->($_[1], $Value, $Opts); $DidStore = 0; if (@NewValue) { ($Value, my $SetOpts) = @NewValue; die "get_and_set callback options must be a hash reference" if defined $SetOpts and ref $SetOpts ne "HASH"; $DidStore = $Self->set($_[1], $Value, {"_locked", 1, %{$SetOpts or {};}}); } else { &fc_unlock($Cache); } ; 1 } } or do { $Err = $@ || "unknown error" } 4 15017 15021
1175 4 ▶ $Err = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
40
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1176 };
1177 15021 ▶ if (defined $Err) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Err) 4 15017 15021
1178 4 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 2 2 4
1179 4 die $Err;
1180 }
1181  
1182 15017 ▶ return wantarray ? ($Value, $DidStore) : $Value;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 4 15013 15017
1183 }
1184  
1185 =item I<exists($Key)>
1186  
1187 Search cache for given Key. Returns false if not found or true
1188 if found. This will *not* call the I<read_cb> if not found.
1189  
1190 This is also an optimisation over C<get()> as it will not uncompress or
1191 deserialize the value if found in the cache.
1192  
1193 =cut
1194 sub exists {
1195 24 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine exists: called CC=5 SCAR=17.4
Pod documented
1196  
1197 # Hash value, lock page, read result
1198 24 my ($HashPage, $HashSlot) = fc_hash($Cache, $_[1]);
1199 24 fc_lock($Cache, $HashPage);
1200 24 my ($Found, $Err);
1201 eval {
1202 24 my ($Val, $Flags, $ExpireOn);
1203 24 ($Val, $Flags, $Found, $ExpireOn) = fc_read($Cache, $HashSlot, $_[1]);
1204 24 1;
1205 24 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my($Val, $Flags, $ExpireOn); () = &fc_read($Cache, $HashSlot, $_[1]); 1 } } or do { $Err = $@ || "unknown error" } 0 24 24
1206 0 ▶ $Err = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1207 };
1208 24 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 24 0 24
1209 24 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 0 24 24
1210  
1211 24 return $Found;
1212 }
1213  
1214 =item I<remove($Key, [ \%Options ])>
1215  
1216 Delete the given key from the cache
1217  
1218 I<%Options> is optional. Pass C<< modseq => $ModSeq >> to leave a
1219 tombstone recording the modseq of the invalidating change instead of
1220 plainly deleting (see L</TOMBSTONES AND MODSEQS>); expire_on or
1221 expire_time then override the tombstone's expiry (default
1222 C<tombstone_expire_time>). An existing tombstone with a newer modseq
1223 is kept. Other entries are used by get_and_remove() to control the
1224 locking behaviour. For now, you should probably ignore them unless
1225 you read the code to understand how it works
1226  
1227 =cut
1228 sub remove {
1229 11401 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine remove: called CC=20 SCAR=31.7
Pod documented
1230 11401 my $Opts = $_[2];
1231  
1232 11401 ▶ my $ModSeq = $Opts ? $Opts->{modseq} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$Opts ? : 5007 6394 11401
1233 11401 ▶ !defined($ModSeq) || $ModSeq =~ /^\d+$/
Branch: 1 branch
BranchTrueFalseTotal
not defined $ModSeq or $ModSeq =~ /^\d+$/ or die "remove modseq option must be an unsigned integer" 0 11401 11401
Condition66%2/3
not defined $ModSeq or $ModSeq =~ /^\d+$/
l!l&&r!l&&!r
1139470
MC/DC0%0/2
not defined $ModSeq or $ModSeq =~ /^\d+$/
not defined $ModSeq $ModSeq =~ /^\d+$/
Truth table66%2/3
not(A) or B
A= not defined $ModSeqB= $ModSeq =~ /^\d+$/
ABresult
1X1
011
000
1234 or die "remove modseq option must be an unsigned integer";
1235  
1236 # Hash value, lock page (unless caller already holds the lock), delete
1237 11401 my ($HashPage, $HashSlot) = fc_hash($Cache, $_[1]);
1238 11401 ▶ fc_lock($Cache, $HashPage) unless $Opts && $Opts->{_locked};
Branch: 1 branch
BranchTrueFalseTotal
unless $Opts and $Opts->{"_locked"} 6401 5000 11401
Condition100%3/3
$Opts and $Opts->{"_locked"}
!ll&&!rl&&r
639475000
MC/DC100%2/2
$Opts and $Opts->{"_locked"}
$Opts $Opts->{"_locked"}
Truth table100%3/3
A and B
A= $OptsB= $Opts->{"_locked"}
ABresult
0X0
100
111
1239  
1240 11401 my ($DidDel, $Flags, $Err);
1241 eval {
1242 11401 ▶ if (defined $ModSeq) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ModSeq) { } 7 11394 11401
1243 # Remove-with-modseq leaves a tombstone recording the invalidating
1244 # change, so conditional stores can refuse stale write-backs.
1245 # The C layer never lowers an existing tombstone's modseq
1246 7 my $expire_on = -1;
1247 7 ▶ if ($Opts && defined $Opts->{expire_on}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($Opts and defined $Opts->{'expire_on'}) { } 0 7 7
elsif ($Opts and defined $Opts->{'expire_time'}) { } 2 5 7
elsif (my $TombExpire = $Self->{'tombstone_expire_time'}) { } 5 0 5
Condition33%1/3
$Opts and defined $Opts->{"expire_on"}
!ll&&!rl&&r
070
MC/DC0%0/2
$Opts and defined $Opts->{"expire_on"}
$Opts defined $Opts->{"expire_on"}
Truth table33%1/3
A and B
A= $OptsB= defined $Opts->{"expire_on"}
ABresult
0X0
100
111
1248 0 $expire_on = $Opts->{expire_on};
1249 ▶ } elsif ($Opts && defined $Opts->{expire_time}) {
Condition66%2/3
$Opts and defined $Opts->{"expire_time"}
!ll&&!rl&&r
052
MC/DC50%1/2
$Opts and defined $Opts->{"expire_time"}
$Opts defined $Opts->{"expire_time"}
Truth table66%2/3
A and B
A= $OptsB= defined $Opts->{"expire_time"}
ABresult
0X0
100
111
1250 2 $expire_on = parse_expire_time($Opts->{expire_time}, _time());
1251 } elsif (my $TombExpire = $Self->{tombstone_expire_time}) {
1252 5 $expire_on = _time() + $TombExpire;
1253 }
1254  
1255 7 $Self->_expunge_page(2, 1, length($_[1]) + 8);
1256 7 $DidDel = fc_tombstone($Cache, $HashSlot, $_[1], $expire_on, $ModSeq);
1257 7 $Flags = 0;
1258 } else {
1259 11394 ($DidDel, $Flags) = fc_delete($Cache, $HashSlot, $_[1]);
1260 }
1261 11401 1;
1262 11401 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { if (defined $ModSeq) { my $expire_on = -1; if ($Opts and defined $Opts->{"expire_on"}) { $expire_on = $Opts->{"expire_on"}; } elsif ($Opts and defined $Opts->{"expire_time"}) { $expire_on = parse_expire_time($Opts->{"expire_time"}, _time()); } elsif (my $TombExpire = $Self->{"tombstone_expire_time"}) { $expire_on = _time() + $TombExpire; } ; $Self->_expunge_page(2, 1, length($_[1]) + 8); $DidDel = &fc_tombstone($Cache, $HashSlot, $_[1], $expire_on, $ModSeq); $Flags = 0; } else { () = &fc_delete($Cache, $HashSlot, $_[1]); } ; 1 } } or do { $Err = $@ || "unknown error" } 0 11401 11401
1263 0 ▶ $Err = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1264 };
1265 11401 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 11401 0 11401
1266 11401 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 0 11401 11401
1267  
1268 # If we deleted from the cache, and it's not dirty, also delete
1269 # from underlying store
1270 11401 ▶ if ((!$DidDel || ($DidDel && !($Flags & FC_ISDIRTY)))
Branch: 1 branch
BranchTrueFalseTotal
if (!$DidDel || $DidDel && !($Flags & 1) and my $delete_cb = $Self->{"delete_cb"}) 283 11118 11401
Condition88%8/9
!$DidDel || $DidDel && !($Flags & 1) and my $delete_cb = $Self->{"delete_cb"}
!ll&&!rl&&r
1911099283
not $DidDel or $DidDel and not $Flags & 1
l!l&&r!l&&!r
5166621619
$DidDel and not $Flags & 1
!ll&&!rl&&r
0196216
MC/DC75%3/4
!$DidDel || $DidDel && !($Flags & 1) and my $delete_cb = $Self->{"delete_cb"}
not $DidDel $DidDel not $Flags & 1 my $delete_cb = $Self->{"delete_cb"}
Truth table83%5/6
not(A) or B and not(C) and D
A= not $DidDelB= $DidDelC= not $Flags & 1D= my $delete_cb = $Self->{"delete_cb"}
ABCDresult
00XX0
010X0
1XX00
01100
1XX11
01111
1271 && (my $delete_cb = $Self->{delete_cb})) {
1272 283 eval { $delete_cb->($Self->{context}, $_[1]); };
1273 }
1274  
1275 11401 return $DidDel;
1276 }
1277  
1278 =item I<get_and_remove($Key)>
1279  
1280 Atomically retrieve value of a Key while removing it from the cache.
1281  
1282 The page is locked while retrieving the $Key and is unlocked only after
1283 the value is removed, thus guaranteeing the value stored by someone else
1284 isn't removed by us.
1285  
1286 =cut
1287 sub get_and_remove {
1288 5000 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine get_and_remove: called CC=2 SCAR=7.0
Pod documented
1289  
1290 5000 my ($Value) = $Self->get($_[1], { skip_unlock => 1 });
1291 5000 my $DidDel = $Self->remove($_[1], { _locked => 1 });
1292 5000 ▶ return wantarray ? ($Value, $DidDel) : $Value;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 5000 0 5000
1293 }
1294  
1295 =item I<expire($Key)>
1296  
1297 Explicitly expire the given $Key. For a cache in write-back mode, this
1298 will cause the item to be written back to the underlying store if dirty,
1299 otherwise it's the same as removing the item.
1300  
1301 =cut
1302 sub expire {
1303 3 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine expire: called CC=11 SCAR=25.1
Pod documented
1304  
1305 # Hash value, lock page, read result
1306 3 my ($HashPage, $HashSlot) = fc_hash($Cache, $_[1]);
1307 3 fc_lock($Cache, $HashPage);
1308 3 my ($Val, $Flags, $Found, $ExpireOn, $Err);
1309 eval {
1310 3 ($Val, $Flags, $Found, $ExpireOn) = fc_read($Cache, $HashSlot, $_[1]);
1311  
1312 # If we found it, remove it
1313 3 ▶ if ($Found) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Found) 2 1 3
1314 2 (undef, $Flags) = fc_delete($Cache, $HashSlot, $_[1]);
1315 }
1316 3 1;
1317 3 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { () = &fc_read($Cache, $HashSlot, $_[1]); if ($Found) { (undef, $Flags) = &fc_delete($Cache, $HashSlot, $_[1]); } ; 1 } } or do { $Err = $@ || "unknown error" } 0 3 3
1318 0 ▶ $Err = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1319 };
1320 3 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 3 0 3
1321 3 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 0 3 3
1322  
1323 # If it's dirty, write it back
1324 3 ▶ if (($Flags & FC_ISDIRTY) && (my $write_cb = $Self->{write_cb})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Flags & 1 and my $write_cb = $Self->{"write_cb"}) 2 1 3
Condition66%2/3
$Flags & 1 and my $write_cb = $Self->{"write_cb"}
!ll&&!rl&&r
102
MC/DC50%1/2
$Flags & 1 and my $write_cb = $Self->{"write_cb"}
$Flags & 1 my $write_cb = $Self->{"write_cb"}
Truth table66%2/3
A and B
A= $Flags & 1B= my $write_cb = $Self->{"write_cb"}
ABresult
0X0
100
111
1325 2 ▶ if (defined $Val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Val) 2 0 2
1326 2 ▶ $Val = $Self->{uncompress}($Val) if $Self->{uncompress};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"uncompress"} 0 2 2
1327 2 ▶ $Val = ${$Self->{deserialize}($Val)} if $Self->{deserialize};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"deserialize"} 1 1 2
1328 }
1329 2 eval { $write_cb->($Self->{context}, $_[1], $Val, $ExpireOn); };
1330 }
1331  
1332 3 return $Found;
1333 }
1334  
1335 =item I<clear()>
1336  
1337 Clear all items from the cache
1338  
1339 Note: If you're using callbacks, this has no effect
1340 on items in the underlying data store. No delete
1341 callbacks are made
1342  
1343 =cut
1344 sub clear {
1345 4 ▶ my $Self = shift;
Subroutine clear: called CC=1 SCAR=0.0
Pod documented
1346 4 $Self->_expunge_all(1, 0);
1347 }
1348  
1349 =item I<purge()>
1350  
1351 Clear all expired items from the cache
1352  
1353 Note: If you're using callbacks, this has no effect
1354 on items in the underlying data store. No delete
1355 callbacks are made, and no write callbacks are made
1356 for the expired data
1357  
1358 =cut
1359 sub purge {
1360 0 ▶ my $Self = shift;
Subroutine purge: not called CC=1 SCAR=6.9
Pod documented
1361 0 $Self->_expunge_all(0, 0);
1362 }
1363  
1364 =item I<empty($OnlyExpired)>
1365  
1366 Empty all items from the cache, or if $OnlyExpired is
1367 true, only expired items.
1368  
1369 Note: If 'write_back' mode is enabled, any changed items
1370 are written back to the underlying store. Expired items are
1371 written back to the underlying store as well.
1372  
1373 =cut
1374 sub empty {
1375 10 ▶ my $Self = shift;
Subroutine empty: called CC=2 SCAR=6.9
Pod documented
1376 10 ▶ $Self->_expunge_all($_[0] ? 0 : 1, 1);
Branch: 1 branch
BranchTrueFalseTotal
$_[0] ? : 3 7 10
1377 }
1378  
1379 =item I<repaired_pages()>
1380  
1381 Number of pages this process has found unusable and reinitialised
1382 since it opened the cache (see L</KILLED WRITERS AND PAGE REPAIR>).
1383  
1384 =cut
1385 sub repaired_pages {
1386 0 ▶ my $Self = shift;
Subroutine repaired_pages: not called CC=1 SCAR=6.9
Pod documented
1387 0 return fc_get_param($Self->{Cache}, 'repaired_pages');
1388 }
1389  
1390 =item I<get_keys($Mode)>
1391  
1392 Get a list of keys/values held in the cache. May immediately be out of
1393 date because of the shared access nature of the cache
1394  
1395 If $Mode == 0, an array of keys is returned
1396  
1397 If $Mode == 1, then an array of hashrefs, with 'key',
1398 'last_access', 'expire_on' and 'flags' keys is returned
1399  
1400 If $Mode == 2, then hashrefs also contain 'value' key
1401  
1402 =cut
1403 sub get_keys {
1404 623 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine get_keys: called CC=10 SCAR=23.7
Pod documented
1405  
1406 623 ▶ my $Mode = $_[1] || 0;
Condition100%2/2
$_[1] || 0
l!l
417206
MC/DC100%1/1
$_[1] || 0
$_[1]
Truth table100%2/2
A
A= $_[1]
Aresult
11
00
1407 623 my ($Uncompress, $Deserialize) = @$Self{qw(uncompress deserialize)};
1408  
1409 623 ▶ return fc_get_keys($Cache, $Mode)
Branch: 1 branch
BranchTrueFalseTotal
if $Mode <= 1 or $Mode == 2 and not $Uncompress and not $Deserialize 622 1 623
Condition66%6/9
$Mode <= 1 or $Mode == 2 and not $Uncompress and not $Deserialize
l!l&&r!l&&!r
4072151
$Mode == 2 and not $Uncompress and not $Deserialize
!ll&&!rl&&r
01215
$Mode == 2 and not $Uncompress
!ll&&!rl&&r
00216
MC/DC50%2/4
$Mode <= 1 or $Mode == 2 and not $Uncompress and not $Deserialize
$Mode <= 1 $Mode == 2 not $Uncompress not $Deserialize
Truth table60%3/5
A or B and not(C) and not(D)
A= $Mode <= 1B= $Mode == 2C= not $UncompressD= not $Deserialize
ABCDresult
1XXX1
01111
00XX0
010X0
01100
1410 if $Mode <= 1 || ($Mode == 2 && !$Uncompress && !$Deserialize);
1411  
1412 # If we're getting values as well, and they're not raw, unfreeze them
1413 1 my @Details = fc_get_keys($Cache, 2);
1414  
1415 1 for (@Details) {
1416 2 my $Val = $_->{value};
1417 2 ▶ if (defined $Val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Val) 2 0 2
1418 2 ▶ $Val = $Uncompress->($Val) if $Uncompress;
Branch: 1 branch
BranchTrueFalseTotal
if $Uncompress 0 2 2
1419 2 ▶ $Val = ${$Deserialize->($Val)} if $Deserialize;
Branch: 1 branch
BranchTrueFalseTotal
if $Deserialize 2 0 2
1420 2 $_->{value} = $Val;
1421 }
1422 }
1423 1 return @Details;
1424 }
1425  
1426 =item I<get_statistics($Clear)>
1427  
1428 Returns a two value list of (nreads, nreadhits). This
1429 only works if you passed enable_stats in the constructor
1430  
1431 nreads is the total number of read attempts done on the
1432 cache since it was created
1433  
1434 nreadhits is the total number of read attempts done on
1435 the cache since it was created that found the key/value
1436 in the cache
1437  
1438 If $Clear is true, the values are reset immediately after
1439 they are retrieved
1440  
1441 =cut
1442 sub get_statistics {
1443 3 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine get_statistics: called CC=7 SCAR=20.3
Pod documented
1444 3 my $Clear = $_[1];
1445  
1446 3 my ($NReads, $NReadHits) = (0, 0);
1447 3 for (0 .. $Self->{num_pages}-1) {
1448 267 fc_lock($Cache, $_);
1449 267 my $Err;
1450 eval {
1451 267 my ($PNReads, $PNReadHits) = fc_get_page_details($Cache);
1452 267 $NReads += $PNReads;
1453 267 $NReadHits += $PNReadHits;
1454 267 ▶ fc_reset_page_details($Cache) if $Clear;
Branch: 1 branch
BranchTrueFalseTotal
if $Clear 178 89 267
1455 267 1;
1456 267 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { () = &fc_get_page_details($Cache); $NReads += $PNReads; $NReadHits += $PNReadHits; &fc_reset_page_details($Cache) if $Clear; 1 } } or do { $Err = $@ || "unknown error" } 0 267 267
1457 0 ▶ $Err = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1458 };
1459 267 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 267 0 267
1460 267 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 0 267 267
1461 }
1462 3 return ($NReads, $NReadHits);
1463 }
1464  
1465 =item I<multi_get($PageKey, [ $Key1, $Key2, ... ])>
1466  
1467 The two multi_xxx routines act a bit differently to the
1468 other routines. With the multi_get, you pass a separate
1469 PageKey value and then multiple keys. The PageKey value
1470 is hashed, and that page locked. Then that page is
1471 searched for each key. It returns a hash ref of
1472 Key => Value items found in that page in the cache.
1473  
1474 The main advantage of this is just a speed one, if you
1475 happen to need to search for a lot of items on each call.
1476  
1477 For instance, say you have users and a bunch of pieces
1478 of separate information for each user. On a particular
1479 run, you need to retrieve a sub-set of that information
1480 for a user. You could do lots of get() calls, or you
1481 could use the 'username' as the page key, and just
1482 use one multi_get() and multi_set() call instead.
1483  
1484 A couple of things to note:
1485  
1486 =over 4
1487  
1488 =item 1.
1489  
1490 This makes multi_get()/multi_set() and get()/set()
1491 incompatible. Don't mix calls to the two, because
1492 you won't find the data you're expecting
1493  
1494 =item 2.
1495  
1496 The writeback and callback modes of operation do
1497 not work with multi_get()/multi_set(). Don't attempt
1498 to use them together.
1499  
1500 =back
1501  
1502 =cut
1503 sub multi_get {
1504 3 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine multi_get: called CC=11 SCAR=24.6
Pod documented
1505  
1506 # Hash value page key, lock page
1507 3 my ($HashPage, $HashSlot) = fc_hash($Cache, $_[1]);
1508 3 fc_lock($Cache, $HashPage);
1509  
1510 3 my ($Keys, %KVs) = ($_[2]);
1511 3 my $Err;
1512 eval {
1513 # For each key to find
1514 3 for (@$Keys) {
1515  
1516 # Hash key to get slot in this page and read
1517 6 my $FinalKey = "$_[1]-$_";
1518 6 (undef, $HashSlot) = fc_hash($Cache, $FinalKey);
1519 6 my ($Val, $Flags, $Found, $ExpireOn) = fc_read($Cache, $HashSlot, $FinalKey);
1520 6 ▶ next unless $Found;
Branch: 1 branch
BranchTrueFalseTotal
unless $Found 0 6 6
1521  
1522 # If not using raw values, use thaw() to turn data back into object
1523 6 ▶ $Val = $Self->{uncompress}($Val) if defined($Val) && $Self->{compress};
Branch: 1 branch
BranchTrueFalseTotal
if defined $Val and $Self->{"compress"} 0 6 6
Condition33%1/3
defined $Val and $Self->{"compress"}
!ll&&!rl&&r
060
MC/DC0%0/2
defined $Val and $Self->{"compress"}
defined $Val $Self->{"compress"}
Truth table33%1/3
A and B
A= defined $ValB= $Self->{"compress"}
ABresult
0X0
100
111
1524 6 ▶ $Val = ${$Self->{deserialize}($Val)} if defined($Val) && $Self->{deserialize};
Branch: 1 branch
BranchTrueFalseTotal
if defined $Val and $Self->{"deserialize"} 2 4 6
Condition66%2/3
defined $Val and $Self->{"deserialize"}
!ll&&!rl&&r
042
MC/DC50%1/2
defined $Val and $Self->{"deserialize"}
defined $Val $Self->{"deserialize"}
Truth table66%2/3
A and B
A= defined $ValB= $Self->{"deserialize"}
ABresult
0X0
100
111
1525  
1526 # Save to return
1527 5 $KVs{$_} = $Val;
1528 }
1529 2 1;
1530 3 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { foreach $_ (@$Keys) { my $FinalKey = "$_[1]-$_"; (undef, $HashSlot) = &fc_hash($Cache, $FinalKey); () = &fc_read($Cache, $HashSlot, $FinalKey); next unless $Found; $Val = $Self->{"uncompress"}->($Val) if defined $Val and $Self->{"compress"}; $Val = ${$Self->{"deserialize"}->($Val);} if defined $Val and $Self->{"deserialize"}; $KVs{$_} = $Val; } ; 1 } } or do { $Err = $@ || "unknown error" } 1 2 3
1531 1 ▶ $Err = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1532 };
1533  
1534 3 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 3 0 3
1535 3 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 1 2 3
1536  
1537 2 return \%KVs;
1538 }
1539  
1540 =item I<multi_set($PageKey, { $Key1 => $Value1, $Key2 => $Value2, ... }, [ \%Options ])>
1541  
1542 Store specified key/value pair into cache
1543  
1544 =cut
1545 sub multi_set {
1546 6 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine multi_set: called CC=13 SCAR=27.4
Pod documented
1547  
1548 # Get opts, make compatible with Cache::Cache interface
1549 6 ▶ my $Opts = defined($_[3]) ? (ref($_[3]) ? $_[3] : { expire_time => $_[3] }) : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $_[3] ? : 0 6 6
ref $_[3] ? : 0 0 0
1550 # expire_on takes precedence, otherwise use expire_time if present
1551 my $expire_on = defined($Opts) ? (
1552 defined $Opts->{expire_on} ? $Opts->{expire_on} :
1553 6 ▶ (defined $Opts->{expire_time} ? parse_expire_time($Opts->{expire_time}, _time()): -1)
Branch: 3 branches
BranchTrueFalseTotal
defined $Opts ? : 0 6 6
defined $Opts->{'expire_on'} ? : 0 0 0
defined $Opts->{'expire_time'} ? : 0 0 0
1554 ) : -1;
1555  
1556 # Hash page key value, lock page
1557 6 my ($HashPage, $HashSlot) = fc_hash($Cache, $_[1]);
1558 6 fc_lock($Cache, $HashPage);
1559  
1560 6 my $KVs = $_[2];
1561 6 my $Err;
1562 eval {
1563 # Loop over each key/value storing into this page
1564 6 ▶ while (my ($Key, $Val) = each %$KVs) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$KVs) 9 5 14
1565  
1566 9 ▶ $Val = $Self->{serialize}(\$Val) if $Self->{serialize};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"serialize"} 5 4 9
1567 8 ▶ $Val = $Self->{compress}($Val) if $Self->{compress};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"compress"} 0 8 8
1568  
1569 # Get key/value len (we've got 'use bytes'), and do expunge check to
1570 # create space if needed
1571 8 my $FinalKey = "$_[1]-$Key";
1572 8 my $KVLen = length($FinalKey) + length($Val);
1573 8 $Self->_expunge_page(2, 1, $KVLen);
1574  
1575 # Now hash key and store into page
1576 8 (undef, $HashSlot) = fc_hash($Cache, $FinalKey);
1577 8 my $DidStore = fc_write($Cache, $HashSlot, $FinalKey, $Val, $expire_on, 0);
1578 }
1579 5 1;
1580 6 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { while (() = each %$KVs) { do { $Val = $Self->{"serialize"}->(\$Val) if $Self->{"serialize"}; $Val = $Self->{"compress"}->($Val) if $Self->{"compress"}; my $FinalKey = "$_[1]-$Key"; my $KVLen = length($FinalKey) + length($Val); $Self->_expunge_page(2, 1, $KVLen); (undef, $HashSlot) = &fc_hash($Cache, $FinalKey); my $DidStore = &fc_write($Cache, $HashSlot, $FinalKey, $Val, $expire_on, 0) }; } ; 1 } } or do { $Err = $@ || "unknown error" } 1 5 6
1581 1 ▶ $Err = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1582 };
1583  
1584 6 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 6 0 6
1585 6 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 1 5 6
1586  
1587 5 return 1;
1588 }
1589  
1590 =back
1591  
1592 =cut
1593  
1594 =head1 INTERNAL METHODS
1595  
1596 =over 4
1597  
1598 =cut
1599  
1600 =item I<_expunge_all($Mode, $WB)>
1601  
1602 Expunge all items from the cache
1603  
1604 Expunged items (that have not expired) are written
1605 back to the underlying store if write_back is enabled
1606  
1607 =cut
1608 sub _expunge_all {
1609 14 ▶ my ($Self, $Cache, $Mode, $WB) = ($_[0], $_[0]->{Cache}, $_[1], $_[2]);
Subroutine _expunge_all: called CC=6 SCAR=19.9
1610  
1611 # Repeat expunge for each page
1612 14 for (0 .. $Self->{num_pages}-1) {
1613 738 fc_lock($Cache, $_);
1614 738 my $Err;
1615 eval {
1616 738 $Self->_expunge_page($Mode, $WB, -1);
1617 738 1;
1618 738 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $Self->_expunge_page($Mode, $WB, -1); 1 } } or do { $Err = $@ || "unknown error" } 0 738 738
1619 0 ▶ $Err = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1620 };
1621 738 ▶ fc_unlock($Cache) if fc_is_locked($Cache);
Branch: 1 branch
BranchTrueFalseTotal
if &fc_is_locked($Cache) 738 0 738
1622 738 ▶ die $Err if defined $Err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Err 0 738 738
1623 }
1624  
1625 }
1626  
1627 =item I<_expunge_page($Mode, $WB, $Len)>
1628  
1629 Expunge items from the current page to make space for
1630 $Len bytes key/value items
1631  
1632 Expunged items (that have not expired) are written
1633 back to the underlying store if write_back is enabled
1634  
1635 =cut
1636 sub _expunge_page {
1637 104459 ▶ my ($Self, $Cache, $Mode, $WB, $Len) = ($_[0], $_[0]->{Cache}, @_[1 .. 3]);
Subroutine _expunge_page: called CC=9 SCAR=22.0
1638  
1639 # If writeback mode, need to get expunged items to write back
1640 104459 ▶ my $write_cb = $Self->{write_back} && $WB ? $Self->{write_cb} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$Self->{'write_back'} && $WB ? : 64717 39742 104459
Condition100%3/3
$Self->{"write_back"} and $WB
!ll&&!rl&&r
397222064717
MC/DC100%2/2
$Self->{"write_back"} and $WB
$Self->{"write_back"} $WB
Truth table100%3/3
A and B
A= $Self->{"write_back"}B= $WB
ABresult
0X0
100
111
1641  
1642 104459 ▶ my @WBItems = fc_expunge($Cache, $Mode, $write_cb ? 1 : 0, $Len);
Branch: 1 branch
BranchTrueFalseTotal
$write_cb ? : 64717 39742 104459
1643  
1644 104459 my ($Uncompress, $Deserialize) = @$Self{qw(uncompress deserialize)};
1645  
1646 104459 for (@WBItems) {
1647 41406 ▶ next if !($_->{flags} & FC_ISDIRTY);
Branch: 1 branch
BranchTrueFalseTotal
unless $_->{"flags"} & 1 7913 33493 41406
1648  
1649 33493 my $Val = $_->{value};
1650 33493 ▶ if (defined $Val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Val) 29741 3752 33493
1651 29741 ▶ $Val = $Uncompress->($Val) if $Uncompress;
Branch: 1 branch
BranchTrueFalseTotal
if $Uncompress 0 29741 29741
1652 29741 ▶ $Val = ${$Deserialize->($Val)} if $Deserialize;
Branch: 1 branch
BranchTrueFalseTotal
if $Deserialize 2 29739 29741
1653 }
1654 33493 eval { $write_cb->($Self->{context}, $_->{key}, $Val, $_->{expire_on}); };
1655 }
1656 }
1657  
1658 sub _time {
1659 30 ▶ $time_override ? $time_override : time;
Subroutine _time: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$time_override ? : 23 7 30
1660 }
1661  
1662 sub _set_time_override {
1663 14 ▶ my $Time = shift;
Subroutine _set_time_override: called CC=2 SCAR=6.9
1664 14 $time_override = $Time;
1665 14 ▶ fc_set_time_override($Time || 0);
Condition100%2/2
$Time || 0
l!l
131
MC/DC100%1/1
$Time || 0
$Time
Truth table100%2/2
A
A= $Time
Aresult
11
00
1666 }
1667  
1668 25 my %Times = ('' => 1, s => 1, m => 60, h => 60*60, d => 24*60*60, w => 7*24*60*60);
1669  
1670 sub parse_expire_time {
1671 16161 ▶ my $expire_time = shift || '';
Subroutine parse_expire_time: called CC=7 SCAR=19.5
Pod undocumented
Condition100%2/2
shift() || ''
l!l
2816133
MC/DC100%1/1
shift() || ''
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
1672 16161 ▶ return 0 if $expire_time eq 'never';
Branch: 1 branch
BranchTrueFalseTotal
if $expire_time eq "never" 2 16159 16161
1673 16159 ▶ return @_ ? shift : 1 if $expire_time eq 'now';
Branch: 2 branches
BranchTrueFalseTotal
if $expire_time eq "now" 2 16157 16159
@_ ? : 2 0 2
1674 16157 ▶ my $offset = $expire_time =~ /^(\d+)\s*([mhdws]?)/i ? $1 * $Times{lc($2)} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$expire_time =~ /^(\d+)\s*([mhdws]?)/i ? : 21 16136 16157
1675 16157 ▶ return $offset + (@_ ? shift : 0);
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 21 16136 16157
1676 }
1677  
1678 sub cleanup {
1679 8065 ▶ my ($Self, $Cache) = ($_[0], $_[0]->{Cache});
Subroutine cleanup: called CC=8 SCAR=21.3
Pod undocumented
1680  
1681 # Avoid potential double cleanup
1682 8065 ▶ return if $Self->{cleaned};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"cleaned"} 0 8065 8065
1683 8065 $Self->{cleaned} = 1;
1684  
1685 # Expunge all entries on exit if requested and in parent process
1686 8065 ▶ if ($Self->{empty_on_exit} && $Cache && $Self->{pid} == $$) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"empty_on_exit"} and $Cache and $Self->{"pid"} == $$) 3 8062 8065
Condition66%4/6
$Self->{"empty_on_exit"} and $Cache and $Self->{"pid"} == $$
!ll&&!rl&&r
806203
$Self->{"empty_on_exit"} and $Cache
!ll&&!rl&&r
806203
MC/DC33%1/3
$Self->{"empty_on_exit"} and $Cache and $Self->{"pid"} == $$
$Self->{"empty_on_exit"} $Cache $Self->{"pid"} == $$
Truth table50%2/4
A and B and C
A= $Self->{"empty_on_exit"}B= $CacheC= $Self->{"pid"} == $$
ABCresult
0XX0
10X0
1100
1111
1687 3 $Self->empty();
1688 }
1689  
1690 8065 ▶ if ($Cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Cache) 8065 0 8065
1691 8065 fc_close($Cache);
1692 8065 $Cache = undef;
1693 8065 delete $Self->{Cache};
1694 }
1695  
1696 unlink($Self->{share_file})
1697 8065 ▶ if $Self->{unlink_on_exit} && $Self->{pid} == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"unlink_on_exit"} and $Self->{"pid"} == $$ 8063 2 8065
Condition66%2/3
$Self->{"unlink_on_exit"} and $Self->{"pid"} == $$
!ll&&!rl&&r
028063
MC/DC50%1/2
$Self->{"unlink_on_exit"} and $Self->{"pid"} == $$
$Self->{"unlink_on_exit"} $Self->{"pid"} == $$
Truth table66%2/3
A and B
A= $Self->{"unlink_on_exit"}B= $Self->{"pid"} == $$
ABresult
0X0
100
111
1698  
1699 }
1700  
1701 sub DESTROY {
1702 8065 ▶ my $Self = shift;
Subroutine DESTROY: called CC=2 SCAR=6.9
1703 8065 $Self->cleanup();
1704 8065 ▶ delete $LiveCaches{"$Self"} if $Self->{empty_on_exit};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"empty_on_exit"} 3 8062 8065
1705 }
1706  
1707 sub END {
1708 25 ▶ while (my (undef, $Self) = each %LiveCaches) {
Subroutine END: called CC=3 SCAR=15.4
Branch: 1 branch
BranchTrueFalseTotal
if (my(undef, $Self) = each %Cache::FastMmap::LiveCaches) 0 25 25
1709 # Weak reference, might be undef already
1710 0 ▶ $Self->cleanup() if $Self;
Branch: 1 branch
BranchTrueFalseTotal
if $Self 0 0 0
1711 }
1712 25 %LiveCaches = ();
1713 }
1714  
1715 sub CLONE {
1716 0 ▶ die "Cache::FastMmap does not support threads sorry";
Subroutine CLONE: not called CC=1 SCAR=6.9
1717 }
1718  
1719 25 1;
1720  
1721 __END__
↑ Summary unix.c »