-
Notifications
You must be signed in to change notification settings - Fork 17
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
Simplify UnaryBlockingCall #225
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
536d92a
Simplify UnaryBlockingCall
jhump 4af7f5d
add some type aliases and comments to clarify the UnaryCall impl; add…
jhump ea06ddc
make tests faster/deterministic; add test for when cancel is called b…
jhump 5e23db9
consolidate test further
jhump 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 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 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 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,85 @@ | ||
// Copyright 2022-2023 The Connect Authors | ||
// | ||
// 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 | ||
// | ||
// 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 com.connectrpc.impl | ||
|
||
import com.connectrpc.ResponseMessage | ||
import com.connectrpc.UnaryBlockingCall | ||
import com.connectrpc.http.Cancelable | ||
import java.util.concurrent.CountDownLatch | ||
import java.util.concurrent.atomic.AtomicBoolean | ||
import java.util.concurrent.atomic.AtomicReference | ||
|
||
/** | ||
* Callback that handles asynchronous response. | ||
*/ | ||
internal typealias ResponseCallback<T> = (ResponseMessage<T>) -> Unit | ||
|
||
/** | ||
* Represents a cancelable asynchronous operation. When the function | ||
* is invoked, the operation is initiated. When that operation completes | ||
* it MUST invoke the callback, even when canceled. The value returned | ||
* from the function can be called to abort the operation and have it | ||
* return early. | ||
*/ | ||
internal typealias AsyncOperation<T> = (callback: ResponseCallback<T>) -> Cancelable | ||
|
||
/** | ||
* Concrete implementation of [UnaryBlockingCall] which transforms | ||
* the given async operation into a synchronous/blocking one. | ||
*/ | ||
internal class UnaryCall<Output>( | ||
private val block: AsyncOperation<Output>, | ||
) : UnaryBlockingCall<Output> { | ||
private val executed = AtomicBoolean() | ||
|
||
/** | ||
* initialized to null and then replaced with non-null | ||
* function when [execute] or [cancel] is called. | ||
*/ | ||
private var cancelFunc = AtomicReference<Cancelable>() | ||
|
||
/** | ||
* Execute the underlying operation and block until it completes. | ||
*/ | ||
override fun execute(): ResponseMessage<Output> { | ||
check(executed.compareAndSet(false, true)) { "already executed" } | ||
|
||
val resultReady = CountDownLatch(1) | ||
val result = AtomicReference<ResponseMessage<Output>>() | ||
val cancelFn = block { responseMessage -> | ||
result.set(responseMessage) | ||
resultReady.countDown() | ||
} | ||
|
||
if (!cancelFunc.compareAndSet(null, cancelFn)) { | ||
// concurrently cancelled before we could set the | ||
// cancel function, so we need to cancel what we | ||
// just started | ||
cancelFn() | ||
} | ||
resultReady.await() | ||
return result.get() | ||
} | ||
|
||
/** | ||
* Cancel the underlying request. | ||
*/ | ||
override fun cancel() { | ||
val cancelFn = cancelFunc.getAndSet {} // set to (non-null) no-op | ||
if (cancelFn != null) { | ||
cancelFn() | ||
} | ||
} | ||
} |
106 changes: 106 additions & 0 deletions
106
library/src/test/kotlin/com/connectrpc/impl/UnaryCallTest.kt
This file contains 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,106 @@ | ||
// Copyright 2022-2023 The Connect Authors | ||
// | ||
// 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 | ||
// | ||
// 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 com.connectrpc.impl | ||
|
||
import com.connectrpc.Code | ||
import com.connectrpc.ConnectException | ||
import com.connectrpc.ResponseMessage | ||
import org.assertj.core.api.Assertions.assertThat | ||
import org.junit.Test | ||
import java.util.concurrent.CountDownLatch | ||
import java.util.concurrent.Executors | ||
|
||
class UnaryCallTest { | ||
@Test | ||
fun testExecute() { | ||
val executor = Executors.newSingleThreadExecutor() | ||
try { | ||
val result = Object() | ||
val call = UnaryCall<Any> { callback -> | ||
executor.execute { | ||
callback.invoke( | ||
ResponseMessage.Success( | ||
result, | ||
headers = emptyMap(), | ||
trailers = emptyMap(), | ||
), | ||
) | ||
} | ||
return@UnaryCall { } | ||
} | ||
val resp = call.execute() | ||
assertThat(resp).isInstanceOf(ResponseMessage.Success::class.java) | ||
val msg = resp.success { it.message }!! | ||
assertThat(msg).isEqualTo(result) | ||
} finally { | ||
assertThat(executor.shutdownNow()).isEmpty() | ||
} | ||
} | ||
|
||
@Test | ||
fun testCancelAfterExecute() { | ||
testCancel(false) | ||
} | ||
|
||
@Test | ||
fun testCancelBeforeExecute() { | ||
testCancel(true) | ||
} | ||
|
||
private fun testCancel(cancelFirst: Boolean) { | ||
val executor = Executors.newFixedThreadPool(2) | ||
try { | ||
// Indicates when the async task has begun. | ||
val taskRunning = CountDownLatch(1) | ||
// Indicates when the async task has been canceled. | ||
val taskCanceled = CountDownLatch(1) | ||
|
||
val call = UnaryCall<Any> { callback -> | ||
executor.execute { | ||
taskRunning.countDown() | ||
taskCanceled.await() | ||
callback.invoke( | ||
ResponseMessage.Failure( | ||
headers = emptyMap(), | ||
trailers = emptyMap(), | ||
cause = ConnectException(code = Code.CANCELED), | ||
), | ||
) | ||
} | ||
return@UnaryCall { | ||
taskCanceled.countDown() | ||
} | ||
} | ||
if (cancelFirst) { | ||
// When we execute the task below, the call will observe | ||
// that it has already been canceled and immediately | ||
// cancel the just-started task. | ||
call.cancel() | ||
} else { | ||
// This will cancel the task right after it has started running. | ||
executor.execute { | ||
taskRunning.await() | ||
call.cancel() | ||
} | ||
} | ||
val resp = call.execute() | ||
assertThat(resp).isInstanceOf(ResponseMessage.Failure::class.java) | ||
val connEx = resp.failure { it.cause }!! | ||
assertThat(connEx.code).isEqualTo(Code.CANCELED) | ||
} finally { | ||
assertThat(executor.shutdownNow()).isEmpty() | ||
} | ||
} | ||
} |
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.
Could this test be simplified to just call success on the callback without a delay? (So remove try/catch block above). Since nothing calls cancel, that shouldn't ever be invoked.
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.
Yep, good call.