-
Notifications
You must be signed in to change notification settings - Fork 38
Added TopicRetryableStream with support of RetryPolicy #628
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f409bb4
Added base TopicStream
alex268 f0020fe
Added TopicRetryableStream
alex268 1a3afd0
Updated streams base implementation
alex268 b60e3df
Small fixes
alex268 6a2c087
Added tests for TopicStream & TopicRetryableStream
alex268 d7c4eb8
Fixed by copilot
alex268 c369fc6
Fixed data race on writer onInit
alex268 2bcb0bc
Fixed flap test
alex268 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package tech.ydb.topic.impl; | ||
|
|
||
| import java.util.concurrent.ThreadLocalRandom; | ||
|
|
||
| /** | ||
| * | ||
| * @author Aleksandr Gorshenin | ||
| */ | ||
| public class DebugTools { | ||
| private static final int ID_LENGTH = 6; | ||
| private static final char[] ID_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" | ||
| .toCharArray(); | ||
|
|
||
| private DebugTools() { } | ||
|
|
||
| public static String createDebugId(String id) { | ||
| if (id != null) { | ||
| return id; | ||
| } | ||
|
|
||
| return ThreadLocalRandom.current().ints(0, ID_ALPHABET.length) | ||
| .limit(ID_LENGTH) | ||
| .map(charId -> ID_ALPHABET[charId]) | ||
| .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) | ||
| .toString(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
154 changes: 154 additions & 0 deletions
154
topic/src/main/java/tech/ydb/topic/impl/TopicRetryableStream.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| package tech.ydb.topic.impl; | ||
|
|
||
| import java.util.concurrent.ScheduledExecutorService; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
|
|
||
| import com.google.protobuf.Message; | ||
| import org.slf4j.Logger; | ||
|
|
||
| import tech.ydb.common.retry.RetryConfig; | ||
| import tech.ydb.common.retry.RetryPolicy; | ||
| import tech.ydb.core.Status; | ||
| import tech.ydb.core.StatusCode; | ||
|
|
||
| public abstract class TopicRetryableStream<R extends Message, W extends Message> { | ||
| private final Logger logger; | ||
| private final String debugId; | ||
| private final RetryConfig retryConfig; | ||
| private final ScheduledExecutorService scheduler; | ||
|
|
||
| private final AtomicReference<TopicStream<R, W>> realStream = new AtomicReference<>(); | ||
| private final AtomicInteger streamCount = new AtomicInteger(0); | ||
| private final RetryState state = new RetryState(); | ||
|
|
||
| private volatile boolean isClosed = false; | ||
|
|
||
| public TopicRetryableStream(Logger logger, String debugId, RetryConfig config, ScheduledExecutorService scheduler) { | ||
| this.debugId = debugId; | ||
| this.logger = logger; | ||
| this.retryConfig = config; | ||
| this.scheduler = scheduler; | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Session[" + debugId + "]"; | ||
| } | ||
|
|
||
| protected abstract TopicStream<R, W> createNewStream(String debugId); | ||
| protected abstract W getInitRequest(); | ||
|
|
||
| protected abstract void onNext(R message); | ||
|
|
||
| protected abstract void onRetry(Status status); | ||
| protected abstract void onClose(Status status); | ||
|
|
||
| public void start() { | ||
| if (isClosed) { | ||
| return; | ||
| } | ||
|
|
||
| String streamID = debugId + '.' + streamCount.incrementAndGet(); | ||
| TopicStream<R, W> stream = createNewStream(streamID); | ||
|
|
||
| if (!realStream.compareAndSet(null, stream)) { | ||
| logger.warn("{} double start of stream, skipping", this); | ||
| stream.close(); | ||
| return; | ||
| } | ||
|
|
||
| stream.start(getInitRequest(), this::onNext).whenComplete((status, th) -> { | ||
| realStream.compareAndSet(stream, null); | ||
| if (status != null) { | ||
| onStreamStop(status, retryConfig.getStatusRetryPolicy(status)); | ||
| } | ||
| if (th != null) { | ||
| Status wrapped = Status.of(StatusCode.CLIENT_INTERNAL_ERROR, th); | ||
| onStreamStop(wrapped, retryConfig.getThrowableRetryPolicy(th)); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| protected void resetRetries() { | ||
| state.reset(); | ||
| } | ||
|
|
||
| public void send(W msg) { | ||
| TopicStream<R, W> stream = realStream.get(); | ||
| if (stream == null) { | ||
| logger.warn("{} send message before stream is ready", this); | ||
| return; | ||
| } | ||
| stream.send(msg); | ||
| } | ||
|
|
||
| public void close() { | ||
| isClosed = true; | ||
| TopicStream<R, W> stream = realStream.getAndSet(null); | ||
| if (stream != null) { | ||
| stream.close(); | ||
| } | ||
| } | ||
|
|
||
| private void onStreamStop(Status status, RetryPolicy policy) { | ||
| if (isClosed) { // stream was already closed (usually with success) | ||
| onClose(status); | ||
| return; | ||
| } | ||
|
|
||
| if (policy == null) { | ||
| logger.warn("{} stopped by non-retryable status {}", this, status); | ||
| onClose(status); | ||
| return; | ||
| } | ||
|
|
||
| long nextRetryMs = state.nextRetryMs(policy); | ||
|
|
||
| if (nextRetryMs < 0) { | ||
| logger.warn("{} stopped after retry policy evaluation for status {}", this, status); | ||
| onClose(status); | ||
| return; | ||
| } | ||
|
|
||
| if (nextRetryMs == 0) { // retry immediately | ||
| logger.warn("{} retry #{}. Retry immediately...", this, state.retryNumber()); | ||
| onRetry(status); | ||
| start(); | ||
| return; | ||
| } | ||
|
|
||
| // retry scheduling | ||
| logger.warn("{} retry #{}. Scheduling reconnect in {}ms...", debugId, state.retryNumber(), nextRetryMs); | ||
| onRetry(status); | ||
|
|
||
| try { | ||
| scheduler.schedule(this::start, nextRetryMs, TimeUnit.MILLISECONDS); | ||
| } catch (Exception ex) { | ||
| logger.error("{} cannot schedule reconnect, stopping", debugId, ex); | ||
| onClose(status); | ||
| } | ||
|
alex268 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private static class RetryState { | ||
| private final AtomicInteger count = new AtomicInteger(); | ||
| private volatile long startedAt = 0; | ||
|
|
||
| public long nextRetryMs(RetryPolicy policy) { | ||
| int retryNumber = count.getAndIncrement(); | ||
| if (retryNumber == 0) { | ||
| startedAt = System.currentTimeMillis(); | ||
| } | ||
| return policy.nextRetryMs(retryNumber, System.currentTimeMillis() - startedAt); | ||
| } | ||
|
|
||
| public int retryNumber() { | ||
| return count.get(); | ||
| } | ||
|
|
||
| public void reset() { | ||
| count.set(0); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| package tech.ydb.topic.impl; | ||
|
|
||
| import java.util.Objects; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.function.Consumer; | ||
|
|
||
| import com.google.protobuf.Message; | ||
| import org.slf4j.Logger; | ||
|
|
||
| import tech.ydb.core.Status; | ||
| import tech.ydb.core.StatusCode; | ||
| import tech.ydb.core.grpc.GrpcReadWriteStream; | ||
|
|
||
| public abstract class TopicStream<R extends Message, W extends Message> { | ||
| private final Logger logger; | ||
| private final String debugId; | ||
| private final GrpcReadWriteStream<R, W> stream; | ||
| private final CompletableFuture<Status> streamStatus = new CompletableFuture<>(); | ||
| private volatile String token; | ||
|
|
||
| public TopicStream(Logger logger, String debugId, GrpcReadWriteStream<R, W> stream) { | ||
| this.logger = logger; | ||
| this.debugId = debugId; | ||
| this.stream = stream; | ||
| this.token = stream.authToken(); | ||
| } | ||
|
|
||
| protected abstract W updateTokenMessage(String token); | ||
| protected abstract Status parseMessageStatus(R message); | ||
|
|
||
| public CompletableFuture<Status> start(W initReq, Consumer<R> messageHandler) { | ||
| this.logger.debug("[{}] is about to start", debugId); | ||
| this.stream.start((R msg) -> { | ||
| Status messageStatus = parseMessageStatus(msg); | ||
| if (messageStatus.isSuccess()) { | ||
| messageHandler.accept(msg); | ||
| } else { | ||
| logger.warn("[{}] stopped by getting status {}", debugId, messageStatus); | ||
| if (streamStatus.complete(messageStatus)) { | ||
| stream.close(); | ||
| } | ||
| } | ||
| }).whenComplete((st, th) -> { | ||
| Status status = st != null ? st : Status.of(StatusCode.CLIENT_INTERNAL_ERROR, th); | ||
| logger.debug("[{}] finished with status {}", debugId, status); | ||
| streamStatus.complete(status); | ||
| }); | ||
|
|
||
| if (!streamStatus.isDone()) { | ||
| stream.sendNext(initReq); | ||
| } | ||
|
|
||
| return streamStatus; | ||
| } | ||
|
|
||
| public void close() { | ||
| logger.debug("[{}] closed by app", debugId); | ||
| if (!streamStatus.isDone()) { | ||
| stream.close(); | ||
| } | ||
| } | ||
|
|
||
| public void send(W req) { | ||
| if (streamStatus.isDone()) { | ||
| logger.warn("[{}] is already closed. Next message with type {} was NOT sent", debugId, | ||
| req.getDescriptorForType().getName()); | ||
| return; | ||
| } | ||
|
|
||
| String currentToken = stream.authToken(); | ||
| if (!Objects.equals(token, currentToken)) { | ||
| token = currentToken; | ||
| logger.info("{} sends new token", this); | ||
| stream.sendNext(updateTokenMessage(token)); | ||
| } | ||
|
|
||
| stream.sendNext(req); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
topic/src/test/java/tech/ydb/topic/impl/DebugToolsTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package tech.ydb.topic.impl; | ||
|
|
||
| import org.junit.Assert; | ||
| import org.junit.Test; | ||
|
|
||
| /** | ||
| * | ||
| * @author Aleksandr Gorshenin | ||
| */ | ||
| public class DebugToolsTest { | ||
| @Test | ||
| public void createDebugIdTest() { | ||
| Assert.assertEquals("custom-id", DebugTools.createDebugId("custom-id")); | ||
|
|
||
| String newID = DebugTools.createDebugId(null); | ||
| Assert.assertNotNull(newID); | ||
| Assert.assertEquals(6, newID.length()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.