Fast/Cache.pm

filter: Statementstmt 97.2% 177 / 182 Branchbran 91.0% 51 / 56 Conditioncond 82.3% 28 / 34 MC/DCmcdc 71.4% 15 / 21 Subroutinesub 90.0% 18 / 20 Podpod 100% 12 / 12 totaltotal 92.6% 301 / 325 CC 52 SCAR 20.2
CC
52
Cov
94%
set
13.0
get
11.0
_drop_key
9.1
CRAP 7.5
« Fast/Schema.pm ↑ Summary Fast/Profiler.pm »
1 package DBIx::Fast::Cache;
2  
3 6 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 6 our $VERSION = '0.22';
7 6 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶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 2 ▶ field $_store; # backend instance
Subroutine shared: called CC=1 SCAR=0.0
Pod documented
29 6 field $_delete_cb; # closure mapping to the backend's delete/remove
30 6 field $_set_ttl; # backend set() accepts a TTL third arg (CHI)
31 field $_tag_index = {}; # tag => { key => 1 }
32 6 field $_index_pairs = 0; # live key-tag pairs in $_tag_index
33 6 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 6 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 71 ▶ method get ($key) {
Subroutine get: called CC=11 SCAR=24.0
Pod documented
86 71 my $entry = $_store->get($key);
87 71 ▶ unless (defined $entry) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 38 33 71
88 38 $_stats->{misses}++;
89 38 return undef;
90 }
91  
92 # entry = [$value, $expires_at, \@tags (, \@tag_versions when shared)]
93 33 my ($value, $expires_at) = @$entry;
94  
95 33 ▶ if ($expires_at && $expires_at <= time()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expires_at and $expires_at <= &DBIx::Fast::Cache::time()) 1 32 33
Condition100%3/3
$expires_at and $expires_at <= &DBIx::Fast::Cache::time()
!ll&&!rl&&r
14181
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 32 ▶ if ($shared && @{ $entry->[2] // [] }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shared and @{$entry->[2] // [];}) 5 27 32
Condition80%4/5
$shared and @{$entry->[2] // [];}
!ll&&!rl&&r
2615
$entry->[2] // []
l!l
60
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 5 ▶ my $versions = $entry->[3] // [];
Condition50%1/2
$entry->[3] // []
l!l
50
MC/DC0%0/1
$entry->[3] // []
$entry->[3]
Truth table50%1/2
A
A= $entry->[3]
Aresult
11
00
106 5 for my $i (0 .. $#{ $entry->[2] }) {
107 5 ▶ 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) 3 2 5
Condition50%1/2
$versions->[$i] // 0
l!l
50
MC/DC0%0/1
$versions->[$i] // 0
$versions->[$i]
Truth table50%1/2
A
A= $versions->[$i]
Aresult
11
00
108 2 $_delete_cb->($key);
109 2 $_stats->{invalidations}++;
110 2 $_stats->{misses}++;
111 2 return undef;
112 }
113 }
114  
115 30 $_stats->{hits}++;
116 30 return $value;
117 6 }
118  
119 202 ▶ method set ($key, $value, %opts) {
Subroutine set: called CC=13 SCAR=25.7
Pod documented
120 202 ▶ my $ttl = exists $opts{ttl} ? $opts{ttl} : $default_ttl;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'ttl'} ? : 16 186 202
121 202 ▶ my $tags = $opts{tags} // [];
Condition100%2/2
$opts{"tags"} // []
l!l
17428
MC/DC100%1/1
$opts{"tags"} // []
$opts{"tags"}
Truth table100%2/2
A
A= $opts{"tags"}
Aresult
11
00
122 202 ▶ croak "tags must be an arrayref" unless ref $tags eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tags eq "ARRAY" 1 201 202
123  
124 201 ▶ my $expires_at = $ttl ? (time() + $ttl) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ttl ? : 31 170 201
125 201 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 201 ▶ push @$entry, [ map { $self->_tag_version($_) } @$tags ] if $shared && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
if $shared and @$tags 4 197 201
Condition100%3/3
$shared and @$tags
!ll&&!rl&&r
19074
MC/DC100%2/2
$shared and @$tags
$shared @$tags
Truth table100%3/3
A and B
A= $sharedB= @$tags
ABresult
0X0
100
111
129 201 ▶ ($_set_ttl && $ttl) ? $_store->set($key, $entry, $ttl)
Branch: 1 branch
BranchTrueFalseTotal
$_set_ttl && $ttl ? : 4 197 201
Condition100%3/3
$_set_ttl and $ttl
!ll&&!rl&&r
19254
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 201 ▶ if ($shared) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shared) 11 190 201
133 11 $_stats->{sets}++;
134 11 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 6 }
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 6 }
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 6 }
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 19 ▶ method invalidate ($tag) {
Subroutine invalidate: called CC=8 SCAR=20.8
Pod documented
184 19 ▶ if ($shared) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shared) 2 17 19
185 2 my $vkey = _version_key($tag);
186 0 ▶ if ($_store->can('incr')) { $_store->incr($vkey) }
Branch: 1 branch
BranchTrueFalseTotal
if ($_store->can('incr')) { } 0 2 2
187 2 else { $_store->set($vkey, $self->_tag_version($tag) + 1) }
188 2 $_stats->{invalidations}++;
189 2 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 6 }
210  
211 # Tag versions live in the backend under a reserved key.
212 13 ▶ sub _version_key ($tag) { "\0dbixfast-tagver\0$tag" }
Subroutine _version_key: called CC=1 SCAR=0.0
213  
214 11 ▶ method _tag_version ($tag) {
Subroutine _tag_version: called CC=3 SCAR=11.0
215 11 my $v = $_store->get(_version_key($tag));
216 11 ▶ return defined $v && !ref $v ? $v : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $v && !ref($v) ? : 4 7 11
Condition66%2/3
defined $v and not ref $v
!ll&&!rl&&r
704
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 6 }
218  
219 16 ▶ method clear () {
Subroutine clear: called CC=1 SCAR=0.0
Pod documented
220 16 $_store->clear;
221 16 $_tag_index = {};
222 16 $_index_pairs = 0;
223 16 $_stats->{invalidations}++;
224 6 }
225  
226 25 ▶ method stats () {
Subroutine stats: called CC=2 SCAR=6.9
Pod documented
227 25 my $total = $_stats->{hits} + $_stats->{misses};
228 return {
229 %$_stats,
230 total => $total,
231 25 ▶ hit_ratio => $total ? $_stats->{hits} / $total : 0,
Branch: 1 branch
BranchTrueFalseTotal
$total ? : 21 4 25
232 index_pairs => $_index_pairs,
233 };
234 6 }
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 6 }
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 56 ▶ 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 56 my $key = length($sql) . ':' . $sql;
248 56 for my $param (@$params) {
249 36 ▶ $key .= defined $param ? ('|' . length($param) . ':' . $param) : '|U';
Branch: 1 branch
BranchTrueFalseTotal
defined $param ? : 34 2 36
250 }
251 56 return $key;
252 6 }
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 6 }
267 }
268  
269 6 1;
270  
271 __END__
« Fast/Schema.pm ↑ Summary Fast/Profiler.pm »