Fix #149: Rethrow CancellationException in FcmTokenRegistrar

The broad catch(Exception) around sendFcmToken swallowed CancellationException
(which inherits from IllegalStateException on JVM), breaking structured
concurrency. Rethrow CancellationException before the general handler so
callers tied to a cancellable scope observe cancellation correctly.

Added a test that cancels the calling scope mid-send and asserts the
CancellationException propagates out of registerToken.
This commit is contained in:
Jason Monk 2026-04-14 20:00:46 -04:00
parent 0b69fae5ed
commit 96b2f97873
2 changed files with 46 additions and 0 deletions

View file

@ -3,6 +3,7 @@ package com.rousecontext.work
import android.util.Log
import com.rousecontext.tunnel.TunnelClient
import com.rousecontext.tunnel.TunnelState
import kotlinx.coroutines.CancellationException
/**
* Forwards refreshed FCM tokens to the relay over the active tunnel connection.
@ -34,6 +35,8 @@ class FcmTokenRegistrar(private val tunnelClient: TunnelClient) {
try {
tunnelClient.sendFcmToken(token)
Log.i(TAG, "Forwarded refreshed FCM token to relay")
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "Failed to push refreshed FCM token; next wake will pull", e)
}

View file

@ -8,8 +8,14 @@ import io.mockk.coVerify
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@ -79,4 +85,41 @@ class FcmTokenRegistrarTest {
coVerify(exactly = 1) { tunnelClient.sendFcmToken("token-abc") }
}
@Test
fun `registerToken propagates cancellation when scope is cancelled mid-send`() = runBlocking {
val tunnelClient = mockk<TunnelClient>()
every { tunnelClient.state } returns MutableStateFlow(TunnelState.CONNECTED)
val sendStarted = CompletableDeferred<Unit>()
val neverCompletes = CompletableDeferred<Unit>()
coEvery { tunnelClient.sendFcmToken(any()) } coAnswers {
sendStarted.complete(Unit)
// Suspend until cancelled — simulates a slow send that never returns.
neverCompletes.await()
}
val registrar = FcmTokenRegistrar(tunnelClient)
val caught = CompletableDeferred<Throwable>()
val job: Job = launch {
try {
registrar.registerToken("token-abc")
caught.complete(IllegalStateException("registerToken returned normally"))
} catch (e: CancellationException) {
caught.complete(e)
throw e
}
}
// Wait until sendFcmToken is actually suspended, then cancel.
sendStarted.await()
job.cancel()
job.join()
val thrown = caught.await()
assertTrue(
"registerToken must propagate CancellationException, got ${thrown::class}",
thrown is CancellationException
)
assertNotNull(thrown)
}
}