use of org.apache.ratis.RaftTestUtil.waitForLeader in project incubator-ratis by apache.
the class RaftAsyncTests method testStaleReadAsync.
@Test
public void testStaleReadAsync() throws Exception {
final int numMesssages = 10;
final CLUSTER cluster = getFactory().newCluster(NUM_SERVERS, properties);
try (RaftClient client = cluster.createClient()) {
cluster.start();
RaftTestUtil.waitForLeader(cluster);
// submit some messages
final List<CompletableFuture<RaftClientReply>> futures = new ArrayList<>();
for (int i = 0; i < numMesssages; i++) {
final String s = "m" + i;
LOG.info("sendAsync " + s);
futures.add(client.sendAsync(new RaftTestUtil.SimpleMessage(s)));
}
Assert.assertEquals(numMesssages, futures.size());
RaftClientReply lastWriteReply = null;
for (CompletableFuture<RaftClientReply> f : futures) {
lastWriteReply = f.join();
Assert.assertTrue(lastWriteReply.isSuccess());
}
futures.clear();
// Use a follower with the max commit index
final RaftPeerId leader = lastWriteReply.getServerId();
LOG.info("leader = " + leader);
final Collection<CommitInfoProto> commitInfos = lastWriteReply.getCommitInfos();
LOG.info("commitInfos = " + commitInfos);
final CommitInfoProto followerCommitInfo = commitInfos.stream().filter(info -> !RaftPeerId.valueOf(info.getServer().getId()).equals(leader)).max(Comparator.comparing(CommitInfoProto::getCommitIndex)).get();
final RaftPeerId follower = RaftPeerId.valueOf(followerCommitInfo.getServer().getId());
LOG.info("max follower = " + follower);
// test a failure case
testFailureCaseAsync("sendStaleReadAsync(..) with a larger commit index", () -> client.sendStaleReadAsync(new RaftTestUtil.SimpleMessage("" + (numMesssages + 1)), followerCommitInfo.getCommitIndex(), follower), StateMachineException.class, IndexOutOfBoundsException.class);
// test sendStaleReadAsync
for (int i = 1; i < followerCommitInfo.getCommitIndex(); i++) {
final int query = i;
LOG.info("sendStaleReadAsync, query=" + query);
final Message message = new RaftTestUtil.SimpleMessage("" + query);
final CompletableFuture<RaftClientReply> readFuture = client.sendReadOnlyAsync(message);
final CompletableFuture<RaftClientReply> staleReadFuture = client.sendStaleReadAsync(message, followerCommitInfo.getCommitIndex(), follower);
futures.add(readFuture.thenApply(r -> getMessageContent(r)).thenCombine(staleReadFuture.thenApply(r -> getMessageContent(r)), (expected, computed) -> {
try {
LOG.info("query " + query + " returns " + LogEntryProto.parseFrom(expected).getSmLogEntry().getData().toStringUtf8());
} catch (InvalidProtocolBufferException e) {
throw new CompletionException(e);
}
Assert.assertEquals("log entry mismatch for query=" + query, expected, computed);
return null;
}));
}
JavaUtils.allOf(futures).join();
} finally {
cluster.shutdown();
}
}
Aggregations