-
Notifications
You must be signed in to change notification settings - Fork 1k
Provide a way to complete a ClientRequestContext in Preprocessor
#6466
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 1 commit
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
51f0790
minimal impl
jrhee17 4fd6854
Merge branch 'main' into feat/xds-error-step1
ikhoon 91a4e86
fix flakiness
jrhee17 75b7084
address comments by @minwoox
jrhee17 c421b52
handle flaky test
jrhee17 82185c2
address comment by @minwoox
jrhee17 4cee5ad
Merge branch 'main' into feat/xds-error-step1
jrhee17 cbdeab3
fix test failure
jrhee17 d452566
Merge branch 'main' into feat/xds-error-step1
jrhee17 5f58091
address comments by @minwoox and @ikhoon
jrhee17 e7ad7a1
update blockhound rule
jrhee17 7afc72d
Merge remote-tracking branch 'origin/main' into feat/xds-error-step1
jrhee17 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
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
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 |
|---|---|---|
|
|
@@ -30,6 +30,7 @@ | |
| import java.util.Objects; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; | ||
| import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; | ||
| import java.util.function.Consumer; | ||
| import java.util.function.Function; | ||
|
|
@@ -116,6 +117,10 @@ public final class DefaultClientRequestContext | |
| whenInitializedUpdater = AtomicReferenceFieldUpdater.newUpdater( | ||
| DefaultClientRequestContext.class, CompletableFuture.class, "whenInitialized"); | ||
|
|
||
| private static final AtomicIntegerFieldUpdater<DefaultClientRequestContext> | ||
| initializationTriggeredUpdater = AtomicIntegerFieldUpdater.newUpdater( | ||
| DefaultClientRequestContext.class, "initializationTriggered"); | ||
|
|
||
| private static SessionProtocol desiredSessionProtocol(SessionProtocol protocol, ClientOptions options) { | ||
| if (!options.factory().options().preferHttp1()) { | ||
| return protocol; | ||
|
|
@@ -134,7 +139,8 @@ private static SessionProtocol desiredSessionProtocol(SessionProtocol protocol, | |
| private static final short STR_PARENT_LOG_AVAILABILITY = 1 << 1; | ||
| private static boolean warnedNullRequestId; | ||
|
|
||
| private boolean initialized; | ||
| // 0: not initialized, 1: initialized | ||
| private volatile int initializationTriggered; | ||
| @Nullable | ||
| private EventLoop eventLoop; | ||
| private EndpointGroup endpointGroup; | ||
|
|
@@ -358,9 +364,10 @@ private static ServiceRequestContext serviceRequestContext() { | |
|
|
||
| @Override | ||
| public CompletableFuture<Boolean> init() { | ||
| if (!initializationTriggeredUpdater.compareAndSet(this, 0, 1)) { | ||
| return whenInitialized(); | ||
| } | ||
| assert endpoint == null : endpoint; | ||
| assert !initialized; | ||
| initialized = true; | ||
|
|
||
| final Throwable cancellationCause = cancellationCause(); | ||
| if (cancellationCause != null) { | ||
|
|
@@ -383,6 +390,29 @@ public CompletableFuture<Boolean> init() { | |
| } | ||
| } | ||
|
|
||
| @Override | ||
| public boolean initAndFail(Throwable cause) { | ||
| if (!initializationTriggeredUpdater.compareAndSet(this, 0, 1)) { | ||
| return false; | ||
| } | ||
| acquireEventLoop(endpointGroup); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Probably, we don't need to call |
||
| failEarly(cause); | ||
| finishInitialization(false); | ||
| return true; | ||
| } | ||
|
|
||
| private void initNow() { | ||
| if (!initializationTriggeredUpdater.compareAndSet(this, 0, 1)) { | ||
| return; | ||
| } | ||
| finishInitialization(false); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean initializationTriggered() { | ||
| return initializationTriggered == 1; | ||
| } | ||
|
|
||
| private EndpointGroup mapEndpoint(EndpointGroup endpointGroup) { | ||
| if (endpointGroup instanceof Endpoint) { | ||
| return requireNonNull(options().endpointRemapper().apply((Endpoint) endpointGroup), | ||
|
|
@@ -462,13 +492,17 @@ public CompletableFuture<Boolean> whenInitialized() { | |
| public void finishInitialization(boolean success) { | ||
| final CompletableFuture<Boolean> whenInitialized = this.whenInitialized; | ||
| if (whenInitialized != null) { | ||
| whenInitialized.complete(success); | ||
| if (!whenInitialized.isDone()) { | ||
| whenInitialized.complete(success); | ||
| } | ||
| } else { | ||
| if (!whenInitializedUpdater.compareAndSet(this, null, | ||
| UnmodifiableFuture.completedFuture(success))) { | ||
| final CompletableFuture<Boolean> oldWhenInitialized = this.whenInitialized; | ||
| assert oldWhenInitialized != null; | ||
| oldWhenInitialized.complete(success); | ||
| if (!oldWhenInitialized.isDone()) { | ||
| oldWhenInitialized.complete(success); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -540,6 +574,7 @@ private void failEarly(Throwable cause) { | |
| final RequestLogBuilder logBuilder = logBuilder(); | ||
| logBuilder.endRequest(wrapped); | ||
| logBuilder.endResponse(wrapped); | ||
| responseCancellationScheduler.finishNow(cause); | ||
| } | ||
|
|
||
| // TODO(ikhoon): Consider moving the logic for filling authority to `HttpClientDelegate.exceute()`. | ||
|
|
@@ -616,6 +651,9 @@ private DefaultClientRequestContext(DefaultClientRequestContext ctx, | |
|
|
||
| this.endpointGroup = endpointGroup; | ||
| updateEndpoint(endpoint); | ||
| if (endpoint != null) { | ||
| initNow(); | ||
| } | ||
| // We don't need to acquire an EventLoop for the initial attempt because it's already acquired by | ||
| // the root context. | ||
| if (endpoint == null || ctx.endpoint() == endpoint && ctx.log.children().isEmpty()) { | ||
|
|
@@ -683,7 +721,7 @@ public SessionProtocol sessionProtocol() { | |
|
|
||
| @Override | ||
| public void setSessionProtocol(SessionProtocol sessionProtocol) { | ||
| checkState(!initialized, "Cannot update sessionProtocol after initialization"); | ||
| checkState(!initializationTriggered(), "Cannot update sessionProtocol after initialization"); | ||
| this.sessionProtocol = desiredSessionProtocol(requireNonNull(sessionProtocol, "sessionProtocol"), | ||
| options); | ||
| } | ||
|
|
@@ -789,7 +827,7 @@ public ContextAwareEventLoop eventLoop() { | |
|
|
||
| @Override | ||
| public void setEventLoop(EventLoop eventLoop) { | ||
| checkState(!initialized, "Cannot update eventLoop after initialization"); | ||
| checkState(!initializationTriggered(), "Cannot update eventLoop after initialization"); | ||
| checkState(this.eventLoop == null, "eventLoop can be updated only once"); | ||
| this.eventLoop = requireNonNull(eventLoop, "eventLoop"); | ||
| initializeResponseCancellationScheduler(); | ||
|
|
@@ -820,7 +858,7 @@ public EndpointGroup endpointGroup() { | |
|
|
||
| @Override | ||
| public void setEndpointGroup(EndpointGroup endpointGroup) { | ||
| checkState(!initialized, "Cannot update endpointGroup after initialization"); | ||
| checkState(!initializationTriggered(), "Cannot update endpointGroup after initialization"); | ||
| this.endpointGroup = requireNonNull(endpointGroup, "endpointGroup"); | ||
| } | ||
|
|
||
|
|
@@ -1035,7 +1073,14 @@ public CancellationScheduler responseCancellationScheduler() { | |
| @Override | ||
| public void cancel(Throwable cause) { | ||
| requireNonNull(cause, "cause"); | ||
| responseCancellationScheduler.finishNow(cause); | ||
| if (initializationTriggered()) { | ||
| // happy path | ||
| responseCancellationScheduler.finishNow(cause); | ||
| return; | ||
| } | ||
| if (!initAndFail(cause)) { | ||
| responseCancellationScheduler.finishNow(cause); | ||
| } | ||
| } | ||
|
|
||
| @Nullable | ||
|
|
||
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
78 changes: 78 additions & 0 deletions
78
grpc/src/test/java/com/linecorp/armeria/client/grpc/GrpcPreprocessorTest.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,78 @@ | ||
| /* | ||
| * Copyright 2025 LY Corporation | ||
| * | ||
| * LY Corporation 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: | ||
| * | ||
| * https://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 com.linecorp.armeria.client.grpc; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.assertj.core.api.Assertions.catchException; | ||
| import static org.awaitility.Awaitility.await; | ||
|
|
||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import com.linecorp.armeria.client.ClientRequestContextCaptor; | ||
| import com.linecorp.armeria.client.Clients; | ||
| import com.linecorp.armeria.common.HttpResponse; | ||
| import com.linecorp.armeria.internal.client.DefaultClientRequestContext; | ||
|
|
||
| import io.grpc.Status; | ||
| import io.grpc.StatusRuntimeException; | ||
| import testing.grpc.EmptyProtos.Empty; | ||
| import testing.grpc.TestServiceGrpc.TestServiceBlockingStub; | ||
|
|
||
| class GrpcPreprocessorTest { | ||
|
|
||
| @Test | ||
| void throwCompletesContext() { | ||
| final RuntimeException exception = new RuntimeException("test"); | ||
| try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) { | ||
| final TestServiceBlockingStub stub = GrpcClients.builder((delegate, ctx, req) -> { | ||
| throw exception; | ||
| }).build(TestServiceBlockingStub.class); | ||
|
|
||
| final Exception thrown = catchException(() -> stub.emptyCall(Empty.getDefaultInstance())); | ||
| assertThat(thrown).isInstanceOf(StatusRuntimeException.class); | ||
| assertThat((StatusRuntimeException) thrown).hasCause(exception); | ||
| final DefaultClientRequestContext ctx = (DefaultClientRequestContext) captor.get(); | ||
| await().untilAsserted(() -> assertThat(ctx.whenInitialized()).isDone()); | ||
| await().untilAsserted(() -> assertThat(ctx.log().isComplete()).isTrue()); | ||
| assertThat(ctx.eventLoop()).isNotNull(); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void cancelCompletesContext() { | ||
| final RuntimeException exception = new RuntimeException("test"); | ||
| try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) { | ||
| final TestServiceBlockingStub stub = GrpcClients.builder((delegate, ctx, req) -> { | ||
| return HttpResponse.of(CompletableFuture.supplyAsync(() -> { | ||
| ctx.cancel(); | ||
| throw exception; | ||
| })); | ||
| }).build(TestServiceBlockingStub.class); | ||
|
|
||
| final Exception thrown = catchException(() -> stub.emptyCall(Empty.getDefaultInstance())); | ||
| assertThat(thrown).isInstanceOf(StatusRuntimeException.class); | ||
| final Status status = ((StatusRuntimeException) thrown).getStatus(); | ||
| assertThat(status.getCause()).isSameAs(exception); | ||
| final DefaultClientRequestContext ctx = (DefaultClientRequestContext) captor.get(); | ||
| await().untilAsserted(() -> assertThat(ctx.whenInitialized()).isDone()); | ||
| await().untilAsserted(() -> assertThat(ctx.log().isComplete()).isTrue()); | ||
| assertThat(ctx.eventLoop()).isNotNull(); | ||
| } | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about moving the call to
completeLogIfIncompletefrom line 111 to here? It seems like it would prevent the case where an http response is returned in the pre decorator.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't we also change this line?
futureConverter, errorResponseFactory, req, false);armeria/core/src/main/java/com/linecorp/armeria/internal/client/TailPreClient.java
Line 82 in 89e1a84
Additionally, this isn't related to this PR but shouldn't
tryCompleteLogbetruein these lines? cc @ikhoonarmeria/core/src/main/java/com/linecorp/armeria/client/retry/RetryingClient.java
Lines 325 to 328 in 51f0790
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Understood that the intention is that
completeLogIfIncompleteis already registered when preclients are invoked, and hence another callback doesn't need to be addedThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ikhoon Do you have any opinion on this?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tryCompleteLogshould befalsesince RetryingClient registers its own callbacks which are optimized forRetryRule.armeria/core/src/main/java/com/linecorp/armeria/client/retry/RetryingClient.java
Line 340 in 51f0790
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah I missed it. Thanks for the explanation. 😉
@jrhee17 Would you mind adding a comment for that?
e.g.
// tryCompleteLog is false because we handle it in completeLogIfBytesNotTransferred.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Side note) I couldn’t immediately tell the difference between the two just from the function name
executeWithFallback. Renaming them to something more explicit likeexecutePreClientandexecuteClientwould make the context clearer during code review.