Repository navigation
jextract/JNI: Propagate CompletableFuture cancellation to Swift tasks - #974
sidepelican wants to merge 10 commits into
Conversation
|
|
||
| @Override | ||
| public void register(SwiftInstance instance) { | ||
| checkValid(); |
There was a problem hiding this comment.
Also fixes a race between async result registration and close().
piercifani
left a comment
There was a problem hiding this comment.
Looks good to me. I read through it and couldn't find a leak or a double free, including when the cancel arrives just as Swift finishes.
I also checked it from Kotlin: cancelling a coroutine that's waiting on future.await() now stops the Swift task too.
One suggestion: the Swift task only stops when the future is cancelled. If the future finishes some other way first, for example through orTimeout(), complete() or completeExceptionally(), the Swift task keeps running. It would be good to stop it in those cases too.
|
@piercifani Thanks for the review and for testing this from Kotlin! Good catch on I updated the bridge to request cancellation of the Swift task whenever the returned future completes. |
Problem
JNI bindings expose Swift
asyncfunctions to Java as methods returning aCompletableFuture.Cancelling the returned future currently leaves the underlying Swift task running.
Solution
The generated Java binding now passes a
SwiftAsyncResultSinkto Swift in place of theCompletableFuture. The sink holds the future returned to the Java caller and useswhenCompleteto forward cancellation to the Swift task.The tricky case is when cancellation occurs after Swift has produced a result but before Java has taken ownership of it.
For results, Swift allocates storage with
UnsafeMutablePointer.allocateand passes the pointer to Java. Java then becomes responsible for releasing that storage.If cancellation races with this handoff, the pointer can be left without an owner.
For results that require an arena,
SwiftAsyncResultSinkuses a temporarySwiftArenabacked by anArrayDequeto collect wrappers during conversion. It converts any result delivered to the sink even if the future has already been cancelled. The sink then registers each wrapper with the caller's arena. Once registered, a wrapper is owned by that arena. If cancellation or an error interrupts the transfer, the sink releases the wrappers still in the deque.To support the temporary arena,
JNISwift2JavaGenerator.JavaTranslationcan now select the arena variable used by the generated result conversion.This PR adds cancellation forwarding only to
JExtractAsyncFuncMode.completableFuture.Fixes: #947