-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathRedisDynoQueue.java
1633 lines (1353 loc) · 64 KB
/
RedisDynoQueue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2016 Netflix, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.dyno.queues.redis;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Uninterruptibles;
import com.netflix.dyno.jedis.DynoJedisClient;
import com.netflix.dyno.queues.DynoQueue;
import com.netflix.dyno.queues.Message;
import com.netflix.dyno.queues.redis.sharding.ShardingStrategy;
import com.netflix.servo.monitor.Stopwatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Tuple;
import redis.clients.jedis.commands.JedisCommands;
import redis.clients.jedis.params.ZAddParams;
import java.io.IOException;
import java.text.NumberFormat;
import java.time.Clock;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static com.netflix.dyno.queues.redis.QueueUtils.execute;
/**
*
* @author Viren
* Current Production (March 2018) recipe - well tested in production.
* Note, this recipe does not use redis pipelines and hence the throughput offered is less compared to v2 recipes.
*/
public class RedisDynoQueue implements DynoQueue {
private final Logger logger = LoggerFactory.getLogger(RedisDynoQueue.class);
private final Clock clock;
private final String queueName;
private final List<String> allShards;
private final String shardName;
private final String redisKeyPrefix;
private final String messageStoreKey;
private final String localQueueShard;
private volatile int unackTime = 60;
private final QueueMonitor monitor;
private final ObjectMapper om;
private volatile JedisCommands quorumConn;
private volatile JedisCommands nonQuorumConn;
private final ConcurrentLinkedQueue<String> prefetchedIds;
private final Map<String, ConcurrentLinkedQueue<String>> unsafePrefetchedIdsAllShardsMap;
private final ScheduledExecutorService schedulerForUnacksProcessing;
private final int retryCount = 2;
private final ShardingStrategy shardingStrategy;
private final boolean singleRingTopology;
// Tracks the number of message IDs to prefetch based on the message counts requested by the caller via pop().
@VisibleForTesting
AtomicInteger numIdsToPrefetch;
// Tracks the number of message IDs to prefetch based on the message counts requested by the caller via
// unsafePopAllShards().
@VisibleForTesting
AtomicInteger unsafeNumIdsToPrefetchAllShards;
public RedisDynoQueue(String redisKeyPrefix, String queueName, Set<String> allShards, String shardName, ShardingStrategy shardingStrategy, boolean singleRingTopology) {
this(redisKeyPrefix, queueName, allShards, shardName, 60_000, shardingStrategy, singleRingTopology);
}
public RedisDynoQueue(String redisKeyPrefix, String queueName, Set<String> allShards, String shardName, int unackScheduleInMS, ShardingStrategy shardingStrategy, boolean singleRingTopology) {
this(Clock.systemDefaultZone(), redisKeyPrefix, queueName, allShards, shardName, unackScheduleInMS, shardingStrategy, singleRingTopology);
}
public RedisDynoQueue(Clock clock, String redisKeyPrefix, String queueName, Set<String> allShards, String shardName, int unackScheduleInMS, ShardingStrategy shardingStrategy, boolean singleRingTopology) {
this.clock = clock;
this.redisKeyPrefix = redisKeyPrefix;
this.queueName = queueName;
this.allShards = ImmutableList.copyOf(allShards.stream().collect(Collectors.toList()));
this.shardName = shardName;
this.messageStoreKey = redisKeyPrefix + ".MESSAGE." + queueName;
this.localQueueShard = getQueueShardKey(queueName, shardName);
this.shardingStrategy = shardingStrategy;
this.numIdsToPrefetch = new AtomicInteger(0);
this.unsafeNumIdsToPrefetchAllShards = new AtomicInteger(0);
this.singleRingTopology = singleRingTopology;
this.om = QueueUtils.constructObjectMapper();
this.monitor = new QueueMonitor(queueName, shardName);
this.prefetchedIds = new ConcurrentLinkedQueue<>();
this.unsafePrefetchedIdsAllShardsMap = new HashMap<>();
for (String shard : allShards) {
unsafePrefetchedIdsAllShardsMap.put(getQueueShardKey(queueName, shard), new ConcurrentLinkedQueue<>());
}
schedulerForUnacksProcessing = Executors.newScheduledThreadPool(1);
if (this.singleRingTopology) {
schedulerForUnacksProcessing.scheduleAtFixedRate(() -> atomicProcessUnacks(), unackScheduleInMS, unackScheduleInMS, TimeUnit.MILLISECONDS);
} else {
schedulerForUnacksProcessing.scheduleAtFixedRate(() -> processUnacks(), unackScheduleInMS, unackScheduleInMS, TimeUnit.MILLISECONDS);
}
logger.info(RedisDynoQueue.class.getName() + " is ready to serve " + queueName);
}
public RedisDynoQueue withQuorumConn(JedisCommands quorumConn) {
this.quorumConn = quorumConn;
return this;
}
public RedisDynoQueue withNonQuorumConn(JedisCommands nonQuorumConn) {
this.nonQuorumConn = nonQuorumConn;
return this;
}
public RedisDynoQueue withUnackTime(int unackTime) {
this.unackTime = unackTime;
return this;
}
/**
* @return Number of items in each ConcurrentLinkedQueue from 'unsafePrefetchedIdsAllShardsMap'.
*/
private int unsafeGetNumPrefetchedIds() {
// Note: We use an AtomicInteger due to Java's limitation of not allowing the modification of local native
// data types in lambdas (Java 8).
AtomicInteger totalSize = new AtomicInteger(0);
unsafePrefetchedIdsAllShardsMap.forEach((k,v)->totalSize.addAndGet(v.size()));
return totalSize.get();
}
@Override
public String getName() {
return queueName;
}
@Override
public int getUnackTime() {
return unackTime;
}
@Override
public List<String> push(final List<Message> messages) {
Stopwatch sw = monitor.start(monitor.push, messages.size());
try {
execute("push", "(a shard in) " + queueName, () -> {
for (Message message : messages) {
String json = om.writeValueAsString(message);
quorumConn.hset(messageStoreKey, message.getId(), json);
double priority = message.getPriority() / 100.0;
double score = Long.valueOf(clock.millis() + message.getTimeout()).doubleValue() + priority;
String shard = shardingStrategy.getNextShard(allShards, message);
String queueShard = getQueueShardKey(queueName, shard);
quorumConn.zadd(queueShard, score, message.getId());
}
return messages;
});
return messages.stream().map(msg -> msg.getId()).collect(Collectors.toList());
} finally {
sw.stop();
}
}
@Override
public List<Message> peek(final int messageCount) {
Stopwatch sw = monitor.peek.start();
try {
Set<String> ids = peekIds(0, messageCount);
if (ids == null) {
return Collections.emptyList();
}
return doPeekBodyHelper(ids);
} finally {
sw.stop();
}
}
@Override
public List<Message> unsafePeekAllShards(final int messageCount) {
Stopwatch sw = monitor.peek.start();
try {
Set<String> ids = peekIdsAllShards(0, messageCount);
if (ids == null) {
return Collections.emptyList();
}
return doPeekBodyHelper(ids);
} finally {
sw.stop();
}
}
/**
*
* Peeks into 'this.localQueueShard' and returns up to 'count' items starting at position 'offset' in the shard.
*
*
* @param offset Number of items to skip over in 'this.localQueueShard'
* @param count Number of items to return.
* @return Up to 'count' number of message IDs in a set.
*/
private Set<String> peekIds(final int offset, final int count, final double peekTillTs) {
return execute("peekIds", localQueueShard, () -> {
double peekTillTsOrNow = (peekTillTs == 0.0) ? Long.valueOf(clock.millis() + 1).doubleValue() : peekTillTs;
return doPeekIdsFromShardHelper(localQueueShard, peekTillTsOrNow, offset, count);
});
}
private Set<String> peekIds(final int offset, final int count) {
return peekIds(offset, count, 0.0);
}
/**
*
* Same as 'peekIds()' but looks into all shards of the queue ('this.allShards').
*
* @param count Number of items to return.
* @return Up to 'count' number of message IDs in a set.
*/
private Set<String> peekIdsAllShards(final int offset, final int count) {
return execute("peekIdsAllShards", localQueueShard, () -> {
Set<String> scanned = new HashSet<>();
double now = Long.valueOf(clock.millis() + 1).doubleValue();
int remaining_count = count;
// Try to get as many items from 'this.localQueueShard' first to reduce chances of returning duplicate items.
// (See unsafe* functions disclaimer in DynoQueue.java)
scanned.addAll(peekIds(offset, count, now));
remaining_count -= scanned.size();
for (String shard : allShards) {
String queueShardName = getQueueShardKey(queueName, shard);
// Skip 'localQueueShard'.
if (queueShardName.equals(localQueueShard)) continue;
Set<String> elems = doPeekIdsFromShardHelper(queueShardName, now, offset, count);
scanned.addAll(elems);
remaining_count -= elems.size();
if (remaining_count <= 0) break;
}
return scanned;
});
}
private Set<String> doPeekIdsFromShardHelper(final String queueShardName, final double peekTillTs, final int offset,
final int count) {
return nonQuorumConn.zrangeByScore(queueShardName, 0, peekTillTs, offset, count);
}
/**
* Takes a set of message IDs, 'message_ids', and returns a list of Message objects
* corresponding to 'message_ids'. Read only, does not make any updates.
*
* @param message_ids Set of message IDs to peek.
* @return a list of Message objects corresponding to 'message_ids'
*
*/
private List<Message> doPeekBodyHelper(Set<String> message_ids) {
List<Message> msgs = execute("peek", messageStoreKey, () -> {
List<Message> messages = new LinkedList<Message>();
for (String id : message_ids) {
String json = nonQuorumConn.hget(messageStoreKey, id);
Message message = om.readValue(json, Message.class);
messages.add(message);
}
return messages;
});
return msgs;
}
@Override
public List<Message> pop(int messageCount, int wait, TimeUnit unit) {
if (messageCount < 1) {
return Collections.emptyList();
}
Stopwatch sw = monitor.start(monitor.pop, messageCount);
try {
long start = clock.millis();
long waitFor = unit.toMillis(wait);
numIdsToPrefetch.addAndGet(messageCount);
// We prefetch message IDs here first before attempting to pop them off the sorted set.
// The reason we do this (as opposed to just popping from the head of the sorted set),
// is that due to the eventually consistent nature of Dynomite, the different replicas of the same
// sorted set _may_ not look exactly the same at any given time, i.e. they may have a different number of
// items due to replication lag.
// So, we first peek into the sorted set to find the list of message IDs that we know for sure are
// replicated across all replicas and then attempt to pop them based on those message IDs.
prefetchIds();
while (prefetchedIds.size() < messageCount && ((clock.millis() - start) < waitFor)) {
Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
prefetchIds();
}
return _pop(shardName, messageCount, prefetchedIds);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
sw.stop();
}
}
@Override
public Message popWithMsgId(String messageId) {
return popWithMsgIdHelper(messageId, shardName, true);
}
@Override
public Message unsafePopWithMsgIdAllShards(String messageId) {
int numShards = allShards.size();
for (String shard : allShards) {
boolean warnIfNotExists = false;
// Only one of the shards will have the message, so we don't want the check in the other 2 shards
// to spam the logs. So make sure only the last shard emits a warning log which means that none of the
// shards have 'messageId'.
if (--numShards == 0) warnIfNotExists = true;
Message msg = popWithMsgIdHelper(messageId, shard, warnIfNotExists);
if (msg != null) return msg;
}
return null;
}
public Message popWithMsgIdHelper(String messageId, String targetShard, boolean warnIfNotExists) {
Stopwatch sw = monitor.start(monitor.pop, 1);
try {
return execute("popWithMsgId", targetShard, () -> {
String queueShardName = getQueueShardKey(queueName, targetShard);
double unackScore = Long.valueOf(clock.millis() + unackTime).doubleValue();
String unackShardName = getUnackKey(queueName, targetShard);
ZAddParams zParams = ZAddParams.zAddParams().nx();
Long exists = nonQuorumConn.zrank(queueShardName, messageId);
// If we get back a null type, then the element doesn't exist.
if (exists == null) {
// We only have a 'warnIfNotExists' check for this call since not all messages are present in
// all shards. So we want to avoid a log spam. If any of the following calls return 'null' or '0',
// we may have hit an inconsistency (because it's in the queue, but other calls have failed),
// so make sure to log those.
if (warnIfNotExists) {
logger.warn("Cannot find the message with ID {}", messageId);
}
monitor.misses.increment();
return null;
}
String json = quorumConn.hget(messageStoreKey, messageId);
if (json == null) {
logger.warn("Cannot get the message payload for {}", messageId);
monitor.misses.increment();
return null;
}
long added = quorumConn.zadd(unackShardName, unackScore, messageId, zParams);
if (added == 0) {
logger.warn("cannot add {} to the unack shard {}", messageId, unackShardName);
monitor.misses.increment();
return null;
}
long removed = quorumConn.zrem(queueShardName, messageId);
if (removed == 0) {
logger.warn("cannot remove {} from the queue shard ", queueName, messageId);
monitor.misses.increment();
return null;
}
Message msg = om.readValue(json, Message.class);
return msg;
});
} finally {
sw.stop();
}
}
public List<Message> unsafePopAllShards(int messageCount, int wait, TimeUnit unit) {
if (messageCount < 1) {
return Collections.emptyList();
}
Stopwatch sw = monitor.start(monitor.pop, messageCount);
try {
long start = clock.millis();
long waitFor = unit.toMillis(wait);
unsafeNumIdsToPrefetchAllShards.addAndGet(messageCount);
prefetchIdsAllShards();
while(unsafeGetNumPrefetchedIds() < messageCount && ((clock.millis() - start) < waitFor)) {
Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
prefetchIdsAllShards();
}
int remainingCount = messageCount;
// Pop as much as possible from the local shard first to reduce chances of returning duplicate items.
// (See unsafe* functions disclaimer in DynoQueue.java)
List<Message> popped = _pop(shardName, remainingCount, unsafePrefetchedIdsAllShardsMap.get(localQueueShard));
remainingCount -= popped.size();
for (String shard : allShards) {
String queueShardName = getQueueShardKey(queueName, shard);
List<Message> elems = _pop(shard, remainingCount, unsafePrefetchedIdsAllShardsMap.get(queueShardName));
popped.addAll(elems);
remainingCount -= elems.size();
}
return popped;
} catch(Exception e) {
throw new RuntimeException(e);
} finally {
sw.stop();
}
}
/**
* Prefetch message IDs from the local shard.
*/
private void prefetchIds() {
double now = Long.valueOf(clock.millis() + 1).doubleValue();
int numPrefetched = doPrefetchIdsHelper(localQueueShard, numIdsToPrefetch, prefetchedIds, now);
if (numPrefetched == 0) {
numIdsToPrefetch.set(0);
}
}
/**
* Prefetch message IDs from all shards.
*/
private void prefetchIdsAllShards() {
double now = Long.valueOf(clock.millis() + 1).doubleValue();
// Try to prefetch as many items from 'this.localQueueShard' first to reduce chances of returning duplicate items.
// (See unsafe* functions disclaimer in DynoQueue.java)
doPrefetchIdsHelper(localQueueShard, unsafeNumIdsToPrefetchAllShards,
unsafePrefetchedIdsAllShardsMap.get(localQueueShard), now);
if (unsafeNumIdsToPrefetchAllShards.get() < 1) return;
for (String shard : allShards) {
String queueShardName = getQueueShardKey(queueName, shard);
if (queueShardName.equals(localQueueShard)) continue; // Skip since we've already serviced the local shard.
doPrefetchIdsHelper(queueShardName, unsafeNumIdsToPrefetchAllShards,
unsafePrefetchedIdsAllShardsMap.get(queueShardName), now);
}
}
/**
* Attempts to prefetch up to 'prefetchCounter' message IDs, by peeking into a queue based on 'peekFunction',
* and store it in a concurrent linked queue.
*
* @param prefetchCounter Number of message IDs to attempt prefetch.
* @param prefetchedIdQueue Concurrent Linked Queue where message IDs are stored.
* @param peekFunction Function to call to peek into the queue.
*/
private int doPrefetchIdsHelper(String queueShardName, AtomicInteger prefetchCounter,
ConcurrentLinkedQueue<String> prefetchedIdQueue, double prefetchFromTs) {
if (prefetchCounter.get() < 1) {
return 0;
}
int numSuccessfullyPrefetched = 0;
int numToPrefetch = prefetchCounter.get();
Stopwatch sw = monitor.start(monitor.prefetch, numToPrefetch);
try {
// Attempt to peek up to 'numToPrefetch' message Ids.
Set<String> ids = doPeekIdsFromShardHelper(queueShardName, prefetchFromTs, 0, numToPrefetch);
// TODO: Check for duplicates.
// Store prefetched IDs in a queue.
prefetchedIdQueue.addAll(ids);
numSuccessfullyPrefetched = ids.size();
// Account for number of IDs successfully prefetched.
prefetchCounter.addAndGet((-1 * ids.size()));
if(prefetchCounter.get() < 0) {
prefetchCounter.set(0);
}
} finally {
sw.stop();
}
return numSuccessfullyPrefetched;
}
private List<Message> _pop(String shard, int messageCount,
ConcurrentLinkedQueue<String> prefetchedIdQueue) throws Exception {
String queueShardName = getQueueShardKey(queueName, shard);
String unackShardName = getUnackKey(queueName, shard);
double unackScore = Long.valueOf(clock.millis() + unackTime).doubleValue();
// NX option indicates add only if it doesn't exist.
// https://redis.io/commands/zadd#zadd-options-redis-302-or-greater
ZAddParams zParams = ZAddParams.zAddParams().nx();
List<Message> popped = new LinkedList<>();
for (;popped.size() != messageCount;) {
String msgId = prefetchedIdQueue.poll();
if(msgId == null) {
break;
}
long added = quorumConn.zadd(unackShardName, unackScore, msgId, zParams);
if(added == 0){
logger.warn("cannot add {} to the unack shard {}", msgId, unackShardName);
monitor.misses.increment();
continue;
}
long removed = quorumConn.zrem(queueShardName, msgId);
if (removed == 0) {
logger.warn("cannot remove {} from the queue shard {}", msgId, queueShardName);
monitor.misses.increment();
continue;
}
String json = quorumConn.hget(messageStoreKey, msgId);
if (json == null) {
logger.warn("Cannot get the message payload for {}", msgId);
monitor.misses.increment();
continue;
}
Message msg = om.readValue(json, Message.class);
popped.add(msg);
if (popped.size() == messageCount) {
return popped;
}
}
return popped;
}
@Override
public boolean ack(String messageId) {
Stopwatch sw = monitor.ack.start();
try {
return execute("ack", "(a shard in) " + queueName, () -> {
for (String shard : allShards) {
String unackShardKey = getUnackKey(queueName, shard);
Long removed = quorumConn.zrem(unackShardKey, messageId);
if (removed > 0) {
quorumConn.hdel(messageStoreKey, messageId);
return true;
}
}
return false;
});
} finally {
sw.stop();
}
}
@Override
public void ack(List<Message> messages) {
for (Message message : messages) {
ack(message.getId());
}
}
@Override
public boolean setUnackTimeout(String messageId, long timeout) {
Stopwatch sw = monitor.ack.start();
try {
return execute("setUnackTimeout", "(a shard in) " + queueName, () -> {
double unackScore = Long.valueOf(clock.millis() + timeout).doubleValue();
for (String shard : allShards) {
String unackShardKey = getUnackKey(queueName, shard);
Double score = quorumConn.zscore(unackShardKey, messageId);
if (score != null) {
quorumConn.zadd(unackShardKey, unackScore, messageId);
return true;
}
}
return false;
});
} finally {
sw.stop();
}
}
@Override
public boolean setTimeout(String messageId, long timeout) {
return execute("setTimeout", "(a shard in) " + queueName, () -> {
String json = nonQuorumConn.hget(messageStoreKey, messageId);
if (json == null) {
return false;
}
Message message = om.readValue(json, Message.class);
message.setTimeout(timeout);
for (String shard : allShards) {
String queueShard = getQueueShardKey(queueName, shard);
Double score = quorumConn.zscore(queueShard, messageId);
if (score != null) {
double priorityd = message.getPriority() / 100;
double newScore = Long.valueOf(clock.millis() + timeout).doubleValue() + priorityd;
ZAddParams params = ZAddParams.zAddParams().xx();
quorumConn.zadd(queueShard, newScore, messageId, params);
json = om.writeValueAsString(message);
quorumConn.hset(messageStoreKey, message.getId(), json);
return true;
}
}
return false;
});
}
@Override
public boolean remove(String messageId) {
Stopwatch sw = monitor.remove.start();
try {
return execute("remove", "(a shard in) " + queueName, () -> {
for (String shard : allShards) {
String unackShardKey = getUnackKey(queueName, shard);
quorumConn.zrem(unackShardKey, messageId);
String queueShardKey = getQueueShardKey(queueName, shard);
Long removed = quorumConn.zrem(queueShardKey, messageId);
if (removed > 0) {
// Ignoring return value since we just want to get rid of it.
Long msgRemoved = quorumConn.hdel(messageStoreKey, messageId);
return true;
}
}
return false;
});
} finally {
sw.stop();
}
}
@Override
public boolean atomicRemove(String messageId) {
Stopwatch sw = monitor.remove.start();
try {
return execute("remove", "(a shard in) " + queueName, () -> {
String atomicRemoveScript = "local hkey=KEYS[1]\n" +
"local msg_id=ARGV[1]\n" +
"local num_shards=ARGV[2]\n" +
"\n" +
"local removed_shard=0\n" +
"local removed_unack=0\n" +
"local removed_hash=0\n" +
"for i=0,num_shards-1 do\n" +
" local shard_name = ARGV[3+(i*2)]\n" +
" local unack_name = ARGV[3+(i*2)+1]\n" +
"\n" +
" removed_shard = removed_shard + redis.call('zrem', shard_name, msg_id)\n" +
" removed_unack = removed_unack + redis.call('zrem', unack_name, msg_id)\n" +
"end\n" +
"\n" +
"removed_hash = redis.call('hdel', hkey, msg_id)\n" +
"if (removed_shard==1 or removed_unack==1 or removed_hash==1) then\n" +
" return 1\n" +
"end\n" +
"return removed_unack\n";
ImmutableList.Builder builder = ImmutableList.builder();
builder.add(messageId);
builder.add(Integer.toString(allShards.size()));
for (String shard : allShards) {
String queueShardKey = getQueueShardKey(queueName, shard);
String unackShardKey = getUnackKey(queueName, shard);
builder.add(queueShardKey);
builder.add(unackShardKey);
}
Long removed = (Long) ((DynoJedisClient)quorumConn).eval(atomicRemoveScript, Collections.singletonList(messageStoreKey), builder.build());
if (removed == 1) return true;
return false;
});
} finally {
sw.stop();
}
}
@Override
public boolean ensure(Message message) {
return execute("ensure", "(a shard in) " + queueName, () -> {
String messageId = message.getId();
for (String shard : allShards) {
String queueShard = getQueueShardKey(queueName, shard);
Double score = quorumConn.zscore(queueShard, messageId);
if (score != null) {
return false;
}
String unackShardKey = getUnackKey(queueName, shard);
score = quorumConn.zscore(unackShardKey, messageId);
if (score != null) {
return false;
}
}
push(Collections.singletonList(message));
return true;
});
}
@Override
public boolean containsPredicate(String predicate) {
return containsPredicate(predicate, false);
}
@Override
public String getMsgWithPredicate(String predicate) {
return getMsgWithPredicate(predicate, false);
}
@Override
public boolean containsPredicate(String predicate, boolean localShardOnly) {
return execute("containsPredicate", messageStoreKey, () -> getMsgWithPredicate(predicate, localShardOnly) != null);
}
@Override
public String getMsgWithPredicate(String predicate, boolean localShardOnly) {
return execute("getMsgWithPredicate", messageStoreKey, () -> {
// We use a Lua script here to do predicate matching since we only want to find whether the predicate
// exists in any of the message bodies or not, and the only way to do that is to check for the predicate
// match on the server side.
// The alternative is to have the server return all the hash values back to us and we filter it here on
// the client side. This is not desirable since we would potentially be sending large amounts of data
// over the network only to return a single string value back to the calling application.
String predicateCheckAllLuaScript = "local hkey=KEYS[1]\n" +
"local predicate=ARGV[1]\n" +
"local cursor=0\n" +
"local begin=false\n" +
"while (cursor ~= 0 or begin==false) do\n" +
" local ret = redis.call('hscan', hkey, cursor)\n" +
" local curmsgid\n" +
" for i, content in ipairs(ret[2]) do\n" +
" if (i % 2 ~= 0) then\n" +
" curmsgid = content\n" +
" elseif (string.match(content, predicate)) then\n" +
" return curmsgid\n" +
" end\n" +
" end\n" +
" cursor=tonumber(ret[1])\n" +
" begin=true\n" +
"end\n" +
"return nil";
String predicateCheckLocalOnlyLuaScript = "local hkey=KEYS[1]\n" +
"local predicate=ARGV[1]\n" +
"local shard_name=ARGV[2]\n" +
"local cursor=0\n" +
"local begin=false\n" +
"while (cursor ~= 0 or begin==false) do\n" +
" local ret = redis.call('hscan', hkey, cursor)\n" +
"local curmsgid\n" +
"for i, content in ipairs(ret[2]) do\n" +
" if (i % 2 ~= 0) then\n" +
" curmsgid = content\n" +
"elseif (string.match(content, predicate)) then\n" +
"local in_local_shard = redis.call('zrank', shard_name, curmsgid)\n" +
"if (type(in_local_shard) ~= 'boolean' and in_local_shard >= 0) then\n" +
"return curmsgid\n" +
"end\n" +
" end\n" +
"end\n" +
" cursor=tonumber(ret[1])\n" +
"begin=true\n" +
"end\n" +
"return nil";
String retval;
if (localShardOnly) {
// Cast from 'JedisCommands' to 'DynoJedisClient' here since the former does not expose 'eval()'.
retval = (String) ((DynoJedisClient) nonQuorumConn).eval(predicateCheckLocalOnlyLuaScript,
Collections.singletonList(messageStoreKey), ImmutableList.of(predicate, localQueueShard));
} else {
// Cast from 'JedisCommands' to 'DynoJedisClient' here since the former does not expose 'eval()'.
retval = (String) ((DynoJedisClient) nonQuorumConn).eval(predicateCheckAllLuaScript,
Collections.singletonList(messageStoreKey), Collections.singletonList(predicate));
}
return retval;
});
}
private Message popMsgWithPredicateObeyPriority(String predicate, boolean localShardOnly) {
String popPredicateObeyPriority = "local hkey=KEYS[1]\n" +
"local predicate=ARGV[1]\n" +
"local num_shards=ARGV[2]\n" +
"local peek_until=tonumber(ARGV[3])\n" +
"local unack_score=tonumber(ARGV[4])\n" +
"\n" +
"local shard_names={}\n" +
"local unack_names={}\n" +
"local shard_lengths={}\n" +
"local largest_shard=-1\n" +
"for i=0,num_shards-1 do\n" +
" shard_names[i+1]=ARGV[5+(i*2)]\n" +
" shard_lengths[i+1] = redis.call('zcard', shard_names[i+1])\n" +
" unack_names[i+1]=ARGV[5+(i*2)+1]\n" +
"\n" +
" if (shard_lengths[i+1] > largest_shard) then\n" +
" largest_shard = shard_lengths[i+1]\n" +
" end\n" +
"end\n" +
"\n" +
"local min_score=-1\n" +
"local min_member\n" +
"local matching_value\n" +
"local owning_shard_idx=-1\n" +
"\n" +
"local num_complete_shards=0\n" +
"for j=0,largest_shard-1 do\n" +
" for i=1,num_shards do\n" +
" local skiploop=false\n" +
" if (shard_lengths[i] < j+1) then\n" +
" skiploop=true\n" +
" end\n" +
"\n" +
" if (skiploop == false) then\n" +
" local element = redis.call('zrange', shard_names[i], j, j, 'WITHSCORES')\n" +
" if ((min_score ~= -1 and min_score < tonumber(element[2])) or peek_until < tonumber(element[2])) then\n" +
" -- This is to make sure we don't process this shard again\n" +
" -- since all elements henceforth are of lower priority than min_member\n" +
" shard_lengths[i]=0\n" +
" num_complete_shards = num_complete_shards + 1\n" +
" else\n" +
" local value = redis.call('hget', hkey, tostring(element[1]))\n" +
" if (value) then\n" +
" if (string.match(value, predicate)) then\n" +
" if (min_score == -1 or tonumber(element[2]) < min_score) then\n" +
" min_score = tonumber(element[2])\n" +
" owning_shard_idx=i\n" +
" min_member = element[1]\n" +
" matching_value = value\n" +
" end\n" +
" end\n" +
" end\n" +
" end\n" +
" end\n" +
" end\n" +
" if (num_complete_shards == num_shards) then\n" +
" break\n" +
" end\n" +
"end\n" +
"\n" +
"if (min_member) then\n" +
" local queue_shard_name=shard_names[owning_shard_idx]\n" +
" local unack_shard_name=unack_names[owning_shard_idx]\n" +
" local zadd_ret = redis.call('zadd', unack_shard_name, 'NX', unack_score, min_member)\n" +
" if (zadd_ret) then\n" +
" redis.call('zrem', queue_shard_name, min_member)\n" +
" end\n" +
"end\n" +
"return {min_member, matching_value}";
double now = Long.valueOf(clock.millis() + 1).doubleValue();
double unackScore = Long.valueOf(clock.millis() + unackTime).doubleValue();
// The script requires the scores as whole numbers
NumberFormat fmt = NumberFormat.getIntegerInstance();
fmt.setGroupingUsed(false);
String nowScoreString = fmt.format(now);
String unackScoreString = fmt.format(unackScore);
ArrayList<String> retval;
if (localShardOnly) {
String unackShardName = getUnackKey(queueName, shardName);
ImmutableList.Builder builder = ImmutableList.builder();
builder.add(predicate);
builder.add(Integer.toString(1));
builder.add(nowScoreString);
builder.add(unackScoreString);
builder.add(localQueueShard);
builder.add(unackShardName);
// Cast from 'JedisCommands' to 'DynoJedisClient' here since the former does not expose 'eval()'.
retval = (ArrayList) ((DynoJedisClient) quorumConn).eval(popPredicateObeyPriority,
Collections.singletonList(messageStoreKey), builder.build());
} else {
ImmutableList.Builder builder = ImmutableList.builder();
builder.add(predicate);
builder.add(Integer.toString(allShards.size()));
builder.add(nowScoreString);
builder.add(unackScoreString);
for (String shard : allShards) {
String queueShard = getQueueShardKey(queueName, shard);
String unackShardName = getUnackKey(queueName, shard);
builder.add(queueShard);
builder.add(unackShardName);
}
// Cast from 'JedisCommands' to 'DynoJedisClient' here since the former does not expose 'eval()'.
retval = (ArrayList) ((DynoJedisClient) quorumConn).eval(popPredicateObeyPriority,
Collections.singletonList(messageStoreKey), builder.build());
}
if (retval.size() == 0) return null;
return new Message(retval.get(0), retval.get(1));
}
@Override
public Message popMsgWithPredicate(String predicate, boolean localShardOnly) {
Stopwatch sw = monitor.start(monitor.pop, 1);
try {
Message payload = execute("popMsgWithPredicateObeyPriority", messageStoreKey, () -> popMsgWithPredicateObeyPriority(predicate, localShardOnly));
return payload;