kevin-wu24 commented on code in PR #23136: URL: https://github.com/apache/kafka/pull/23136#discussion_r3763457602
########## raft/src/testFixtures/java/org/apache/kafka/raft/SharedRaftClientContext.java: ########## @@ -0,0 +1,704 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.apache.kafka.raft; + +import org.apache.kafka.common.Node; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.Uuid; +import org.apache.kafka.common.message.AddRaftVoterRequestData; +import org.apache.kafka.common.message.AddRaftVoterResponseData; +import org.apache.kafka.common.message.ApiVersionsResponseData; +import org.apache.kafka.common.message.BeginQuorumEpochRequestData; +import org.apache.kafka.common.message.BeginQuorumEpochResponseData; +import org.apache.kafka.common.message.DescribeQuorumRequestData; +import org.apache.kafka.common.message.DescribeQuorumResponseData; +import org.apache.kafka.common.message.EndQuorumEpochRequestData; +import org.apache.kafka.common.message.EndQuorumEpochResponseData; +import org.apache.kafka.common.message.FetchRequestData; +import org.apache.kafka.common.message.FetchResponseData; +import org.apache.kafka.common.message.FetchSnapshotRequestData; +import org.apache.kafka.common.message.FetchSnapshotResponseData; +import org.apache.kafka.common.message.RemoveRaftVoterRequestData; +import org.apache.kafka.common.message.RemoveRaftVoterResponseData; +import org.apache.kafka.common.message.UpdateRaftVoterRequestData; +import org.apache.kafka.common.message.UpdateRaftVoterResponseData; +import org.apache.kafka.common.message.VoteRequestData; +import org.apache.kafka.common.message.VoteResponseData; +import org.apache.kafka.common.protocol.ApiKeys; +import org.apache.kafka.common.protocol.ApiMessage; +import org.apache.kafka.common.protocol.ByteBufferAccessor; +import org.apache.kafka.common.protocol.DataOutputStreamWritable; +import org.apache.kafka.common.protocol.Errors; +import org.apache.kafka.common.protocol.ObjectSerializationCache; +import org.apache.kafka.common.utils.MockTime; +import org.apache.kafka.server.common.KRaftVersion; +import org.apache.kafka.test.TestCondition; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.OptionalLong; + +/** + * The shared machinery for driving a mock {@link KafkaRaftClient} through the raft protocol. + * {@link RaftClientTestContext} extends this and overrides the relevant helpers to add protocol + * assertions, calling {@code super} for the shared work. + */ +public abstract class SharedRaftClientContext { + final TopicPartition metadataPartition = RaftClientContextBuilder.METADATA_PARTITION; + final Uuid metadataTopicId = Uuid.METADATA_TOPIC_ID; + final int fetchMaxBytes; + + int electionTimeoutMs; + + final MockQuorumStateStore quorumStateStore; + final String clusterId; + final OptionalInt localId; + public final Uuid localDirectoryId; + public final KRaftVersion kraftVersion; + public final KafkaRaftClient<String> client; + public final MockLog log; + final MockNetworkChannel channel; + final MockTime time; + final VoterSet startingVoters; + // Used to determine which RPC request and response to construct + final RaftProtocol raftProtocol; + + private final List<RaftResponse.Outbound> sentResponses = new ArrayList<>(); + private final List<Throwable> uncaughtExceptions = new ArrayList<>(); + + private static final int MAX_POLLS = 50; + + @SuppressWarnings("ParameterNumber") + SharedRaftClientContext( + String clusterId, + OptionalInt localId, + Uuid localDirectoryId, + KRaftVersion kraftVersion, + KafkaRaftClient<String> client, + MockLog log, + MockNetworkChannel channel, + MockTime time, + MockQuorumStateStore quorumStateStore, + VoterSet startingVoters, + RaftProtocol raftProtocol, + int fetchMaxBytes + ) { + this.clusterId = clusterId; + this.localId = localId; + this.localDirectoryId = localDirectoryId; + this.kraftVersion = kraftVersion; + this.client = client; + this.log = log; + this.channel = channel; + this.time = time; + this.quorumStateStore = quorumStateStore; + this.startingVoters = startingVoters; + this.raftProtocol = raftProtocol; + this.fetchMaxBytes = fetchMaxBytes; + } + + public void unattachedToCandidate() throws Exception { + time.sleep(electionTimeoutMs * 2L); + expectAndGrantPreVotes(currentEpoch()); + } + + public void unattachedToLeader() throws Exception { + int currentEpoch = currentEpoch(); + unattachedToCandidate(); + expectAndGrantVotes(currentEpoch + 1); + expectBeginEpoch(currentEpoch + 1); + } + + public OptionalInt currentLeader() { + return currentLeaderAndEpoch().leaderId(); + } + + public int currentEpoch() { + return currentLeaderAndEpoch().epoch(); + } + + LeaderAndEpoch currentLeaderAndEpoch() { + ElectionState election = quorumStateStore.readElectionState().get(); + return new LeaderAndEpoch(election.optionalLeaderId(), election.epoch()); + } + + void expectAndGrantVotes(int epoch) throws Exception { + pollUntilRequest(); + + List<RaftRequest.Outbound> voteRequests = collectVoteRequests(epoch, + log.lastFetchedEpoch(), log.endOffset().offset()); + + for (RaftRequest.Outbound request : voteRequests) { + VoteResponseData voteResponse = voteResponse(true, OptionalInt.empty(), epoch); + deliverResponse(request.correlationId(), request.destination(), voteResponse); + } + + pollUntil(() -> client.quorum().isLeader()); + } + + void expectAndGrantPreVotes(int epoch) throws Exception { + pollUntilRequest(); + + List<RaftRequest.Outbound> voteRequests = collectPreVoteRequests( + epoch, + log.lastFetchedEpoch(), + log.endOffset().offset() + ); + + for (RaftRequest.Outbound request : voteRequests) { + if (!raftProtocol.isPreVoteSupported()) { + deliverResponse( + request.correlationId(), + request.destination(), + RaftUtil.errorResponse(ApiKeys.VOTE, Errors.UNSUPPORTED_VERSION) + ); + } else { + VoteResponseData voteResponse = voteResponse(true, OptionalInt.empty(), epoch); + deliverResponse(request.correlationId(), request.destination(), voteResponse); + } + } + + pollUntil(() -> client.quorum().isCandidate()); + } + + int localIdOrThrow() { + return localId.orElseThrow(() -> new AssertionError("Required local id is not defined")); + } + + private void expectBeginEpoch(int epoch) throws Exception { + pollUntilRequest(); + for (RaftRequest.Outbound request : collectBeginEpochRequests(epoch)) { + BeginQuorumEpochResponseData beginEpochResponse = beginEpochResponse(epoch, localIdOrThrow()); + deliverResponse(request.correlationId(), request.destination(), beginEpochResponse); + poll(); + } + } + + /** + * Asserts that no uncaught exceptions occurred in async callbacks (e.g., CompletionStage.whenComplete). + * This method is automatically called by the poll() wrapper method, but can also be called directly + * by tests to check for async exceptions at any point. + * + * @throws AssertionError if any uncaught exceptions were captured + */ + public void assertNoAsyncExceptions() { + if (!uncaughtExceptions.isEmpty()) { + Throwable first = uncaughtExceptions.get(0); + uncaughtExceptions.clear(); + throw new AssertionError("Uncaught exception in async callback", first); + } + } + + /** + * Poll for new events and check for any uncaught exceptions in async callbacks. + * This is a wrapper around client.poll() that also calls assertNoAsyncExceptions(). + */ + public void poll() { + client.poll(); + assertNoAsyncExceptions(); + } + + public void pollUntil(TestCondition condition) throws InterruptedException { + try { + for (int remaining = MAX_POLLS; remaining > 0; remaining--) { + poll(); + if (condition.conditionMet()) { + return; + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + throw new IllegalStateException( + String.format("Condition not met within %d polls", MAX_POLLS) + ); + } + + public void pollUntilResponse() throws InterruptedException { + pollUntil(() -> !sentResponses.isEmpty()); + } + + void pollUntilRequest() throws InterruptedException { + pollUntil(channel::hasSentRequests); + } + + // RaftClientTestContext overrides this to also assert the collected requests are pre-votes. + List<RaftRequest.Outbound> collectPreVoteRequests( + int epoch, + int lastEpoch, + long lastEpochOffset + ) { + return collectVoteRequestMessages(); + } + + // RaftClientTestContext overrides this to also assert the collected requests are (standard) votes. + List<RaftRequest.Outbound> collectVoteRequests( + int epoch, + int lastEpoch, + long lastEpochOffset + ) { + return collectVoteRequestMessages(); + } + + private List<RaftRequest.Outbound> collectVoteRequestMessages() { + List<RaftRequest.Outbound> voteRequests = new ArrayList<>(); + for (RaftRequest.Outbound raftMessage : channel.drainSendQueue()) { + if (raftMessage.data() instanceof VoteRequestData) { + voteRequests.add(raftMessage); + } + } + return voteRequests; + } + + // Round-trips a message through serialization to mimic the network, exercising the client's + // request/response encoding on every delivery. The benchmark context overrides this to skip the + // round trip so it is not measured as the client's own work. + ApiMessage maybeRoundTrip(ApiMessage message, short version) { + return roundTripApiMessage(message, version); + } + + private ApiMessage roundTripApiMessage(ApiMessage message, short version) { + ObjectSerializationCache cache = new ObjectSerializationCache(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(message.size(cache, version)); + + // Encode the message to a byte array with the given version + DataOutputStreamWritable writer = new DataOutputStreamWritable(new DataOutputStream(buffer)); + message.write(writer, cache, version); + + // Decode the message from the byte array + ByteBufferAccessor reader = new ByteBufferAccessor(ByteBuffer.wrap(buffer.toByteArray())); + message.read(reader, version); + + return message; + } + + public void deliverRequest(ApiMessage request) { + short version = raftRequestVersion(request); + deliverRequest(request, version); + } + + void deliverRequest(ApiMessage request, short version) { + deliverRequest(inboundRequest(request, version)); + } + + public RaftRequest.Inbound inboundRequest(ApiMessage request) { + return inboundRequest(request, raftRequestVersion(request)); + } + + private RaftRequest.Inbound inboundRequest(ApiMessage request, short version) { + ApiMessage versionedRequest = maybeRoundTrip(request, version); + return new RaftRequest.Inbound( + channel.listenerName(), + channel.newCorrelationId(), + version, + versionedRequest, + time.milliseconds() + ); + } Review Comment: ```suggestion RaftRequest.Inbound inboundRequest(ApiMessage request, short version) { return new RaftRequest.Inbound( channel.listenerName(), channel.newCorrelationId(), version, versionedRequest, time.milliseconds() ); } ``` Then in `RaftClientTestContext` you can override this and say: ``` @Override RaftRequest.Inbound inboundRequest(ApiMessage request, short version) { ApiMessage msg = roundTripApiMessage(request, version); return super.inboundRequest(msg, version); } ``` That would get rid of `maybeRoundTrip` and `roundTripApiMessage` from the super class. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
