Skip to content
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 4 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 5 additions & 44 deletions library/src/main/kotlin/com/connectrpc/UnaryBlockingCall.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,57 +14,18 @@

package com.connectrpc

import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicReference

/**
* A [UnaryBlockingCall] contains the way to make a blocking RPC call and cancelling the RPC.
*/
class UnaryBlockingCall<Output> {
private var executable: ((ResponseMessage<Output>) -> Unit) -> Unit = { }
private var cancelFn: () -> Unit = { }

interface UnaryBlockingCall<Output> {
/**
* Execute the underlying request.
* Subsequent calls will create a new request.
* Execute the underlying request. Can only be called once.
* Subsequent calls will throw IllegalStateException.
*/
fun execute(): ResponseMessage<Output> {
val countDownLatch = CountDownLatch(1)
val reference = AtomicReference<ResponseMessage<Output>>()
executable { responseMessage ->
reference.set(responseMessage)
countDownLatch.countDown()
}
countDownLatch.await()
return reference.get()
}
fun execute(): ResponseMessage<Output>

/**
* Cancel the underlying request.
*/
fun cancel() {
cancelFn()
}

/**
* Gives the blocking call a cancellation function to cancel the
* underlying request.
*
* @param cancel The function to call in order to cancel the
* underlying request.
*/
internal fun setCancel(cancel: () -> Unit) {
this.cancelFn = cancel
}

/**
* Gives the blocking call the execution function to initiate
* the underlying request.
*
* @param executable The function to call in order to initiate
* a request.
*/
internal fun setExecute(executable: ((ResponseMessage<Output>) -> Unit) -> Unit) {
this.executable = executable
}
fun cancel()
}
14 changes: 2 additions & 12 deletions library/src/main/kotlin/com/connectrpc/impl/ProtocolClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import okio.Buffer
import java.net.URI
import java.util.concurrent.CountDownLatch
import kotlin.coroutines.resume

/**
Expand Down Expand Up @@ -167,18 +166,9 @@ class ProtocolClient(
headers: Headers,
methodSpec: MethodSpec<Input, Output>,
): UnaryBlockingCall<Output> {
val countDownLatch = CountDownLatch(1)
val call = UnaryBlockingCall<Output>()
// Set the unary synchronous executable.
call.setExecute { callback: (ResponseMessage<Output>) -> Unit ->
val cancellationFn = unary(request, headers, methodSpec) { responseMessage ->
callback(responseMessage)
countDownLatch.countDown()
}
// Set the cancellation function .
call.setCancel(cancellationFn)
return UnaryCall { callback ->
unary(request, headers, methodSpec, callback)
}
return call
}

override suspend fun <Input : Any, Output : Any> serverStream(
Expand Down
85 changes: 85 additions & 0 deletions library/src/main/kotlin/com/connectrpc/impl/UnaryCall.kt
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 library/src/test/kotlin/com/connectrpc/impl/UnaryCallTest.kt
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(
Copy link
Contributor

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.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, good call.

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()
}
}
}
Loading