Fast/Cache.pm

filter: Statementstmt 96.1% 175 / 182 Branchbran 91.0% 51 / 56 Conditioncond 82.3% 28 / 34 MC/DCmcdc 71.4% 15 / 21 Subroutinesub 85.0% 17 / 20 Podpod 100% 12 / 12 totaltotal 91.6% 298 / 325 CC 52 SCAR 20.2
CC
52
Cov
93%
set
13.0
get
11.0
_drop_key
9.1
CRAP 7.5
« Fast/Schema.pm ↑ Summary Fast/Cached.pm »
1 package DBIx::Fast::Cache;
2  
3 5 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 5 our $VERSION = '0.21';
7 5 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Time::HiRes 'time';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 # In-process query cache with TTL and tag-based invalidation.
11 #
12 # Backend: LRU::Cache (XS) by default - 6M+ set+get/s, ~120ns per op.
13 # Capacity eviction is delegated to the backend. TTL and tags are layered
14 # on top by storing each value as [$value, $expires_at, \@tags].
15 #
16 # Multi-process deployments should swap the backend to CHI (Redis/Memcached)
17 # via the `backend` option; the API stays identical.
18  
19 class DBIx::Fast::Cache {
20 0 field $max_size :param :reader = 1_000;
21 0 ▶ field $default_ttl :param :reader = 60; # seconds; 0 = no expiry
Subroutine max_size: not called CC=1 SCAR=2.6
Pod documented
22 0 ▶ field $backend :param :reader = 'LRU'; # 'LRU' | 'CHI' | object
Subroutine default_ttl: not called CC=1 SCAR=0.4
Pod documented
23 # Tag invalidation shared by every process using the same backend (see
24 # invalidate). Default: on for an external backend object, off for the
25 # in-process LRU.
26 1 ▶ field $shared :param :reader = undef;
Subroutine backend: called CC=1 SCAR=0.0
Pod documented
27  
28 0 ▶ field $_store; # backend instance
Subroutine shared: not called CC=1 SCAR=1.2
Pod documented
29 5 field $_delete_cb; # closure mapping to the backend's delete/remove
30 5 field $_set_ttl; # backend set() accepts a TTL third arg (CHI)
31 field $_tag_index = {}; # tag => { key => 1 }
32 5 field $_index_pairs = 0; # live key-tag pairs in $_tag_index
33 5 field $_index_watermark; # sweep threshold (see _sweep_index)
34 field $_stats = {
35 hits => 0,
36 misses => 0,
37 sets => 0,
38 evictions => 0,
39 expirations => 0,
40 invalidations => 0,
41 };
42  
43 5 ADJUST {
44 if (ref $backend) {
45 # Pre-built backend object (duck-typed: must respond to get/set
46 # and one of delete/remove, plus clear).
47 $_store = $backend;
48 }
49 elsif ($backend eq 'LRU') {
50 require LRU::Cache;
51 $_store = LRU::Cache->new($max_size);
52 }
53 elsif ($backend eq 'CHI') {
54 croak "CHI backend requires a pre-built CHI object passed as backend";
55 }
56 else {
57 croak "Unknown cache backend: $backend";
58 }
59  
60 # Normalize delete API across backends. CHI calls it `remove`,
61 # LRU::Cache calls it `delete`. Resolved once at construction.
62 if ($_store->can('delete')) {
63 $_delete_cb = sub { $_store->delete($_[0]) };
64 }
65 elsif ($_store->can('remove')) {
66 $_delete_cb = sub { $_store->remove($_[0]) };
67 }
68 else {
69 croak "Cache backend ", ref($_store),
70 " supports neither delete() nor remove()";
71 }
72  
73 # CHI-like backends accept a TTL on set(): push ours down so the external
74 # store (Redis/Memcached) also expires entries physically, instead of
75 # holding logically-expired data until eviction.
76 $_set_ttl = $_store->isa('CHI::Driver')
77 || ($_store->can('supports_ttl') && $_store->supports_ttl);
78 $shared //= ref $backend ? 1 : 0;
79  
80 # The tag index is pruned lazily; sweep when it outgrows this many
81 # key-tag pairs (see _sweep_index).
82 $_index_watermark = 4 * $max_size;
83 }
84  
85 66 ▶ method get ($key) {
Subroutine get: called CC=11 SCAR=24.0
Pod documented
86 66 my $entry = $_store->get($key);
87 66 ▶ unless (defined $entry) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 36 30 66
88 36 $_stats->{misses}++;
89 36 return undef;
90 }
91  
92 # entry = [$value, $expires_at, \@tags (, \@tag_versions when shared)]
93 30 my ($value, $expires_at) = @$entry;
94  
95 30 ▶ if ($expires_at && $expires_at <= time()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expires_at and $expires_at <= &DBIx::Fast::Cache::time()) 1 29 30
Condition100%3/3
$expires_at and $expires_at <= &DBIx::Fast::Cache::time()
!ll&&!rl&&r
14151
MC/DC100%2/2
$expires_at and $expires_at <= &DBIx::Fast::Cache::time()
$expires_at $expires_at <= &DBIx::Fast::Cache::time()
Truth table100%3/3
A and B
A= $expires_atB= $expires_at <= &DBIx::Fast::Cache::time()
ABresult
0X0
100
111
96 1 $self->_drop_key($key, $entry); # reuse the entry we just fetched
97 1 $_stats->{expirations}++;
98 1 $_stats->{misses}++;
99 1 return undef;
100 }
101  
102 29 ▶ if ($shared && @{ $entry->[2] // [] }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shared and @{$entry->[2] // [];}) 2 27 29
Condition80%4/5
$shared and @{$entry->[2] // [];}
!ll&&!rl&&r
2612
$entry->[2] // []
l!l
30
MC/DC100%2/2
$shared and @{$entry->[2] // [];}
$shared @{$entry->[2] // [];}
MC/DC0%0/1
$entry->[2] // []
$entry->[2]
Truth table100%3/3
A and B
A= $sharedB= @{$entry->[2] // [];}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $entry->[2]
Aresult
11
00
103 # Stale when any of its tags was invalidated (by any process sharing
104 # the backend) since the entry was stored.
105 2 ▶ my $versions = $entry->[3] // [];
Condition50%1/2
$entry->[3] // []
l!l
20
MC/DC0%0/1
$entry->[3] // []
$entry->[3]
Truth table50%1/2
A
A= $entry->[3]
Aresult
11
00
106 2 for my $i (0 .. $#{ $entry->[2] }) {
107 2 ▶ next if $self->_tag_version($entry->[2][$i]) == ($versions->[$i] // 0);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_tag_version($entry->[2][$i]) == ($versions->[$i] // 0) 1 1 2
Condition50%1/2
$versions->[$i] // 0
l!l
20
MC/DC0%0/1
$versions->[$i] // 0
$versions->[$i]
Truth table50%1/2
A
A= $versions->[$i]
Aresult
11
00
108 1 $_delete_cb->($key);
109 1 $_stats->{invalidations}++;
110 1 $_stats->{misses}++;
111 1 return undef;
112 }
113 }
114  
115 28 $_stats->{hits}++;
116 28 return $value;
117 5 }
118  
119 199 ▶ method set ($key, $value, %opts) {
Subroutine set: called CC=13 SCAR=25.7
Pod documented
120 199 ▶ my $ttl = exists $opts{ttl} ? $opts{ttl} : $default_ttl;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'ttl'} ? : 16 183 199
121 199 ▶ my $tags = $opts{tags} // [];
Condition100%2/2
$opts{"tags"} // []
l!l
17128
MC/DC100%1/1
$opts{"tags"} // []
$opts{"tags"}
Truth table100%2/2
A
A= $opts{"tags"}
Aresult
11
00
122 199 ▶ croak "tags must be an arrayref" unless ref $tags eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tags eq "ARRAY" 1 198 199
123  
124 198 ▶ my $expires_at = $ttl ? (time() + $ttl) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ttl ? : 28 170 198
125 198 my $entry = [$value, $expires_at, $tags];
126 # Shared mode: snapshot the tag versions with the entry; no in-process
127 # index (it would only know this process' keys).
128 198 ▶ push @$entry, [ map { $self->_tag_version($_) } @$tags ] if $shared && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
if $shared and @$tags 1 197 198
Condition100%3/3
$shared and @$tags
!ll&&!rl&&r
19071
MC/DC100%2/2
$shared and @$tags
$shared @$tags
Truth table100%3/3
A and B
A= $sharedB= @$tags
ABresult
0X0
100
111
129 198 ▶ ($_set_ttl && $ttl) ? $_store->set($key, $entry, $ttl)
Branch: 1 branch
BranchTrueFalseTotal
$_set_ttl && $ttl ? : 1 197 198
Condition100%3/3
$_set_ttl and $ttl
!ll&&!rl&&r
19251
MC/DC100%2/2
$_set_ttl and $ttl
$_set_ttl $ttl
Truth table100%3/3
A and B
A= $_set_ttlB= $ttl
ABresult
0X0
100
111
130 : $_store->set($key, $entry);
131  
132 198 ▶ if ($shared) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shared) 8 190 198
133 8 $_stats->{sets}++;
134 8 return $value;
135 }
136  
137 190 for my $tag (@$tags) {
138 171 ▶ $_index_pairs++ unless exists $_tag_index->{$tag}{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $_tag_index->{$tag}{$key} 171 0 171
139 171 $_tag_index->{$tag}{$key} = 1;
140 }
141  
142 190 ▶ $self->_sweep_index if $_index_pairs > $_index_watermark;
Branch: 1 branch
BranchTrueFalseTotal
if $_index_pairs > $_index_watermark 8 182 190
143  
144 190 $_stats->{sets}++;
145 190 return $value;
146 5 }
147  
148 # The backend evicts silently (LRU), so dead keys pile up in the tag index
149 # of long-lived workers whose tags are never invalidated. Sweep when the
150 # index outgrows the watermark: drop every indexed key the backend no longer
151 # holds. One backend get per key, and only when the index has grown to 4x
152 # the cache capacity, so the amortized cost per set is negligible.
153 8 ▶ method _sweep_index () {
Subroutine _sweep_index: called CC=7 SCAR=19.5
154 8 for my $tag (keys %$_tag_index) {
155 88 ▶ my $bucket = $_tag_index->{$tag} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $bucket = $_tag_index->{$tag} or next 88 0 88
156 88 for my $key (keys %$bucket) {
157 136 ▶ next if defined $_store->get($key);
Branch: 1 branch
BranchTrueFalseTotal
if defined $_store->get($key) 32 104 136
158 104 delete $bucket->{$key};
159 104 $_index_pairs--;
160 104 $_stats->{evictions}++;
161 }
162 88 ▶ delete $_tag_index->{$tag} unless %$bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless %$bucket 62 26 88
163 }
164 # Keys legitimately carrying many tags can keep the index above the static
165 # threshold; leave headroom over the live size so the sweep cannot thrash.
166 8 $_index_watermark = 4 * $max_size;
167 8 ▶ $_index_watermark = 2 * $_index_pairs
Branch: 1 branch
BranchTrueFalseTotal
if 2 * $_index_pairs > $_index_watermark 0 8 8
168 if 2 * $_index_pairs > $_index_watermark;
169 5 }
170  
171 3 ▶ method delete ($key) {
Subroutine delete: called CC=2 SCAR=6.9
Pod documented
172 3 ▶ $_stats->{invalidations}++ if defined $self->_drop_key($key);
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->_drop_key($key) 2 1 3
173 5 }
174  
175 # Invalidate every key tagged with $tag. Each key is dropped through
176 # _drop_key so it is pruned from ALL of its tag buckets, not just $tag -
177 # otherwise a multi-tagged key would leave dangling references in its other
178 # buckets forever.
179 #
180 # Shared mode bumps the tag's version in the backend instead: every entry
181 # stored under the old version - by ANY process sharing the backend - reads
182 # as a miss from then on. Returns 1 (how many keys that hits is unknown).
183 18 ▶ method invalidate ($tag) {
Subroutine invalidate: called CC=8 SCAR=20.8
Pod documented
184 18 ▶ if ($shared) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shared) 1 17 18
185 1 my $vkey = _version_key($tag);
186 1 ▶ if ($_store->can('incr')) { $_store->incr($vkey) }
Branch: 1 branch
BranchTrueFalseTotal
if ($_store->can('incr')) { } 0 1 1
187 1 else { $_store->set($vkey, $self->_tag_version($tag) + 1) }
188 1 $_stats->{invalidations}++;
189 1 return 1;
190 }
191 17 ▶ my $keys = delete $_tag_index->{$tag} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $keys = delete $_tag_index->{$tag} or return 0 11 6 17
192 11 $_index_pairs -= scalar keys %$keys; # this tag's pairs went with the bucket
193 11 my $n = 0;
194 11 my $now = time();
195 11 for my $key (keys %$keys) {
196 # Count what actually happened: a key the backend already dropped is a
197 # detected eviction, a logically-expired one an expiration - neither is
198 # an invalidation (the count would be inflated far beyond what the store
199 # holds). Pass the fetched entry down so _drop_key doesn't hit the
200 # backend a second time.
201 19 my $entry = $_store->get($key);
202 19 $self->_drop_key($key, $entry);
203 19 ▶ if (!defined $entry) { $_stats->{evictions}++ }
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $entry) { } 6 13 19
elsif ($entry->[1] and $entry->[1] <= $now) { } 1 12 13
204 1 ▶ elsif ($entry->[1] && $entry->[1] <= $now) { $_stats->{expirations}++ }
Condition100%3/3
$entry->[1] and $entry->[1] <= $now
!ll&&!rl&&r
661
MC/DC100%2/2
$entry->[1] and $entry->[1] <= $now
$entry->[1] $entry->[1] <= $now
Truth table100%3/3
A and B
A= $entry->[1]B= $entry->[1] <= $now
ABresult
0X0
100
111
205 12 else { $n++ }
206 }
207 11 $_stats->{invalidations} += $n;
208 11 return $n;
209 5 }
210  
211 # Tag versions live in the backend under a reserved key.
212 5 ▶ sub _version_key ($tag) { "\0dbixfast-tagver\0$tag" }
Subroutine _version_key: called CC=1 SCAR=0.0
213  
214 4 ▶ method _tag_version ($tag) {
Subroutine _tag_version: called CC=3 SCAR=11.0
215 4 my $v = $_store->get(_version_key($tag));
216 4 ▶ return defined $v && !ref $v ? $v : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $v && !ref($v) ? : 1 3 4
Condition66%2/3
defined $v and not ref $v
!ll&&!rl&&r
301
MC/DC50%1/2
defined $v and not ref $v
defined $v not ref $v
Truth table66%2/3
A and not(B)
A= defined $vB= not ref $v
ABresult
0X0
100
111
217 5 }
218  
219 13 ▶ method clear () {
Subroutine clear: called CC=1 SCAR=0.0
Pod documented
220 13 $_store->clear;
221 13 $_tag_index = {};
222 13 $_index_pairs = 0;
223 13 $_stats->{invalidations}++;
224 5 }
225  
226 24 ▶ method stats () {
Subroutine stats: called CC=2 SCAR=6.9
Pod documented
227 24 my $total = $_stats->{hits} + $_stats->{misses};
228 return {
229 %$_stats,
230 total => $total,
231 24 ▶ hit_ratio => $total ? $_stats->{hits} / $total : 0,
Branch: 1 branch
BranchTrueFalseTotal
$total ? : 20 4 24
232 index_pairs => $_index_pairs,
233 };
234 5 }
235  
236 12 ▶ method reset_stats () {
Subroutine reset_stats: called CC=2 SCAR=6.9
Pod documented
237 12 $_stats->{$_} = 0 for keys %$_stats;
238 5 }
239  
240 # Cheap, stable key builder used by DBIx::Fast::cached() proxies.
241 # Avoid hashing the bind values into a serialized blob - just join.
242 51 ▶ method build_key ($sql, $params = []) {
Subroutine build_key: called CC=4 SCAR=13.9
Pod documented
243 # Length-prefix every component so the encoding is injective: a separator
244 # or NUL byte inside a bind value can no longer collide with a different
245 # parameter tuple, and undef is encoded out-of-band ('|U') so no string
246 # value can forge it.
247 51 my $key = length($sql) . ':' . $sql;
248 51 for my $param (@$params) {
249 36 ▶ $key .= defined $param ? ('|' . length($param) . ':' . $param) : '|U';
Branch: 1 branch
BranchTrueFalseTotal
defined $param ? : 34 2 36
250 }
251 51 return $key;
252 5 }
253  
254 # Internal: remove a key from backend + tag index. Returns the entry that
255 # was dropped (undef when the backend no longer held the key).
256 23 ▶ method _drop_key ($key, $entry = undef) {
Subroutine _drop_key: called CC=9 SCAR=22.1
257 23 ▶ $entry //= $_store->get($key);
Condition100%3/3
$entry //= $_store->get($key)
l!l&&r!l&&!r
1427
MC/DC100%2/2
$entry //= $_store->get($key)
$entry $_store->get($key)
Truth table100%3/3
A //= B
A= $entryB= $_store->get($key)
ABresult
1X1
011
000
258 23 ▶ if ($entry && ref $entry->[2] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry and ref $entry->[2] eq "ARRAY") 16 7 23
Condition66%2/3
$entry and ref $entry->[2] eq "ARRAY"
!ll&&!rl&&r
7016
MC/DC50%1/2
$entry and ref $entry->[2] eq "ARRAY"
$entry ref $entry->[2] eq "ARRAY"
Truth table66%2/3
A and B
A= $entryB= ref $entry->[2] eq "ARRAY"
ABresult
0X0
100
111
259 16 for my $tag (@{$entry->[2]}) {
260 15 ▶ $_index_pairs-- if delete $_tag_index->{$tag}{$key};
Branch: 1 branch
BranchTrueFalseTotal
if delete $_tag_index->{$tag}{$key} 2 13 15
261 15 ▶ delete $_tag_index->{$tag} unless %{$_tag_index->{$tag} // {}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$_tag_index->{$tag} // {};} 15 0 15
Condition50%1/2
$_tag_index->{$tag} // {}
l!l
150
MC/DC0%0/1
$_tag_index->{$tag} // {}
$_tag_index->{$tag}
Truth table50%1/2
A
A= $_tag_index->{$tag}
Aresult
11
00
262 }
263 }
264 23 $_delete_cb->($key);
265 23 return $entry;
266 5 }
267 }
268  
269 5 1;
270  
271 __END__
« Fast/Schema.pm ↑ Summary Fast/Cached.pm »