Redis/Cluster.pm

filter: Statementstmt 47.2% 59 / 125 Branchbran 7.1% 1 / 14 Conditioncond 25.0% 2 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 54.5% 18 / 33 Podpod 40.0% 4 / 10 totaltotal 43.0% 84 / 195 CC 15 SCAR 18.9
CC
15
Cov
42%
execute_command
30.0
replace_nodes
12.0
__ANON__
12.0
CRAP 6.6
« Redis/Subscription.pm ↑ Summary job-queue.pl »
1 package Net::Async::Redis::Cluster;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 3 use parent qw(
9 Net::Async::Redis::Commands
10 IO::Async::Notifier
11 3 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 3 our $VERSION = '2.004_001'; # TRIAL VERSION
14  
15 =encoding utf8
16  
17 =head1 NAME
18  
19 Net::Async::Redis::Cluster - support for cluster routing
20  
21 =head1 SYNOPSIS
22  
23 use IO::Async::Loop;
24 use Net::Async::Redis::Cluster;
25 my $loop = IO::Async::Loop->new;
26 $loop->add(
27 my $cluster = Net::Async::Redis::Cluster->new(
28 )
29 );
30 await $cluster->bootstrap(
31 host => 'redis.local',
32 );
33 print "Key: " . await $cluster->get('some_key');
34  
35 =head1 DESCRIPTION
36  
37 Provides access to a Redis cluster.
38  
39 Usage is similar to L<Net::Async::Redis> with the addition of a L</bootstrap>
40 step to find the initial client nodes:
41  
42 $loop->add(
43 my $cluster = Net::Async::Redis::Cluster->new(
44 )
45 );
46 await $cluster->bootstrap(
47 host => 'redis.local',
48 );
49 print "Key: " . await $cluster->get('some_key');
50  
51 Note that this adds some overhead to lookups, so you may be better served
52 by options such as the L<https://github.com/twitter/twemproxy|twemproxy>
53 proxy routing dæmon, or a service mesh such as L<https://istio.io/|istio>.
54  
55 =cut
56  
57 3 ▶no indirect;
Subroutine BEGIN: called CC=1 SCAR=0.0
58 3 ▶use Syntax::Keyword::Try;
Subroutine BEGIN: called CC=1 SCAR=0.0
59 3 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 3 ▶use List::BinarySearch::XS qw(binsearch);
Subroutine BEGIN: called CC=1 SCAR=0.0
61 3 ▶use List::UtilsBy qw(nsort_by);
Subroutine BEGIN: called CC=1 SCAR=0.0
62 3 ▶use List::Util qw(first);
Subroutine BEGIN: called CC=1 SCAR=0.0
63 3 ▶use Digest::CRC qw(crc);
Subroutine BEGIN: called CC=1 SCAR=0.0
64  
65 3 ▶use Log::Any qw($log);
Subroutine BEGIN: called CC=1 SCAR=0.0
66  
67 3 ▶use Net::Async::Redis;
Subroutine BEGIN: called CC=1 SCAR=0.0
68 3 ▶use Net::Async::Redis::Cluster::Node;
Subroutine BEGIN: called CC=1 SCAR=0.0
69  
70 use overload
71 0 ▶ '""' => sub { 'NaRedis::Cluster[]' },
Subroutine __ANON__: not called CC=1 SCAR=6.9
72 0 ▶ bool => sub { 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
73 3 ▶ fallback => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
74  
75 3 ▶use constant MAX_SLOTS => 16384;
Subroutine BEGIN: called CC=1 SCAR=0.0
76  
77 BEGIN {
78 # It's unlikely that MAX_SLOTS would ever need
79 # to change, but it's also important that if we do change it,
80 # our bitwise-AND still makes sense in context, i.e. this
81 # must always be a power of 2.
82 3 ▶ die 'invalid MAX_SLOTS' unless 1 == unpack(
Subroutine BEGIN: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
unless 1 == unpack("b*", "\0\0\@\0") =~ tr/1// 0 3 3
83 "b*" => pack(
84 N1 => MAX_SLOTS
85 )
86 ) =~ tr/1/1/;
87 }
88  
89 =head1 METHODS
90  
91 =head2 bootstrap
92  
93 Connects to a Redis server and attempts to discover the cluster node configuration.
94  
95 Usage:
96  
97 try {
98 await $cluster->bootstrap(
99 host => 'redis-primary.local',
100 port => 6379,
101 );
102 } catch {
103 $log->errorf('Unable to bootstrap the Redis cluster: %s', $@);
104 }
105  
106 =cut
107  
108 0 ▶async sub bootstrap {
Subroutine bootstrap: not called CC=1 SCAR=5.1
109 0 my ($self, %args) = @_;
110 0 my $redis;
111 try {
112 $self->add_child(
113 $redis = Net::Async::Redis->new(
114 host => $args{host},
115 port => $args{port},
116 )
117 0 );
118 0 await $redis->connect;
119 0 await $self->apply_slots_from_instance($redis);
120 } finally {
121 $redis->remove_from_parent if $redis;
122 }
123 0 }
124  
125 =head2 hash_slot_for_key
126  
127 Calculates the CRC16 hash slot for the given key.
128  
129 Note that keys are expected as bytestrings, if you have a Unicode string
130 you'd likely want to convert to UTF-8 first.
131  
132 =cut
133  
134 sub hash_slot_for_key {
135 3 ▶ my ($self, $key) = @_;
Subroutine hash_slot_for_key: called CC=2 SCAR=7.0
Pod documented
136 # Extract out the first non-zero-length substring between the first {} character pair,
137 # if any...
138 3 my ($hash_string) = $key =~ /^[^\{]*\{([^\}]+)\}/;
139 # ... and if we don't have any matching substrings, we just use the full key
140 3 ▶ $hash_string //= $key;
Condition66%2/3
$hash_string //= $key
l!l&&r!l&&!r
120
MC/DC0%0/2
$hash_string //= $key
$hash_string $key
Truth table66%2/3
A //= B
A= $hash_stringB= $key
ABresult
1X1
011
000
141 # see Digest::CRC docs and the XMODEM protocol for more details, but essentially:
142 # input, width=16, init=0, xor constant for output = 0, reflect output = 0, polynomial = 0x1021,
143 # reflect input = 0, continuation = 0
144 3 return crc($hash_string, 16, 0, 0, 0, 0x1021, 0, 0) & (MAX_SLOTS - 1);
145 }
146  
147 =head2 replace_nodes
148  
149 Swap the existing node configuration out for a new arrayref of nodes.
150  
151 =cut
152  
153 sub replace_nodes {
154 0 ▶ my ($self, $nodes) = @_;
Subroutine replace_nodes: not called CC=3 SCAR=24.8
Pod documented
155 0 delete $self->{slot_cache};
156 0 $_->remove_from_parent for splice $self->{nodes}->@*;
157 0 $self->add_child($_) for $nodes->@*;
158 0 $self->{nodes} = $nodes;
159 0 $self
160 }
161  
162 =head2 node_list
163  
164 Returns a list of the currently-configured nodes.
165  
166 =cut
167  
168 0 ▶sub node_list { shift->{nodes}->@* }
Subroutine node_list: not called CC=1 SCAR=6.9
Pod documented
169  
170 sub slot_cache {
171 0 ▶ my ($self) = @_;
Subroutine slot_cache: not called CC=2 SCAR=17.9
Pod undocumented
172 0 ▶ $self->{slot_cache} //= [ (undef) x MAX_SLOTS ];
Condition0%0/2
$self->{"slot_cache"} //= [(undef) x 16384]
l!l
00
MC/DC0%0/1
$self->{"slot_cache"} //= [(undef) x 16384]
$self->{"slot_cache"}
Truth table0%0/2
A
A= $self->{"slot_cache"}
Aresult
11
00
173 }
174  
175 =head2 node_for_slot
176  
177 Returns the appropriate L<Net::Async::Redis::Cluster::Node|node> for the given hash key (slot).
178  
179 =cut
180  
181 sub node_for_slot {
182 0 ▶ my ($self, $slot) = @_;
Subroutine node_for_slot: not called CC=2 SCAR=17.9
Pod documented
183 0 ▶ return $self->slot_cache->[$slot & (MAX_SLOTS - 1)] //= do {
Condition0%0/3
$self->slot_cache->[$slot & 16383] //= do { my(@nodes) = @{$self->{"nodes"}}; my $idx = &binsearch(sub { $a < $b->start ? -1 : ($a > $b->end ? 1 : 0); } , $slot, \@nodes); $nodes[$idx] }
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->slot_cache->[$slot & 16383] //= do { my(@nodes) = @{$self->{"nodes"}}; my $idx = &binsearch(sub { $a < $b->start ? -1 : ($a > $b->end ? 1 : 0); } , $slot, \@nodes); $nodes[$idx] }
$self->slot_cache->[$slot & 16383] do { my(@nodes) = @{$self->{"nodes"}}; my $idx = &binsearch(sub { $a < $b->start ? -1 : ($a > $b->end ? 1 : 0); } , $slot, \@nodes); $nodes[$idx] }
Truth table0%0/3
A //= B
A= $self->slot_cache->[$slot & 16383]B= do { my(@nodes) = @{$self->{"nodes"}}; my $idx = &binsearch(sub { $a < $b->start ? -1 : ($a > $b->end ? 1 : 0); } , $slot, \@nodes); $nodes[$idx] }
ABresult
1X1
011
000
184 0 my @nodes = $self->{nodes}->@*;
185 my $idx = binsearch {
186 0 ▶ $a < $b->start
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 2 branches
BranchTrueFalseTotal
$a < $b->start ? : 0 0 0
$a > $b->end ? : 0 0 0
187 ? -1
188 : $a > $b->end
189 ? 1
190 :0
191 0 } $slot, @nodes;
192 0 $nodes[$idx]
193 };
194 }
195  
196 0 ▶async sub connection_for_slot {
Subroutine connection_for_slot: not called CC=2 SCAR=17.9
Pod undocumented
197 0 my ($self, $slot) = @_;
198 0 ▶ my $node = $self->node_for_slot($slot) or die 'no node found for slot';
Branch: 1 branch
BranchTrueFalseTotal
my $node = $self->node_for_slot($slot) or die "no node found for slot" 0 0 0
199 0 return await $node->primary_connection;
200 3 }
201  
202 sub node_by_host_port {
203 0 ▶ my ($self, $host, $port) = @_;
Subroutine node_by_host_port: not called CC=1 SCAR=6.9
Pod undocumented
204 0 my $host_port = join ':', $host, $port;
205 0 ▶ my ($node) = first { $host_port eq $_->host_port } $self->{nodes}->@*;
Subroutine __ANON__: not called CC=1 SCAR=6.9
206 0 return $node;
207 }
208  
209 sub register_moved_slot {
210 0 ▶ my ($self, $slot, $host_port) = @_;
Subroutine register_moved_slot: not called CC=1 SCAR=6.9
Pod undocumented
211 0 my $node = $self->node_by_host_port(split /:/, $host_port);
212 0 $self->slot_cache->[$slot & (MAX_SLOTS - 1)] = $node;
213 0 return $node;
214 }
215  
216 0 ▶async sub apply_slots_from_instance {
Subroutine apply_slots_from_instance: not called CC=2 SCAR=17.9
Pod undocumented
217 0 my ($self, $redis) = @_;
218 0 my ($slots) = await $redis->cluster_slots;
219 0 $log->tracef('Have %d slots', 0 + @$slots);
220  
221 0 my @nodes;
222 0 ▶ for my $slot_data (nsort_by { $_->[0] } $slots->@*) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
223 0 my $node = Net::Async::Redis::Cluster::Node->from_arrayref($slot_data);
224 0 $log->tracef(
225 'Node %s (%s) handles slots %d-%d and has %d replica(s) - %s',
226 $node->id,
227 $node->primary,
228 $node->start,
229 $node->end,
230 $node->replica_count,
231 $node
232 );
233  
234 0 push @nodes, $node;
235 }
236  
237 0 $self->replace_nodes(\@nodes);
238 3 }
239  
240 0 ▶async sub execute_command {
Subroutine execute_command: not called CC=5 SCAR=34.0
Pod undocumented
241 0 my ($self, @cmd) = @_;
242 0 $log->tracef('Will execute %s on cluster', join(' ', @cmd));
243 0 my $k;
244 0 ▶ if($cmd[0] eq 'XREADGROUP') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd[0] eq 'XREADGROUP') { } 0 0 0
245 0 my ($idx) = grep { $cmd[$_] eq 'STREAMS' } 0..$#cmd;
246 0 $k = $cmd[$idx + 1];
247 } else {
248 0 my $key_idx;
249 0 for my $idx (0..3) {
250 0 my $check = join ' ', @cmd[0..$idx];
251 0 ▶ last if $key_idx = $Net::Async::Redis::Commands::KEY_FINDER{$check};
Branch: 1 branch
BranchTrueFalseTotal
if $key_idx = $Net::Async::Redis::Commands::KEY_FINDER{$check} 0 0 0
252 }
253 0 ▶ die 'no index found for ' . join(' ', @cmd) unless defined $key_idx;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key_idx 0 0 0
254 0 $k = $cmd[$key_idx];
255 }
256 0 my $slot = $self->hash_slot_for_key($k);
257 0 $log->tracef('Look up hash slot for %s - %d', $k, $slot);
258 0 my $redis = await $self->connection_for_slot($slot);
259 0 return await $redis->execute_command(@cmd);
260 3 }
261  
262 3 1;
263  
264 =head1 AUTHOR
265  
266 Tom Molesworth C<< <TEAM@cpan.org> >> plus contributors as mentioned in
267 L<Net::Async::Redis/CONTRIBUTORS>.
268  
269 =head1 LICENSE
270  
271 Copyright Tom Molesworth and others 2015-2020.
272 Licensed under the same terms as Perl itself.
273  
« Redis/Subscription.pm ↑ Summary job-queue.pl »