forked from starifly/NekoBoxForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Move service teardown off the main dispatcher #151
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
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
36 changes: 36 additions & 0 deletions
36
app/src/main/java/io/nekohasekai/sagernet/bg/ServiceTeardownExecution.kt
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,36 @@ | ||
| package io.nekohasekai.sagernet.bg | ||
|
|
||
| import kotlinx.coroutines.CoroutineDispatcher | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.NonCancellable | ||
| import kotlinx.coroutines.withContext | ||
|
|
||
| internal suspend fun runServiceTeardown( | ||
| dispatcher: CoroutineDispatcher = Dispatchers.IO, | ||
| after: suspend () -> Unit = {}, | ||
| block: suspend () -> Unit, | ||
| ) = withContext(NonCancellable) { | ||
| runRequiredCompletion(after) { | ||
| withContext(dispatcher) { | ||
| block() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| internal suspend fun runRequiredCompletion(after: suspend () -> Unit, block: suspend () -> Unit) { | ||
| var failure: Throwable? = null | ||
| try { | ||
| block() | ||
| } catch (throwable: Throwable) { | ||
| failure = throwable | ||
| } | ||
| try { | ||
| after() | ||
| } catch (throwable: Throwable) { | ||
| val primaryFailure = failure | ||
| if (primaryFailure == null) throw throwable | ||
| if (primaryFailure !== throwable) primaryFailure.addSuppressed(throwable) | ||
| } | ||
| val finalFailure = failure | ||
| if (finalFailure != null) throw finalFailure | ||
| } |
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
156 changes: 156 additions & 0 deletions
156
app/src/test/java/io/nekohasekai/sagernet/bg/ServiceTeardownExecutionTest.kt
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,156 @@ | ||
| package io.nekohasekai.sagernet.bg | ||
|
|
||
| import kotlinx.coroutines.CompletableDeferred | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.ExperimentalCoroutinesApi | ||
| import kotlinx.coroutines.currentCoroutineContext | ||
| import kotlinx.coroutines.launch | ||
| import kotlinx.coroutines.runBlocking | ||
| import kotlinx.coroutines.test.StandardTestDispatcher | ||
| import kotlinx.coroutines.test.advanceUntilIdle | ||
| import kotlinx.coroutines.test.runCurrent | ||
| import kotlinx.coroutines.test.runTest | ||
| import org.junit.Assert.assertFalse | ||
| import org.junit.Assert.assertSame | ||
| import org.junit.Assert.assertTrue | ||
| import org.junit.Test | ||
| import kotlin.coroutines.ContinuationInterceptor | ||
|
|
||
| @OptIn(ExperimentalCoroutinesApi::class) | ||
| class ServiceTeardownExecutionTest { | ||
|
|
||
| @Test | ||
| fun callerWaitsForTeardownToComplete() = runTest { | ||
| val dispatcher = StandardTestDispatcher(testScheduler) | ||
| val releaseTeardown = CompletableDeferred<Unit>() | ||
| val caller = launch { | ||
| runServiceTeardown(dispatcher) { | ||
| releaseTeardown.await() | ||
| } | ||
| } | ||
|
|
||
| runCurrent() | ||
| assertFalse(caller.isCompleted) | ||
|
|
||
| releaseTeardown.complete(Unit) | ||
| advanceUntilIdle() | ||
| assertTrue(caller.isCompleted) | ||
| } | ||
|
|
||
| @Test | ||
| fun parentCancellationAfterEntryDoesNotSkipTeardown() = runTest { | ||
| val dispatcher = StandardTestDispatcher(testScheduler) | ||
| val teardownEntered = CompletableDeferred<Unit>() | ||
| val releaseTeardown = CompletableDeferred<Unit>() | ||
| var teardownCompleted = false | ||
| val caller = launch { | ||
| runServiceTeardown(dispatcher) { | ||
| teardownEntered.complete(Unit) | ||
| releaseTeardown.await() | ||
| teardownCompleted = true | ||
| } | ||
| } | ||
|
|
||
| runCurrent() | ||
| teardownEntered.await() | ||
| caller.cancel() | ||
| releaseTeardown.complete(Unit) | ||
| advanceUntilIdle() | ||
|
|
||
| assertTrue(teardownCompleted) | ||
| assertTrue(caller.isCancelled) | ||
| } | ||
|
|
||
| @Test | ||
| fun parentCancellationDoesNotSkipRequiredCompletion() = runTest { | ||
| val dispatcher = StandardTestDispatcher(testScheduler) | ||
| val teardownEntered = CompletableDeferred<Unit>() | ||
| val releaseTeardown = CompletableDeferred<Unit>() | ||
| var completionRan = false | ||
| val caller = launch { | ||
| runServiceTeardown( | ||
| dispatcher = dispatcher, | ||
| after = { completionRan = true }, | ||
| ) { | ||
| teardownEntered.complete(Unit) | ||
| releaseTeardown.await() | ||
| } | ||
| } | ||
|
|
||
| runCurrent() | ||
| teardownEntered.await() | ||
| caller.cancel() | ||
| releaseTeardown.complete(Unit) | ||
| advanceUntilIdle() | ||
|
|
||
| assertTrue(completionRan) | ||
| assertTrue(caller.isCancelled) | ||
| } | ||
|
|
||
| @Test | ||
| fun teardownExceptionPropagatesAfterRequiredCompletion() = runBlocking { | ||
| val failure = IllegalStateException("teardown failure") | ||
| var completionRan = false | ||
|
|
||
| val result = runCatching { | ||
| runServiceTeardown( | ||
| dispatcher = Dispatchers.Unconfined, | ||
| after = { completionRan = true }, | ||
| ) { | ||
| throw failure | ||
| } | ||
| } | ||
|
|
||
| assertTrue(completionRan) | ||
| var propagated = result.exceptionOrNull() | ||
| while (propagated != null && propagated !== failure) { | ||
| propagated = propagated.cause | ||
| } | ||
| assertSame(failure, propagated) | ||
| } | ||
|
|
||
| @Test | ||
| fun completionExceptionIsSuppressedByTeardownFailure() = runBlocking { | ||
| val teardownFailure = IllegalStateException("teardown failure") | ||
| val completionFailure = IllegalArgumentException("completion failure") | ||
| val result = runCatching { | ||
| runRequiredCompletion( | ||
| after = { throw completionFailure }, | ||
| ) { | ||
| throw teardownFailure | ||
| } | ||
| } | ||
|
|
||
| val failure = result.exceptionOrNull() | ||
| assertSame(teardownFailure, failure) | ||
| assertSame(completionFailure, failure?.suppressed?.single()) | ||
| } | ||
|
|
||
| @Test | ||
| fun repeatedFailureInstancePreservesOriginalFailure() = runBlocking { | ||
| val failure = IllegalStateException("shared failure") | ||
| val result = runCatching { | ||
| runRequiredCompletion( | ||
| after = { throw failure }, | ||
| ) { | ||
| throw failure | ||
| } | ||
| } | ||
|
|
||
| val thrown = result.exceptionOrNull() | ||
| assertSame(failure, thrown) | ||
| assertTrue(thrown?.suppressed?.isEmpty() == true) | ||
| } | ||
|
|
||
| @Test | ||
| fun teardownUsesSuppliedDispatcher() = runTest { | ||
| val dispatcher = StandardTestDispatcher(testScheduler) | ||
| var observedDispatcher: ContinuationInterceptor? = null | ||
|
|
||
| runServiceTeardown(dispatcher) { | ||
| observedDispatcher = currentCoroutineContext()[ContinuationInterceptor] | ||
| } | ||
|
|
||
| assertSame(dispatcher, observedDispatcher) | ||
| } | ||
| } |
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.
When a synchronous
Closeable.close()caller reaches this path from aDispatchers.Defaultworker,runBlocking(Dispatchers.Default)can occupy the dispatcher whilecloseAndPersist()waits for the traffic looper job to cancel and join on the same dispatcher. That can leave teardown stuck indefinitely and block service shutdown or restart.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.
No change. Normal service shutdown uses the suspending close path and never calls this compatibility override. The override preserves the prior behavior for unexpected Closeable callers; one caller cannot self-starve the shared Default scheduler because another worker remains available for the traffic job.
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.
That's a fair correction.
Dispatchers.Defaultis a thread pool (minimum 2 threads), so a singlerunBlockingcall on it won't starve itself — at least one other thread remains available to run the looper cancellation work. My original comment overstated the risk for the single-caller case.The remaining (much narrower) scenario would be multiple concurrent unexpected
Closeablecallers saturating the Default pool simultaneously, but that's contrived given the suspend path is the normal route and the compatibility override is a last-resort bridge. Your point stands.Would you like me to remember a rule along the lines of: "don't flag
runBlocking(Dispatchers.Default)as a self-starvation risk unless pool exhaustion across concurrent callers is plausible, given Default is a multi-threaded pool"?