Fast/Cache.pm

filter: Statementstmt 97.3% 145 / 149 Branchbran 90.4% 38 / 42 Conditioncond 89.4% 17 / 19 MC/DCmcdc 83.3% 10 / 12 Subroutinesub 88.2% 15 / 17 Podpod 100% 11 / 11 totaltotal 94.4% 236 / 250 CC 38 SCAR 17.8
CC
38
Cov
95%
set
10.0
_drop_key
9.1
_sweep_index
7.0
CRAP 5.9
« Fast/Schema.pm ↑ Summary Fast/Profiler.pm »
1 package DBIx::Fast::Cache;
2  
3 3 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 our $VERSION = '0.20';
7 3 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶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  
24 1 ▶ field $_store; # backend instance
Subroutine backend: called CC=1 SCAR=0.0
Pod documented
25 3 field $_delete_cb; # closure mapping to the backend's delete/remove
26 3 field $_set_ttl; # backend set() accepts a TTL third arg (CHI)
27 field $_tag_index = {}; # tag => { key => 1 }
28 3 field $_index_pairs = 0; # live key-tag pairs in $_tag_index
29 3 field $_index_watermark; # sweep threshold (see _sweep_index)
30 field $_stats = {
31 hits => 0,
32 misses => 0,
33 sets => 0,
34 evictions => 0,
35 expirations => 0,
36 invalidations => 0,
37 };
38  
39 3 ADJUST {
40 if (ref $backend) {
41 # Pre-built backend object (duck-typed: must respond to get/set
42 # and one of delete/remove, plus clear).
43 $_store = $backend;
44 }
45 elsif ($backend eq 'LRU') {
46 require LRU::Cache;
47 $_store = LRU::Cache->new($max_size);
48 }
49 elsif ($backend eq 'CHI') {
50 croak "CHI backend requires a pre-built CHI object passed as backend";
51 }
52 else {
53 croak "Unknown cache backend: $backend";
54 }
55  
56 # Normalize delete API across backends. CHI calls it `remove`,
57 # LRU::Cache calls it `delete`. Resolved once at construction.
58 if ($_store->can('delete')) {
59 $_delete_cb = sub { $_store->delete($_[0]) };
60 }
61 elsif ($_store->can('remove')) {
62 $_delete_cb = sub { $_store->remove($_[0]) };
63 }
64 else {
65 croak "Cache backend ", ref($_store),
66 " supports neither delete() nor remove()";
67 }
68  
69 # CHI-like backends accept a TTL on set(): push ours down so the external
70 # store (Redis/Memcached) also expires entries physically, instead of
71 # holding logically-expired data until eviction.
72 $_set_ttl = $_store->isa('CHI::Driver');
73  
74 # The tag index is pruned lazily; sweep when it outgrows this many
75 # key-tag pairs (see _sweep_index).
76 $_index_watermark = 4 * $max_size;
77 }
78  
79 64 ▶ method get ($key) {
Subroutine get: called CC=4 SCAR=13.9
Pod documented
80 64 my $entry = $_store->get($key);
81 64 ▶ unless (defined $entry) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 35 29 64
82 35 $_stats->{misses}++;
83 35 return undef;
84 }
85  
86 # entry = [$value, $expires_at, \@tags]
87 29 my ($value, $expires_at) = @$entry;
88  
89 29 ▶ if ($expires_at && $expires_at <= time()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expires_at and $expires_at <= &DBIx::Fast::Cache::time()) 1 28 29
Condition100%3/3
$expires_at and $expires_at <= &DBIx::Fast::Cache::time()
!ll&&!rl&&r
13151
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
90 1 $self->_drop_key($key, $entry); # reuse the entry we just fetched
91 1 $_stats->{expirations}++;
92 1 $_stats->{misses}++;
93 1 return undef;
94 }
95  
96 28 $_stats->{hits}++;
97 28 return $value;
98 3 }
99  
100 197 ▶ method set ($key, $value, %opts) {
Subroutine set: called CC=10 SCAR=23.0
Pod documented
101 197 ▶ my $ttl = exists $opts{ttl} ? $opts{ttl} : $default_ttl;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'ttl'} ? : 16 181 197
102 197 ▶ my $tags = $opts{tags} // [];
Condition100%2/2
$opts{"tags"} // []
l!l
17126
MC/DC100%1/1
$opts{"tags"} // []
$opts{"tags"}
Truth table100%2/2
A
A= $opts{"tags"}
Aresult
11
00
103 197 ▶ croak "tags must be an arrayref" unless ref $tags eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tags eq "ARRAY" 1 196 197
104  
105 196 ▶ my $expires_at = $ttl ? (time() + $ttl) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ttl ? : 26 170 196
106 196 my $entry = [$value, $expires_at, $tags];
107 196 ▶ ($_set_ttl && $ttl) ? $_store->set($key, $entry, $ttl)
Branch: 1 branch
BranchTrueFalseTotal
$_set_ttl && $ttl ? : 1 195 196
Condition100%3/3
$_set_ttl and $ttl
!ll&&!rl&&r
19051
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
108 : $_store->set($key, $entry);
109  
110 196 for my $tag (@$tags) {
111 172 ▶ $_index_pairs++ unless exists $_tag_index->{$tag}{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $_tag_index->{$tag}{$key} 172 0 172
112 172 $_tag_index->{$tag}{$key} = 1;
113 }
114  
115 196 ▶ $self->_sweep_index if $_index_pairs > $_index_watermark;
Branch: 1 branch
BranchTrueFalseTotal
if $_index_pairs > $_index_watermark 8 188 196
116  
117 196 $_stats->{sets}++;
118 196 return $value;
119 3 }
120  
121 # The backend evicts silently (LRU), so dead keys pile up in the tag index
122 # of long-lived workers whose tags are never invalidated. Sweep when the
123 # index outgrows the watermark: drop every indexed key the backend no longer
124 # holds. One backend get per key, and only when the index has grown to 4x
125 # the cache capacity, so the amortized cost per set is negligible.
126 8 ▶ method _sweep_index () {
Subroutine _sweep_index: called CC=7 SCAR=19.5
127 8 for my $tag (keys %$_tag_index) {
128 88 ▶ my $bucket = $_tag_index->{$tag} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $bucket = $_tag_index->{$tag} or next 88 0 88
129 88 for my $key (keys %$bucket) {
130 136 ▶ next if defined $_store->get($key);
Branch: 1 branch
BranchTrueFalseTotal
if defined $_store->get($key) 32 104 136
131 104 delete $bucket->{$key};
132 104 $_index_pairs--;
133 104 $_stats->{evictions}++;
134 }
135 88 ▶ delete $_tag_index->{$tag} unless %$bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless %$bucket 62 26 88
136 }
137 # Keys legitimately carrying many tags can keep the index above the static
138 # threshold; leave headroom over the live size so the sweep cannot thrash.
139 8 $_index_watermark = 4 * $max_size;
140 8 ▶ $_index_watermark = 2 * $_index_pairs
Branch: 1 branch
BranchTrueFalseTotal
if 2 * $_index_pairs > $_index_watermark 0 8 8
141 if 2 * $_index_pairs > $_index_watermark;
142 3 }
143  
144 3 ▶ method delete ($key) {
Subroutine delete: called CC=2 SCAR=6.9
Pod documented
145 3 ▶ $_stats->{invalidations}++ if defined $self->_drop_key($key);
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->_drop_key($key) 2 1 3
146 3 }
147  
148 # Invalidate every key tagged with $tag. Each key is dropped through
149 # _drop_key so it is pruned from ALL of its tag buckets, not just $tag -
150 # otherwise a multi-tagged key would leave dangling references in its other
151 # buckets forever.
152 18 ▶ method invalidate ($tag) {
Subroutine invalidate: called CC=6 SCAR=17.9
Pod documented
153 18 ▶ my $keys = delete $_tag_index->{$tag} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $keys = delete $_tag_index->{$tag} or return 0 12 6 18
154 12 $_index_pairs -= scalar keys %$keys; # this tag's pairs went with the bucket
155 12 my $n = 0;
156 12 my $now = time();
157 12 for my $key (keys %$keys) {
158 # Count what actually happened: a key the backend already dropped is a
159 # detected eviction, a logically-expired one an expiration - neither is
160 # an invalidation (the count would be inflated far beyond what the store
161 # holds). Pass the fetched entry down so _drop_key doesn't hit the
162 # backend a second time.
163 20 my $entry = $_store->get($key);
164 20 $self->_drop_key($key, $entry);
165 20 ▶ if (!defined $entry) { $_stats->{evictions}++ }
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $entry) { } 6 14 20
elsif ($entry->[1] and $entry->[1] <= $now) { } 1 13 14
166 1 ▶ elsif ($entry->[1] && $entry->[1] <= $now) { $_stats->{expirations}++ }
Condition100%3/3
$entry->[1] and $entry->[1] <= $now
!ll&&!rl&&r
761
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
167 13 else { $n++ }
168 }
169 12 $_stats->{invalidations} += $n;
170 12 return $n;
171 3 }
172  
173 13 ▶ method clear () {
Subroutine clear: called CC=1 SCAR=0.0
Pod documented
174 13 $_store->clear;
175 13 $_tag_index = {};
176 13 $_index_pairs = 0;
177 13 $_stats->{invalidations}++;
178 3 }
179  
180 24 ▶ method stats () {
Subroutine stats: called CC=2 SCAR=6.9
Pod documented
181 24 my $total = $_stats->{hits} + $_stats->{misses};
182 return {
183 %$_stats,
184 total => $total,
185 24 ▶ hit_ratio => $total ? $_stats->{hits} / $total : 0,
Branch: 1 branch
BranchTrueFalseTotal
$total ? : 20 4 24
186 index_pairs => $_index_pairs,
187 };
188 3 }
189  
190 12 ▶ method reset_stats () {
Subroutine reset_stats: called CC=2 SCAR=6.9
Pod documented
191 12 $_stats->{$_} = 0 for keys %$_stats;
192 3 }
193  
194 # Cheap, stable key builder used by DBIx::Fast::cached() proxies.
195 # Avoid hashing the bind values into a serialized blob - just join.
196 49 ▶ method build_key ($sql, $params = []) {
Subroutine build_key: called CC=4 SCAR=13.9
Pod documented
197 # Length-prefix every component so the encoding is injective: a separator
198 # or NUL byte inside a bind value can no longer collide with a different
199 # parameter tuple, and undef is encoded out-of-band ('|U') so no string
200 # value can forge it.
201 49 my $key = length($sql) . ':' . $sql;
202 49 for my $param (@$params) {
203 36 ▶ $key .= defined $param ? ('|' . length($param) . ':' . $param) : '|U';
Branch: 1 branch
BranchTrueFalseTotal
defined $param ? : 34 2 36
204 }
205 49 return $key;
206 3 }
207  
208 # Internal: remove a key from backend + tag index. Returns the entry that
209 # was dropped (undef when the backend no longer held the key).
210 24 ▶ method _drop_key ($key, $entry = undef) {
Subroutine _drop_key: called CC=9 SCAR=22.1
211 24 ▶ $entry //= $_store->get($key);
Condition100%3/3
$entry //= $_store->get($key)
l!l&&r!l&&!r
1527
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
212 24 ▶ if ($entry && ref $entry->[2] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry and ref $entry->[2] eq "ARRAY") 17 7 24
Condition66%2/3
$entry and ref $entry->[2] eq "ARRAY"
!ll&&!rl&&r
7017
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
213 17 for my $tag (@{$entry->[2]}) {
214 16 ▶ $_index_pairs-- if delete $_tag_index->{$tag}{$key};
Branch: 1 branch
BranchTrueFalseTotal
if delete $_tag_index->{$tag}{$key} 2 14 16
215 16 ▶ delete $_tag_index->{$tag} unless %{$_tag_index->{$tag} // {}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$_tag_index->{$tag} // {};} 16 0 16
Condition50%1/2
$_tag_index->{$tag} // {}
l!l
160
MC/DC0%0/1
$_tag_index->{$tag} // {}
$_tag_index->{$tag}
Truth table50%1/2
A
A= $_tag_index->{$tag}
Aresult
11
00
216 }
217 }
218 24 $_delete_cb->($key);
219 24 return $entry;
220 3 }
221 }
222  
223 3 1;
224  
225 __END__
« Fast/Schema.pm ↑ Summary Fast/Profiler.pm »