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
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
Expand All @@ -13,7 +14,12 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.siloserver.silo.model.auth.DeviceCodeFormat
Expand Down Expand Up @@ -304,13 +310,18 @@ class CompanionPairingCoordinator(
}
coroutineScope {
val inbox = Channel<PairingMessage>(Channel.UNLIMITED)
val peer = PeerState()
val collector = launch {
try {
connected.incoming.collect { inbox.send(it) }
connected.incoming.collect {
peer.observe(it)
inbox.send(it)
}
} finally {
// The TV hung up (or the read failed): wake any wait
// for its next message instead of sitting on it until
// the step's timeout.
peer.ended()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Kody Rules high

Server-selection hang occurs when the incoming flow completes normally while chooseServers(orderedServers) awaits UI input: recording transport closure with peer.ended() only wakes the match-confirmation interruption watcher, and normal collector completion and closing inbox do not cancel the separate UI wait, leaving the phone stuck after the TV disconnects. Propagate unexpected transport completion to the entire pairing operation, or race server selection against peer termination and cancel the pending selection when termination wins; add a regression test for clean EOF during server selection.

Kody rule violation: Propagate transport closure to pending interaction and preserve terminal failures

Prompt for LLM

File android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pairing/CompanionPairingCoordinator.kt:

Line 324:

Server-selection hang occurs when the incoming flow completes normally while `chooseServers(orderedServers)` awaits UI input: recording transport closure with `peer.ended()` only wakes the match-confirmation interruption watcher, and normal collector completion and closing `inbox` do not cancel the separate UI wait, leaving the phone stuck after the TV disconnects. Propagate unexpected transport completion to the entire pairing operation, or race server selection against peer termination and cancel the pending selection when termination wins; add a regression test for clean EOF during server selection.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

inbox.close()
}
}
Expand All @@ -331,6 +342,7 @@ class CompanionPairingCoordinator(
server = server,
transport = connected,
inbox = inbox,
peer = peer,
requireUserConfirmation = index == 0,
confirmFirstMatch = confirmFirstMatch,
)
Expand Down Expand Up @@ -425,9 +437,18 @@ class CompanionPairingCoordinator(
server: CompanionPairingServer,
transport: PairingTransport,
inbox: ReceiveChannel<PairingMessage>,
peer: PeerState,
requireUserConfirmation: Boolean,
confirmFirstMatch: suspend (CompanionPairingApproval) -> Boolean,
) {
// A signed-out TV keeps its sign-in request after it cancels this
// attempt, so once it has ended the attempt (cancelled, hung up, or
// reported this server failed) the phone must not approve or deny
// that request. Checked before every decision.
fun ensureAttemptLive() {
peer.interruption(server.url)?.let { throw it.failure(target, server.displayName) }
}

_status.value = CompanionPairingStatus.PushingServer(target.name, server.displayName)
transport.send(
PairingMessage.PushServer(
Expand Down Expand Up @@ -459,6 +480,7 @@ class CompanionPairingCoordinator(
}
val serverMatchCode = lookup.matchCode?.takeIf { it.isNotBlank() }
?: error("Server did not return a match code for TV setup.")
ensureAttemptLive()
if (serverMatchCode != started.matchCode) {
deviceLoginApprover.deny(server, started.userCode)
transport.send(PairingMessage.Cancel(reason = "match-code-mismatch"))
Expand All @@ -477,19 +499,39 @@ class CompanionPairingCoordinator(
// nothing is approved for an account it couldn't name. The TV
// keeps its code, so "Try again" can pick it up.
val accountName = deviceLoginApprover.accountName(server)
ensureAttemptLive()
if (accountName.isNullOrBlank()) {
transport.send(PairingMessage.Cancel(reason = "account-unknown"))
error("Couldn't confirm which account would sign in on ${target.name}. Try again.")
}
val shown = approval.copy(accountName = accountName)
_status.value = CompanionPairingStatus.AwaitingMatchConfirmation(shown)
if (!confirmFirstMatch(shown)) {
// The TV can end the attempt while the person compares codes:
// the card's buttons go away at once instead of acting on it.
val confirmed = coroutineScope {
val answer = async { confirmFirstMatch(shown) }
val interrupted = async { peer.awaitInterruption(server.url) }
select<Unit> {
answer.onAwait {}
interrupted.onAwait {}
}
interrupted.cancel()
// Also wins when both finished together; leaving this scope
// by throwing cancels the pending answer.
ensureAttemptLive()
answer.await()
}
if (!confirmed) {
Comment thread
Quick104 marked this conversation as resolved.
Resolved
// Leaving the scope above waits for the cancelled watcher,
// and the TV can end the attempt in that time.
ensureAttemptLive()
deviceLoginApprover.deny(server, started.userCode)
transport.send(PairingMessage.Cancel(reason = "user-cancelled"))
error("Cancelled. Nothing was approved.")
}
}

ensureAttemptLive()
_status.value = CompanionPairingStatus.Approving(target.name, server.displayName)
when (val approved = deviceLoginApprover.approve(server, started.userCode)) {
is ApiResult.Success -> Unit
Expand Down Expand Up @@ -548,6 +590,51 @@ class CompanionPairingCoordinator(
/** The TV sent `cancel` while the phone waited for its next message. */
private class PeerCancelledException(val reason: String) : IllegalStateException("peer cancelled: $reason")

/** What ended the TV's side of a server's attempt. */
private sealed class PeerInterruption {
data class Cancelled(val reason: String) : PeerInterruption()
data object Closed : PeerInterruption()
data class Failed(val error: String?) : PeerInterruption()
}

/**
* Records, as the TV's messages arrive, anything that ends an attempt: a
* `cancel`, the connection closing, or a failed result for a server. The
* inbox only shows these when the phone next reads it, which is after
* the decision it would have stopped.
*/
private class PeerState {
private val ended = MutableStateFlow<PeerInterruption?>(null)
private val failed = MutableStateFlow<Map<String, PeerInterruption.Failed>>(emptyMap())

fun observe(message: PairingMessage) {
when (message) {
is PairingMessage.Cancel -> ended.compareAndSet(null, PeerInterruption.Cancelled(message.reason))
is PairingMessage.ServerResult -> if (message.status != PairingServerStatus.SignedIn) {
failed.update { it + (message.serverURL to PeerInterruption.Failed(message.error)) }
}
else -> Unit
}
}

fun ended() {
ended.compareAndSet(null, PeerInterruption.Closed)
}

/** Why [serverURL]'s attempt is over, or null while it is live. */
fun interruption(serverURL: String): PeerInterruption? = ended.value ?: failed.value[serverURL]

suspend fun awaitInterruption(serverURL: String): PeerInterruption =
combine(ended, failed) { end, failures -> end ?: failures[serverURL] }.filterNotNull().first()
}

/** The failure the phone reports for [this], phrased as when it's read from the inbox. */
private fun PeerInterruption.failure(target: CompanionPairingTarget, serverName: String): Throwable = when (this) {
is PeerInterruption.Cancelled -> PeerCancelledException(reason)
PeerInterruption.Closed -> ClosedReceiveChannelException("${target.name} closed the connection")
is PeerInterruption.Failed -> IllegalStateException(PairingFailureCode.fromWire(error).phoneMessage(target, serverName))
}

private companion object {
const val TAG = "CompanionPairing"
/** [PairingReceiver.denyPendingServer]'s reason when the TV user declines the push. */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.siloserver.silo.common.pairing

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.test.runTest
Expand Down Expand Up @@ -76,6 +77,7 @@ private class FakeCompanionApprover(
private val onApprove: suspend (String) -> Unit = {},
private val account: String? = "alice",
private val approveFailure: ApiResult<DeviceLoginDecisionResponse>? = null,
private val onLookup: suspend (String) -> Unit = {},
) : CompanionDeviceLoginApprover {
override suspend fun accountName(server: CompanionPairingServer): String? = account

Expand All @@ -88,6 +90,7 @@ private class FakeCompanionApprover(
code: String,
): ApiResult<DeviceLoginLookupResponse> {
lookups += code
onLookup(code)
return ApiResult.Success(
DeviceLoginLookupResponse(
status = "pending",
Expand Down Expand Up @@ -445,9 +448,93 @@ class CompanionPairingCoordinatorTest {
assertEquals(CompanionPairingResult.Failed("Connection to Den TV was lost. Try again."), lostMidSession)
}

/**
* The TV ends the attempt while the phone shows the code to compare: it
* cancels, hangs up, or reports the code expired with the connection
* still open. A signed-out TV keeps its sign-in request, so the card
* stops waiting for an answer at once and nothing reaches the server.
*/
@Test
fun tvEndingTheAttemptDuringTheCodeComparisonApprovesAndDeniesNothing() = runTest {
val tvEnds = mapOf<String, suspend (Channel<PairingMessage>, String) -> Unit>(
"Den TV cancelled." to { inbox, _ -> inbox.send(PairingMessage.Cancel(reason = "user_cancelled")); inbox.close() },
"Den TV closed the connection. Try again." to { inbox, _ -> inbox.close() },
"The code on Den TV expired. Try again." to { inbox, url ->
inbox.send(PairingMessage.ServerResult(url, PairingServerStatus.Failed, "expired"))
},
)
for ((message, end) in tvEnds) {
for (answer in listOf(true, false)) {
val approver = FakeCompanionApprover()
var inbox: Channel<PairingMessage>? = null
var answered = false
val result = pairWithTvThat(
approver = approver,
confirm = {
end(inbox!!, "https://lib.example")
delay(1_000)
answered = true
answer
},
) { inbound, push ->
inbox = inbound
inbound.send(PairingMessage.DeviceStarted(push.serverURL, "ABCD-0001", "MATCH-1"))
}
assertEquals(CompanionPairingResult.Failed(message), result, "answer=$answer")
assertTrue(!answered, "$message: the card kept waiting for an answer")
assertTrue(approver.approvals.isEmpty(), "$message answer=$answer")
assertTrue(approver.denials.isEmpty(), "$message answer=$answer")
}
}
}

/**
* The TV cancels while the phone looks its code up: a mismatched code is
* not denied, and a second server (approved without asking) is not approved.
*/
@Test
fun tvCancellingDuringTheLookupApprovesAndDeniesNothing() = runTest {
val home = CompanionPairingServer("srv-1", "https://lib.example", "Home")
val cabin = CompanionPairingServer("srv-2", "https://cabin.example", "Cabin")
// mismatched: the first server's code doesn't match; second: the
// first server signs in and the TV cancels during the second lookup.
for (case in listOf("mismatched", "second")) {
var inbox: Channel<PairingMessage>? = null
val cancelOn = if (case == "mismatched") "ABCD-0001" else "ABCD-0002"
val approver = FakeCompanionApprover(
matchCodes = mapOf("ABCD-0001" to "MATCH-1", "ABCD-0002" to "MATCH-2"),
onApprove = { code ->
if (code == "ABCD-0001") inbox!!.send(PairingMessage.ServerResult(home.url, PairingServerStatus.SignedIn, null))
},
onLookup = { code ->
if (code == cancelOn) {
inbox!!.send(PairingMessage.Cancel(reason = "user_cancelled"))
inbox!!.close()
delay(10) // the lookup's round trip
}
},
)
val result = pairWithTvThat(
approver = approver,
servers = listOf(home, cabin),
) { inbound, push ->
inbox = inbound
val n = if (push.serverURL == home.url) 1 else 2
val shown = if (case == "mismatched") "MATCH-X" else "MATCH-$n"
inbound.send(PairingMessage.DeviceStarted(push.serverURL, "ABCD-000$n", shown))
}
assertEquals(CompanionPairingResult.Failed("Den TV cancelled."), result, case)
assertTrue(approver.denials.isEmpty(), case)
assertEquals(if (case == "second") listOf("ABCD-0001") else emptyList(), approver.approvals, case)
}
}

/** Pairs with a TV whose reaction to the pushed server is [onPush]. */
private suspend fun pairWithTvThat(
onCoordinator: (CompanionPairingCoordinator) -> Unit = {},
approver: CompanionDeviceLoginApprover = FakeCompanionApprover(),
confirm: suspend (CompanionPairingApproval) -> Boolean = { true },
servers: List<CompanionPairingServer> = listOf(CompanionPairingServer("srv-1", "https://lib.example", "Home")),
onPush: suspend (Channel<PairingMessage>, PairingMessage.PushServer) -> Unit,
): CompanionPairingResult {
val transport = object : PairingTransport {
Expand All @@ -461,14 +548,13 @@ class CompanionPairingCoordinatorTest {
}
override fun close() { inbound.close() }
}
val server = CompanionPairingServer("srv-1", "https://lib.example", "Home")
val coordinator = CompanionPairingCoordinator(
serverStore = FakeCompanionServerStore(CompanionPairingServerSnapshot("srv-1", listOf(server))),
deviceLoginApprover = FakeCompanionApprover(),
serverStore = FakeCompanionServerStore(CompanionPairingServerSnapshot("srv-1", servers)),
deviceLoginApprover = approver,
transportFactory = { transport },
)
onCoordinator(coordinator)
return coordinator.pair(CompanionPairingTarget("tv-1", "Den TV", "127.0.0.1", 9999))
return coordinator.pair(CompanionPairingTarget("tv-1", "Den TV", "127.0.0.1", 9999), confirmFirstMatch = confirm)
}

/** A Roku keeps one server and refuses a second push (silo-roku `docs/companion-pairing.md` section 4). */
Expand Down
Loading