lib/Myriad/Transport/Redis.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« lib/Myriad.pm ↑ Summary lib/Test/Myriad/Service.pm »
1 package Myriad::Transport::Redis;
2  
3 2 ▶use Myriad::Class extends => qw(IO::Async::Notifier);
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 our $VERSION = '1.001'; # VERSION
6 our $AUTHORITY = 'cpan:DERIV'; # AUTHORITY
7  
8 =pod
9  
10 We expect to expose:
11  
12 =over 4
13  
14 =item * stream handling functionality, including claiming/pending
15  
16 =item * get/set and observables
17  
18 =item * sorted sets
19  
20 =item * hyperloglog existence
21  
22 =item * simple queues via lists
23  
24 =item * pub/sub
25  
26 =back
27  
28 This module is responsible for namespacing, connection handling and clustering.
29 It should also cover retry for stateless calls.
30  
31 =cut
32  
33 2 ▶use Class::Method::Modifiers qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
34 2 ▶use Sub::Util qw(subname);
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 0 ▶use Myriad::Redis::Pending;
Subroutine BEGIN: called CC=1 SCAR=2.6
37  
38 use Net::Async::Redis;
39 use Net::Async::Redis::Cluster;
40  
41 use List::Util qw(pairmap);
42  
43 use Myriad::Exception::Builder category => 'transport_redis';
44  
45 declare_exception 'NoSuchStream' => (
46 message => 'There is no such stream, is the other service running?',
47 );
48  
49 has $use_cluster;
50 has $redis_uri;
51 has $redis;
52 has $redis_pool;
53 has $waiting_redis_pool;
54 has $pending_redis_count = 0;
55 has $wait_time;
56 has $batch_count = 50;
57 has $max_pool_count;
58 has $clientside_cache_size = 0;
59 has $prefix;
60 has $ryu;
61  
62 BUILD {
63 $redis_pool = [];
64 $waiting_redis_pool = [];
65 }
66  
67 method configure (%args) {
68 if(exists $args{redis_uri}) {
69 my $uri = delete $args{redis_uri};
70 $redis_uri = ref($uri) ? $uri : URI->new($uri);
71 }
72 if(exists $args{cluster}) {
73 $use_cluster = delete $args{cluster};
74 }
75 $max_pool_count = exists $args{max_pool_count} ? delete $args{max_pool_count} : 10;
76 $prefix //= exists $args{prefix} ? delete $args{prefix} : 'myriad';
77 $clientside_cache_size = delete $args{client_side_cache_size} if exists $args{client_side_cache_size};
78 $wait_time = exists $args{wait_time} ? delete $args{wait_time} : 15_000;
79 # limit minimum wait time to 100ms
80 $wait_time = 100 if $wait_time < 100;
81 return $self->next::method(%args);
82 }
83  
84 method ryu { $ryu }
85  
86 =head2 wait_time
87  
88 Time to wait for items, in milliseconds.
89  
90 =cut
91  
92 method wait_time () { $wait_time }
93  
94 =head2 batch_count
95  
96 Number of items to allow per batch (pending / readgroup calls).
97  
98 =cut
99  
100 method batch_count () { $batch_count }
101  
102 async method start {
103 $redis = await $self->redis;
104 return;
105 }
106  
107  
108 =head2 apply_prefix
109  
110 =cut
111  
112 method apply_prefix($key) {
113 $key =~ /^$prefix\./ ? $key : "$prefix.$key";
114 }
115  
116 =head2 remove_prefix
117  
118 =cut
119  
120 method remove_prefix($key) {
121 $key =~ s/^\Q$prefix\E\.//;
122 return $key;
123 }
124  
125 =head2 oldest_processed_id
126  
127 Check the last id that has been processed
128 by B<all> the consumer groups in the given stream.
129  
130 =cut
131  
132 async method oldest_processed_id($stream) {
133 $stream = $self->apply_prefix($stream);
134 my ($groups) = await $redis->xinfo(GROUPS => $stream);
135 my $oldest;
136  
137 for my $group ($groups->@*) {
138 # Use snake_case instead of kebab-case so that we can map cleanly to Perl conventions
139 my %info = pairmap {
140 (
141 ($a =~ tr/-/_/r),
142 $b
143 )
144 } @$group;
145 $log->tracef('Group info: %s', \%info);
146  
147 my $group_name = $info{name};
148  
149 $log->tracef('Pending check where oldest was %s and last delivered %s', $oldest, $info{last_delivered_id});
150 $oldest //= $info{last_delivered_id};
151 $oldest = $info{last_delivered_id} if $info{last_delivered_id} and $self->compare_id($oldest, $info{last_delivered_id}) > 0;
152  
153 # Pending list might have items older than "last_delivered_id"
154 # If the get deleted we can't claim them back and they are lost forever.
155 my ($pending_info) = await $redis->xpending($stream, $group_name);
156 my ($count, $first_id, $last_id, $consumers) = $pending_info->@*;
157 $log->tracef('Pending info %s', $pending_info);
158 $log->tracef('Pending from %s', $first_id);
159 $log->tracef('Pending check where oldest was %s and first %s', $oldest, $first_id);
160 $oldest //= $first_id;
161 $oldest = $first_id if defined($first_id) and $self->compare_id($oldest, $first_id) > 0;
162 }
163  
164 return $oldest;
165 }
166  
167 =head2 compare_id
168  
169 Given two IDs, compare them as if doing a C<< <=> >> numeric
170 comparison.
171  
172 =cut
173  
174 method compare_id($x, $y) {
175 $x //= '0-0';
176 $y //= '0-0';
177 # Do they match?
178 return 0 if $x eq $y;
179 my @first = split /-/, $x, 2;
180 my @second = split /-/, $y, 2;
181  
182 return $first[0] <=> $second[0]
183 || $first[1] <=> $second[1];
184 }
185  
186 =head2 next_id
187  
188 Given a stream ID, returns the next ID after it.
189 This is managed by the simple expedient of incrementing
190 the right-hand part of the identifier.
191  
192 =cut
193  
194 method next_id($id) {
195 my ($left, $right) = split /-/, $id, 2;
196 ++$right;
197 $left . '-' . $right
198 }
199  
200 method _add_to_loop(@) {
201 $self->add_child(
202 $ryu = Ryu::Async->new
203 )
204 }
205  
206 method source (@args) {
207 $self->ryu->source(@args)
208 }
209  
210 =head2 iterate
211  
212 Deal with incoming requests via a stream.
213  
214 Returns a L<Ryu::Source> which emits L<Myriad::Redis::Pending> items.
215  
216 =cut
217  
218 async method read_from_stream (%args) {
219 my $stream = $self->apply_prefix($args{stream});
220 my $group = $args{group};
221 my $client = $args{client};
222  
223 my ($delivery) = await $self->xreadgroup(
224 BLOCK => $self->wait_time,
225 GROUP => $group, $client,
226 COUNT => $self->batch_count,
227 STREAMS => ($stream, '>'),
228 );
229  
230 $log->tracef('Read group: %s as `%s` from [%s]: %s', $group, $client, $stream, $delivery);
231  
232 # We are strictly reading for one stream
233 my $batch = $delivery->[0];
234 if ($batch) {
235 my ($stream, $data) = $batch->@*;
236 return map {
237 my ($id, $args) = $_->@*;
238 +{
239 stream => $self->remove_prefix($stream),
240 id => $id,
241 data => $args,
242 }
243 } $data->@*;
244 }
245  
246 return ();
247 }
248  
249 async method stream_info ($stream) {
250 my $v = await $redis->xinfo(
251 STREAM => $self->apply_prefix($stream)
252 );
253  
254 my %info = pairmap {
255 (
256 ($a =~ tr/-/_/r),
257 $b
258 )
259 } @$v;
260 $log->tracef('Currently %d groups, %d total length', $info{groups}, $info{length});
261 $log->tracef('Full info %s', \%info);
262 return \%info;
263 }
264  
265 =head2 cleanup
266  
267 Clear up old entries from a stream when it grows too large.
268  
269 =cut
270  
271 async method cleanup (%args) {
272 my $stream = $self->apply_prefix($args{stream});
273 # Check on our status - can we clean up any old queue items?
274 my ($info) = await $self->stream_info($stream);
275 return unless $info->{length} > $args{limit};
276  
277 # Track how far back our active stream list goes - anything older than this is fair game
278 my $oldest = await $self->oldest_processed_id($stream);
279 $log->tracef('Attempting to clean up [%s] Size: %d | Earliest ID to care about: %s', $stream, $info->{length}, $oldest);
280 if ($oldest and $oldest ne '0-0' and $self->compare_id($oldest, $info->{first_entry}[0]) > 0) {
281 # At this point we know we have some older items that can go. We'll need to finesse
282 # the direction to search: for now, take the naïve but workable assumption that we
283 # have an even distribution of values. This means we go forwards from the start if
284 # $oldest is closer to the first_delivery_id, or backwards from the end if it's
285 # nearer to the end. We can use the timestamp (first half) rather than the full ID
286 # for this comparison. If we get this wrong, we'll still end up with the right
287 # count - it'll just be a bit less efficient.
288 # This could likely be enhanced by taking a binary search (setting count to 1), although for the common case
289 # of consistent/predictable stream population, having a few points that can be used for a good derivative
290 # estimate means we could apply Newton-Raphson, Runge-Kutta or similar methods to converge faster.
291 my $direction = do {
292 no warnings 'numeric';
293 ($oldest - $info->{first_entry}[0]) > ($info->{last_entry}[0] - $oldest)
294 ? 'xrevrange'
295 : 'xrange'
296 };
297 my $limit = 200;
298  
299 my $endpoint = $direction eq 'xrevrange' ? '+' : '-';
300 my $total = 0;
301 while (1) {
302 # XRANGE / XREVRANGE conveniently have switched start/end parameters, so we don't need to swap $endpoint
303 # and $oldest depending on type here.
304 my ($v) = await $redis->$direction($stream, $endpoint, $oldest, COUNT => $limit);
305 $log->tracef('%s returns %d/%d items between %s and %s', uc($direction), 0 + @$v, $limit, $endpoint, $oldest);
306 $total += 0 + @$v;
307 last unless 0 + @$v >= $limit;
308 # Overlapping ranges, so the next ID will be included twice
309 --$total;
310 $endpoint = $v->[-1][0];
311 }
312 $total = $info->{length} - $total if $direction eq 'xrange';
313  
314 # my ($before) = await $redis->memory_usage($stream);
315 my ($trim) = await $redis->xtrim($stream, MAXLEN => $total);
316 # my ($after) = await $redis->memory_usage($stream);
317 $log->tracef('Trimmed %d items from stream: %s', $total, $stream);
318 }
319 else {
320 $log->tracef('No point in trimming (%s) where: oldest is %s and this compares to %s', $stream, $oldest, $info->{first_entry}[0]);
321 }
322 }
323  
324 =head2 pending
325  
326 Check for any pending items, claiming them for reprocessing as required.
327  
328 Takes the following named parameters:
329  
330 =over 4
331  
332 =item * C<stream> - the stream name
333  
334 =item * C<group> - which consumer group to check
335  
336 =item * C<client> - the name of the client to check
337  
338 =back
339  
340 Returns the pending items in this stream.
341  
342 =cut
343  
344 async method pending (%args) {
345 my $src = $self->source;
346 my $stream = $self->apply_prefix($args{stream});
347 my $group = $args{group};
348 my $client = $args{client};
349 my @res = ();
350  
351 my $instance = await $self->borrow_instance_from_pool;
352 try {
353 my ($pending) = await $instance->xpending(
354 $stream,
355 $group,
356 '-', '+',
357 $self->batch_count,
358 $client,
359 );
360 @res = await &fmap_concat($self->$curry::weak(
361 async method ($item) {
362 my ($id, $consumer, $age, $delivery_count) = $item->@*;
363 $log->tracef('Claiming pending message %s from %s, age %s, %d prior deliveries', $id, $consumer, $age, $delivery_count);
364 my $claim = await $redis->xclaim($stream, $group, $client, 10, $id);
365 $log->tracef('Claim is %s', $claim);
366 my $args = $claim->[0]->[1];
367  
368 return {stream => $self->remove_prefix($stream), id => $id, data => $args ? $args : []};
369 }),
370 foreach => $pending,
371 concurrent => scalar @$pending
372 );
373  
374 } catch ($e) {
375 $log->warnf('Could not read pending messages on stream: %s | error: %s', $stream, $e);
376 }
377 $self->return_instance_to_pool($instance) if $instance;
378 undef $instance;
379  
380 return @res;
381 }
382  
383 =head2 create_stream
384  
385 Creates a Redis stream.
386 Note that there is no straight way to do that in Redis
387 without creating a group or adding an event.
388 To overcome this it will create a group with MKSTREAM option
389 Then destroy that init consumer group.
390  
391 =over 4
392  
393 =item * C<stream> - name of the stream we want to create.
394  
395 =back
396  
397 =cut
398  
399 async method create_stream ($stream) {
400 await $self->create_group($stream, 'INIT', '$', 1);
401 await $self->remove_group($stream, 'INIT');
402 $log->tracef('created a Redis stream: %s', $stream);
403 }
404  
405 =head2 create_group
406  
407 Create a Redis consumer group if it does NOT exist.
408  
409 It'll also send the MKSTREAM option to create the stream if it doesn't exist.
410  
411 =over 4
412  
413 =item * C<stream> - The name of the stream we want to attach the group to.
414  
415 =item * C<group> - The group name.
416  
417 =item * C<start_from> - The id of the message that is going to be considered the start of the stream for this group's point of view
418 by default it's C<$> which means the last message.
419  
420 =back
421  
422 =cut
423  
424 async method create_group ($stream, $group, $start_from = '$', $make_stream = 0) {
425 try {
426 my @args = ('CREATE', $self->apply_prefix($stream), $group, $start_from);
427 push @args, 'MKSTREAM' if $make_stream;
428 await $redis->xgroup(@args);
429 $log->tracef('Created new consumer group: %s from stream: %s', $group, $stream);
430 } catch ($e) {
431 if($e =~ /BUSYGROUP/){
432 $log->tracef('Already exists consumer group: %s from stream: %s', $group, $stream);
433 return;
434 } elsif ($e =~ /requires the key to exist/) {
435 Myriad::Exception::Transport::Redis::NoSuchStream->throw(
436 reason => "no such stream: $stream",
437 );
438 } else {
439 die $e;
440 }
441 }
442 }
443  
444 =head2 remove_group
445  
446 Delete a Redis consumer group.
447  
448 =over 4
449  
450 =item * C<stream> - The name of the stream group belongs to.
451  
452 =item * C<group> - The consumer group name.
453  
454 =back
455  
456 =cut
457  
458 async method remove_group ($stream, $group) {
459 try {
460 my @args = ('DESTROY', $self->apply_prefix($stream), $group);
461 await $redis->xgroup(@args);
462 $log->tracef('Deleted consumergroup: %s from stream: %s', $group, $stream);
463 } catch ($e) {
464 if ($e =~ /requires the key to exist/) {
465 $log->warnf('Trying to remove a consumergroup(%s) from stream: %s that does not exist', $group, $stream);
466 Myriad::Exception::Transport::Redis::NoSuchStream->throw(
467 reason => "no such stream: $stream",
468 );
469 } else {
470 die $e;
471 }
472 }
473 }
474  
475 =head2 pending_messages_info
476  
477 Return information about the pending messages for a stream and a consumer group.
478  
479 This currently just execute C<XPENDING> without any filtering.
480  
481 =over 4
482  
483 =item * C<stream> - The name of the stream we want to check.
484  
485 =item * C<group> - The consumers group name that we want to check.
486  
487 =back
488  
489 =cut
490  
491 async method pending_messages_info($stream, $group) {
492 await $redis->xpending($self->apply_prefix($stream), $group);
493 }
494  
495 =head2 stream_length
496  
497 Return the length of a given stream
498  
499 =cut
500  
501 async method stream_length ($stream) {
502 return await $redis->xlen($self->apply_prefix($stream));
503 }
504  
505 =head2 borrow_instance_from_pool
506  
507 Returns a Redis connection either from a pool of connection or a new one.
508 With the possibility of waiting to get one, if all connection were busy and we maxed out our limit.
509  
510 =cut
511  
512 async method borrow_instance_from_pool {
513 $log->tracef('Available Redis pool count: %d', 0 + $redis_pool->@*);
514 if (my $available_redis = shift $redis_pool->@*) {
515 ++$pending_redis_count;
516 return $available_redis;
517 } elsif ($pending_redis_count < $max_pool_count) {
518 ++$pending_redis_count;
519 return await $self->redis;
520 }
521 push @$waiting_redis_pool, my $f = $self->loop->new_future;
522 $log->debugf('All Redis instances are pending, added to waiting list. Current Redis count: %d/%d | Waiting count: %d', $pending_redis_count, $max_pool_count, 0 + $waiting_redis_pool->@*);
523 return await $f;
524 }
525  
526 =head2 return_instance_to_pool
527  
528 This puts back a redis connection into Redis pool, so it can be used by other called.
529 It should be called at the end of every usage, as on_ready.
530  
531 It should also be possible with a try/finally combination..
532 but that's currently failing with the $redis_pool slot not being defined.
533  
534 Takes the following parameters:
535  
536 =over 4
537  
538 =item * C<$instance> - Redis connection to be returned.
539  
540 =back
541  
542 =cut
543  
544 method return_instance_to_pool ($instance) {
545 if( my $waiting_redis = shift $waiting_redis_pool->@*) {
546 $waiting_redis->done($instance)
547 } else {
548 push $redis_pool->@*, $instance;
549 $log->tracef('Returning instance to pool, Redis used/available now %d/%d', $pending_redis_count, 0 + $redis_pool->@*);
550 $pending_redis_count--;
551 }
552 return;
553 }
554  
555 =head2 redis
556  
557 Resolves to a new L<Net::Async::Redis> or L<Net::Async::Redis::Cluster>
558 instance, depending on the setting of C<$use_cluster>.
559  
560 =cut
561  
562 async method redis () {
563 my $instance;
564 if($use_cluster) {
565 $instance = Net::Async::Redis::Cluster->new(
566 client_side_cache_size => $clientside_cache_size,
567 );
568 $self->add_child(
569 $instance
570 );
571 await $instance->bootstrap(
572 host => $redis_uri->host,
573 port => $redis_uri->port,
574 );
575 } else {
576 $instance = Net::Async::Redis->new(
577 host => $redis_uri->host,
578 port => $redis_uri->port,
579 client_side_cache_size => $clientside_cache_size,
580 );
581 $self->add_child(
582 $instance
583 );
584 $log->tracef('Added new Redis connection (%s) to pool', $redis_uri->as_string);
585 await $instance->connect;
586 }
587 return $instance;
588 }
589  
590 async method xreadgroup (@args) {
591 my $instance = await $self->borrow_instance_from_pool;
592 my ($batch) = await $instance->xreadgroup(@args)->on_ready(sub {
593 $self->return_instance_to_pool($instance);
594 });
595 return ($batch);
596 }
597  
598 async method xadd ($stream, @args) {
599 return await $redis->xadd($self->apply_prefix($stream), @args);
600 }
601  
602 =head2 ack
603  
604 Acknowledge a message from a Redis stream.
605  
606 =over 4
607  
608 =item * C<stream> - The stream name.
609  
610 =item * C<group> - The group name.
611  
612 =item * C<message_id> - The id of the message we want to acknowledge.
613  
614 =back
615  
616 =cut
617  
618 async method ack ($stream, $group, $message_id) {
619 await $redis->xack($self->apply_prefix($stream), $group, $message_id);
620 }
621  
622 =head2 publish
623  
624 Publish a message through a Redis channel (pub/sub system)
625  
626 =over 4
627  
628 =item * C<channel> - The channel name.
629  
630 =item * C<message> - The message we want to publish (string).
631  
632 =back
633  
634 =cut
635  
636 async method publish ($channel, $message) {
637 await $redis->publish($self->apply_prefix($channel), "$message");
638 }
639  
640 =head2 subscribe
641  
642 Subscribe to a redis channel.
643  
644 =cut
645  
646 async method subscribe ($channel) {
647 my $instance = await $self->borrow_instance_from_pool;
648 await $instance->subscribe($self->apply_prefix($channel))->on_ready(sub {
649 $self->return_instance_to_pool($instance);
650 });
651 }
652  
653 async method get($key) {
654 await $redis->get($self->apply_prefix($key));
655 }
656  
657 async method set ($key, $v) {
658 await $redis->set($self->apply_prefix($key), $v);
659 }
660  
661 async method getset($key, $v) {
662 await $redis->set($self->apply_prefix($key), $v);
663 }
664  
665 async method incr ($key) {
666 await $redis->incr($self->apply_prefix($key));
667 }
668  
669 async method rpush($key, @v) {
670 await $redis->rpush($self->apply_prefix($key), @v);
671 }
672  
673 async method lpush($key, @v) {
674 await $redis->lpush($self->apply_prefix($key), @v);
675 }
676  
677 async method rpop($key) {
678 await $redis->rpop($self->apply_prefix($key));
679 }
680  
681 async method lpop($key) {
682 await $redis->lpop($self->apply_prefix($key));
683 }
684  
685 async method hset ($k, $hash_key, $v) {
686 await $redis->hset($k, $self->apply_prefix($hash_key), $v);
687 }
688  
689 async method hget($k, $hash_key) {
690 await $redis->hget($k, $self->apply_prefix($hash_key));
691 }
692  
693 async method hincrby($k, $hash_key, $v) {
694 await $redis->hincrby($k, $self->apply_prefix($hash_key), $v);
695 }
696  
697 async method zadd ($key, @v) {
698 await $redis->zadd($self->apply_prefix($key), @v);
699 }
700  
701 async method zrem ($k, $m) {
702 await $redis->zrem($self->apply_prefix($k), $m);
703 }
704  
705 async method zremrangebyscore ($k, $min, $max) {
706 await $redis->zremrangebyscore($self->apply_prefix($k), $min => $max);
707 }
708  
709 async method zcount ($k, $min, $max) {
710 await $redis->zcount($self->apply_prefix($k), $min, $max);
711 }
712  
713 async method zrange ($k, @v) {
714 await $redis->zrange($self->apply_prefix($k), @v);
715 }
716  
717 async method watch_keyspace($pattern) {
718 my $sub;
719 if ($clientside_cache_size) {
720 # Net::Async::Redis will handl the connection in this case
721 $sub = $redis->clientside_cache_events->map(sub {
722 $_ =~ s/$prefix\.//;
723 return $_;
724 });
725 } else {
726 # Keyspace notification is a psubscribe
727 my $instance = await $self->borrow_instance_from_pool;
728 $sub = await $instance->watch_keyspace($self->apply_prefix($pattern));
729  
730 $sub = $sub->events->map(sub {
731 $_->{channel} =~ s/__key.*:$prefix\.//;
732 return $_->{channel};
733 });
734  
735 $sub->on_ready(sub {
736 $self->return_instance_to_pool($instance);
737 });
738 }
739  
740 return $sub;
741 }
742  
743 1;
744  
745 =head1 AUTHOR
746  
747 Deriv Group Services Ltd. C<< DERIV@cpan.org >>
748  
749 =head1 LICENSE
750  
751 Copyright Deriv Group Services Ltd 2020-2022. Licensed under the same terms as Perl itself.
752  
« lib/Myriad.pm ↑ Summary lib/Test/Myriad/Service.pm »