Skip to content
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
19 changes: 11 additions & 8 deletions app/src/main/java/io/nekohasekai/sagernet/bg/BaseService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -312,14 +312,17 @@ class BaseService {
}
}

fun killProcesses() {
data.proxy?.close()
wakeLock?.apply {
release()
wakeLock = null
}
runOnDefaultDispatcher {
DefaultNetworkListener.stop(this@Interface)
suspend fun killProcesses() {
runServiceTeardown(
after = {
wakeLock?.apply {
release()
wakeLock = null
}
DefaultNetworkListener.stop(this@Interface)
},
) {
data.proxy?.closeAndPersist()
}
}

Expand Down
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
}
9 changes: 5 additions & 4 deletions app/src/main/java/io/nekohasekai/sagernet/bg/VpnService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,11 @@ class VpnService :
}

@Suppress("EXPERIMENTAL_API_USAGE")
override fun killProcesses() {
conn?.close()
conn = null
super.killProcesses()
override suspend fun killProcesses() {
runServiceTeardown(after = { super.killProcesses() }) {
conn?.close()
conn = null
}
}

override fun onBind(intent: Intent) = when (intent.action) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package io.nekohasekai.sagernet.bg.proto

import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.bg.ServiceNotification
import io.nekohasekai.sagernet.bg.runRequiredCompletion
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.ktx.Logs
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -51,14 +52,21 @@ class ProxyInstance(profile: ProxyEntity, var service: BaseService.Interface? =
looper?.start()
}

override fun close() {
suspend fun closeAndPersist() = runRequiredCompletion(
after = {
try {
looper?.stop()
} finally {
looper = null
}
},
) {
super.close()
// Teardown is called on the main thread; the final traffic flush in looper.stop() does
// synchronous DAO writes, so run the blocking body on a background dispatcher to keep it
// off the UI thread (Plan 027 — main-thread-DB allowance removed).
runBlocking(Dispatchers.Default) {
looper?.stop()
looper = null
}
}

// Synchronous compatibility path for Closeable callers. Service teardown uses
// closeAndPersist() through runServiceTeardown instead of blocking its caller.
override fun close() = runBlocking(Dispatchers.Default) {
closeAndPersist()
}
Comment on lines +69 to 71

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Default Dispatcher Blocks Itself

When a synchronous Closeable.close() caller reaches this path from a Dispatchers.Default worker, runBlocking(Dispatchers.Default) can occupy the dispatcher while closeAndPersist() 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.

Copy link
Copy Markdown
Owner Author

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.

Copy link
Copy Markdown

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.Default is a thread pool (minimum 2 threads), so a single runBlocking call 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 Closeable callers 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"?

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