From 7642bb268ee739d4e1cc6447ca7bcef71cd51990 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Fri, 27 Nov 2026 07:14:21 +0100 Subject: [PATCH] Android peripheral: retry a notification the stack refused (#407) drainNotifications pushes a refused payload (notifyCharacteristicChanged returns false) back to the front of pendingNotifications and removes the in-flight marker. Nothing then schedules another drain: the marker was absent before the send, so there is no packet whose onNotificationSent would retry it. The queued update therefore waits for an unrelated updateCharacteristic for the same client, and every later update queues behind it. A payload enqueued in the window between the isSubscribed check in updateCharacteristic and the enqueue (a CCCD unsubscribe can land in between) could likewise be transmitted stale after a resubscription. A refusal now schedules a retry for that client on the existing main Handler. At most one runnable exists per address, so further refusals coalesce into it. The delay is 10 ms, doubled per consecutive refusal and capped at 500 ms; the attempt counter stops at the ceiling so the shift distance stays in range, and a successful send clears it, leaving at most one int map entry per device. The runnable re-checks the subscription outside the pendingNotifications monitor, because isSubscribed takes subscribedCharDevicesMap and the descriptor/cleanup paths take the two monitors in the opposite order. When the client has unsubscribed, the queued payloads of the characteristic at the head of its queue are dropped with dropNotifications(includeInFlight = false) and settled with "Central unsubscribed", which ends the retry loop, and the client's other characteristics still drain. A client that resubscribes before the retry fires is treated as still wanting the update, like any queued payload. Settlements still go through settleNotifications, so no Dart callback runs on a binder thread. Disconnect, adapter reset, removeService/clearServices, clearPendingNotifications and the CCCD unsubscribe path cancel a retry that is no longer needed, and the onNotificationSent flow that settles a successful send is unchanged. The queued payload a drain finds with no server is unreachable through the public paths and now says so instead of scheduling a retry against a server that is still null. Tests (PeripheralRegressionTest) add a captured postDelayed helper that runs retries manually, never with real delays, and cover: one retry for a refusal that succeeds when it runs, one retry for several queued updates, the 10/20/40/80/160/320/500/500 ms backoff, the unsubscribe drop with a failed callback and no resend after resubscribing, dropping the unsubscribed characteristic while the client's other characteristic keeps draining, disconnect/removeService/reset/clearPendingNotifications cancelling the runnable and failing the queue, removeService keeping a retry that another service's payload still needs, and the attempt state cleared by a successful send. The retry cases fail against the unfixed production file ("The refusal schedules exactly one retry ==> expected: <1> but was: <0>"). Verification: flutter analyze clean, flutter test 344 passed, Android unit tests 145 passed (142 before). --- CHANGELOG.md | 1 + .../UniversalBlePeripheralPlugin.kt | 199 +++++++++- .../universal_ble/PeripheralRegressionTest.kt | 352 ++++++++++++++++++ 3 files changed, 542 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3379c50..89ca2062 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ * Apple peripheral: add `UniversalBlePeripheral.setDesiredConnectionLatency(deviceId, PeripheralConnectionLatency.low|medium|high)`, mapped to `CBPeripheralManager.setDesiredConnectionLatency(_:for:)`. Apple otherwise negotiates a high latency, which caps notification throughput. No-op on non-Apple platforms (#402). * Windows: connecting to a device whose GATT database holds a service Windows reserves for itself — HID over GATT, `0x1812` — no longer fails. Windows answers `GetCharacteristicsAsync` with `AccessDenied` for it whether or not the device is paired, and since 2.2.0 that error ended the connection attempt during discovery. A denied service is now left out: its characteristics are not reported by `discoverServices`, the rest of the database connects normally, and a GATT service refresh skips it instead of keeping the previous map. A denied service that discovery already reported is the exception — the refresh keeps the previous services then, so reads and subscriptions on it do not silently disappear. A device whose every service was denied still connects, reports no services, and logs a warning. `Unreachable` and `ProtocolError` still fail the connection, so a discovery cut short by a link drop is still reported (#400). * Android peripheral: an update no longer races the notification the stack is already sending. Below API 33 the payload travels in the shared `BluetoothGattCharacteristic.value`, and `updateCharacteristic` wrote it on the main thread while `onNotificationSent` drained the next queued payload on a binder thread: the assignment could land between that drain's value write and its `notifyCharacteristicChanged` call, so a same-length payload was silently transmitted with the wrong content. The in-flight check, the dequeue, the value assignment and the send now all happen under the pending-notification monitor, and the drain no longer reads the subscription map while holding it — the descriptor and cleanup paths take it in the opposite order. API 33+ uses the stateless four-argument overload and treats only `BluetoothStatusCodes.SUCCESS` as sent, and the value a read returns is written only when no target device is subscribed rather than on every update (#403). +* Android peripheral: a notification the stack refuses (`notifyCharacteristicChanged` returns `false`) is now retried on its own. The refusal pushed the payload back to the front of the queue and waited for `onNotificationSent`, but the stack only reports packets it accepted, so a refused payload had no callback coming: it stalled until an unrelated update for the same client, with every later update queued behind it, and a payload enqueued between the subscriber check and the queue could be sent stale after a resubscription. Each client now has at most one retry posted on the main handler, delayed 10 ms and doubled per consecutive refusal up to 500 ms, reset by a successful send; the retry re-checks the subscription outside the pending-notification monitor and, when the client has unsubscribed, drops the queued payloads of the characteristic at the head of its queue with "Central unsubscribed" — then drains the client's other characteristics, so a payload that waited across a CCCD unsubscribe is dropped instead of being delivered after the client resubscribes (a client that resubscribes before the retry fires is treated as still wanting the update, like any queued payload). A disconnect, adapter reset, service removal or clear, `clearPendingNotifications` and a CCCD unsubscribe cancel a retry that is no longer needed (#407). ## 3.4.1 * Android: a `setNotifiable` call whose CCCD write throws now fails with a classified error instead of being left pending. The old code withdrew the pending result twice — once in the inner handler and again in the outer one — so the second withdrawal found nothing to fail and the Dart call hung until its timeout. The CCCD write is now one helper, and the request is withdrawn once before its single reply. diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt index c0c000ef..c8fa6fd1 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt @@ -35,6 +35,19 @@ import java.util.concurrent.atomic.AtomicReference private const val TAG = "UniversalBlePeripheral" private const val REQUEST_CODE_ENABLE_BLUETOOTH = 2342717 +/** First delay before a refused notification is retried; doubled per refusal. */ +private const val NOTIFICATION_RETRY_BASE_DELAY_MS = 10L + +/** Ceiling for the refused-notification backoff, so a stuck client is polled twice a second. */ +private const val NOTIFICATION_RETRY_MAX_DELAY_MS = 500L + +/** + * Refusals the backoff counts up to. The counter only exists to pick the delay, + * so it stops where the ceiling is reached: an int left to grow would eventually + * overflow into a negative shift distance. + */ +private const val NOTIFICATION_RETRY_MAX_ATTEMPT = 7 + /** Bytes of [value] starting at [offset], as ATT expects for a read at that offset. */ private fun offsetSuffix(value: ByteArray, offset: Int): ByteArray = when { offset <= 0 -> value @@ -89,13 +102,17 @@ class UniversalBlePeripheralPlugin( * Notifications waiting for the native transmit queue. Android accepts one * notification per client at a time ([BluetoothGattServer.notifyCharacteristicChanged] * returns false while the previous one is in flight), so they are drained - * FIFO from [BluetoothGattServerCallback.onNotificationSent]. Ordering matters: - * a HID release must never overtake the press it releases. + * FIFO, normally from [BluetoothGattServerCallback.onNotificationSent]. + * Ordering matters: a HID release must never overtake the press it releases. + * + * A refused send leaves nothing for `onNotificationSent` to report, so it + * also schedules a delayed retry ([scheduleNotificationRetryLocked]). * * This monitor also guards the transmit itself. Below API 33 the payload * travels in the shared [BluetoothGattCharacteristic.value], so the check, * the dequeue, that assignment and the notify call must not interleave with - * another drain or with an update (#403). + * another drain or with an update (#403). It guards the retry bookkeeping + * too, so a retry cannot be scheduled and cancelled at the same time. */ private val pendingNotifications: ArrayDeque = ArrayDeque() @@ -107,6 +124,22 @@ class UniversalBlePeripheralPlugin( */ private val notificationsInFlight: MutableMap = HashMap() + /** + * The pending retry for a client whose send the stack refused, keyed by + * client address. A runnable is only installed when there is something to + * retry, and at most one exists per client: further refusals coalesce into + * it instead of posting another. Guarded by [pendingNotifications]. + */ + private val notificationRetries: MutableMap = HashMap() + + /** + * Consecutive refusals per client, used to back the retry off. An entry is + * dropped when a send succeeds or the client's notification path is torn + * down, so the map holds at most one int per client. Guarded by + * [pendingNotifications]. + */ + private val notificationRetryAttempts: MutableMap = HashMap() + /** * Settles [notifications] with [error] on the main thread. A GATT callback * runs on a binder thread, so completing the Pigeon result there would reply @@ -138,6 +171,114 @@ class UniversalBlePeripheralPlugin( removed } + /** + * Schedules one retry of [deviceAddress]'s queue after the stack refused a + * send. Coalesced: while a retry is already scheduled, a further refusal + * leaves it alone rather than posting a second one. The delay doubles per + * consecutive refusal (base [NOTIFICATION_RETRY_BASE_DELAY_MS], capped at + * [NOTIFICATION_RETRY_MAX_DELAY_MS]), so a client that stays busy is not + * polled in a tight loop. + * + * Called under the [pendingNotifications] monitor from [drainNotifications]; + * [handler] runs the retry on the main thread, never on a binder thread. + */ + private fun scheduleNotificationRetryLocked(deviceAddress: String) { + if (notificationRetries.containsKey(deviceAddress)) return + val attempt = ((notificationRetryAttempts[deviceAddress] ?: 0) + 1) + .coerceAtMost(NOTIFICATION_RETRY_MAX_ATTEMPT) + notificationRetryAttempts[deviceAddress] = attempt + // The ceiling is reached at the last attempt, so this is 10, 20, 40, 80, + // 160, 320, 500, 500, ... with no shift distance beyond 6. + val delay = (NOTIFICATION_RETRY_BASE_DELAY_MS shl (attempt - 1)) + .coerceAtMost(NOTIFICATION_RETRY_MAX_DELAY_MS) + val retry = Runnable { retryNotificationSend(deviceAddress) } + notificationRetries[deviceAddress] = retry + handler.postDelayed(retry, delay) + } + + /** + * Cancels the retry scheduled for [deviceAddress] and forgets its backoff. + * The caller must not hold the [pendingNotifications] monitor. + */ + private fun clearNotificationRetry(deviceAddress: String) { + synchronized(pendingNotifications) { clearNotificationRetryLocked(deviceAddress) } + } + + /** + * Cancels the retry scheduled for [deviceAddress] and forgets its backoff. + * Matches the key case-insensitively, because a caller-supplied id from Dart + * need not be in the stack's native case. Caller holds the + * [pendingNotifications] monitor. + */ + private fun clearNotificationRetryLocked(deviceAddress: String) { + // The common path: a send went through and there was no refusal before, + // so there is nothing to forget. + if (notificationRetries.isEmpty() && notificationRetryAttempts.isEmpty()) return + val keys = (notificationRetries.keys + notificationRetryAttempts.keys) + .filter { it.equals(deviceAddress, ignoreCase = true) } + keys.forEach { key -> + notificationRetries.remove(key)?.let { handler.removeCallbacks(it) } + notificationRetryAttempts.remove(key) + } + } + + /** Cancels every scheduled retry and forgets their backoff. */ + private fun clearNotificationRetries() { + synchronized(pendingNotifications) { + notificationRetries.values.forEach { handler.removeCallbacks(it) } + notificationRetries.clear() + notificationRetryAttempts.clear() + } + } + + /** + * Cancels [deviceAddress]'s retry only when nothing is queued for it any + * more, so a packet of another characteristic (another service, or another + * subscription) is still retried. + */ + private fun clearNotificationRetryIfIdle(deviceAddress: String) { + synchronized(pendingNotifications) { + if (pendingNotifications.none { it.device.address == deviceAddress }) { + clearNotificationRetryLocked(deviceAddress) + } + } + } + + /** + * Runs a scheduled retry for [deviceAddress] on [handler]. A refused send is + * the only caller, so there is no `onNotificationSent` to wait for. + * + * The subscription is re-checked here, outside the [pendingNotifications] + * monitor: [isSubscribed] takes the subscription map, and the descriptor and + * cleanup paths take that monitor and this one in the opposite order, so + * nesting them would deadlock. A client that unsubscribed while the payload + * waited is not the client the update was queued for: its payloads for the + * characteristic at the head of the queue are dropped and failed instead of + * being retried — which also ends the retry loop — and the remaining + * characteristics keep draining. If it resubscribed in the meantime, the + * check passes and the payload is still delivered, as any queued update is. + */ + private fun retryNotificationSend(deviceAddress: String) { + val head = synchronized(pendingNotifications) { + notificationRetries.remove(deviceAddress) + pendingNotifications.firstOrNull { it.device.address == deviceAddress } + } + if (head == null) { + clearNotificationRetry(deviceAddress) + return + } + if (!isSubscribed(deviceAddress, head.characteristic)) { + // dropNotifications takes the monitor itself, so this must stay + // outside it: the subscription check above already released it. + val dropped = dropNotifications(includeInFlight = false) { + it.device.address == deviceAddress && it.characteristic === head.characteristic + } + settleNotifications(dropped, IllegalStateException("Central unsubscribed")) + } + drainNotifications(deviceAddress) + clearNotificationRetryIfIdle(deviceAddress) + } + /** * A [BluetoothGattServer] and a [BluetoothLeAdvertiser] do not survive an * adapter restart: the stack drops them, but they stay non-null here, so @@ -201,7 +342,8 @@ class UniversalBlePeripheralPlugin( kotlin.runCatching { bluetoothLeAdvertiser?.stopAdvertising(advertiseCallback) } restoreAdapterNameIfNeeded() // Queued notifications belong to the server that is being dropped, so - // discard them before the caches that resolve their characteristics. + // discard them (and their retries) before the caches that resolve their + // characteristics. clearPendingNotifications(null) val droppedInFlight = synchronized(pendingNotifications) { // The old server will never report these as sent, and a leftover @@ -403,6 +545,9 @@ class UniversalBlePeripheralPlugin( serviceId.findService()?.let { service -> val removed = dropNotifications { it.characteristic.service === service } settleNotifications(removed, IllegalStateException("Service removed")) + // Retries for the removed packets are no longer needed; a client that + // still has another service's payload queued keeps its retry. + removed.map { it.device.address }.distinct().forEach(::clearNotificationRetryIfIdle) // The service and its characteristics are no longer registered, so // nothing may keep resolving them: a later registration of the same // UUID would notify through these orphaned objects (#385). Done even @@ -417,8 +562,9 @@ class UniversalBlePeripheralPlugin( } override fun clearServices() { - // Queued notifications are dropped before the caches that resolve their - // characteristics, so none can be re-queued for services that are gone. + // Queued notifications (and their retries) are dropped before the caches + // that resolve their characteristics, so none can be re-queued for + // services that are gone. clearPendingNotifications(null) val droppedInFlight = synchronized(pendingNotifications) { val current = notificationsInFlight.values.toList() @@ -550,7 +696,9 @@ class UniversalBlePeripheralPlugin( ) { // A failure or an empty subscriber set completes immediately; when there // is something to notify, the callback fires once every target client's - // notification has settled. + // notification has settled. A send the stack refuses stays queued and is + // retried on a short delay, so the callback waits for that retry instead + // of failing. val characteristic: BluetoothGattCharacteristic val targetDevices: List try { @@ -625,9 +773,20 @@ class UniversalBlePeripheralPlugin( synchronized(pendingNotifications) { if (notificationsInFlight.containsKey(deviceAddress)) return val index = pendingNotifications.indexOfFirst { it.device.address == deviceAddress } - if (index < 0) return + if (index < 0) { + // Nothing left to retry: do not leave a runnable behind for an + // empty queue. + clearNotificationRetryLocked(deviceAddress) + return + } val next = pendingNotifications.removeAt(index) val server = gattServer ?: run { + // Not reachable through the public paths: the server is only + // nulled by resetPeripheralState, which empties this queue (and + // cancels its retries) before releasing the monitor, and every + // enqueue path calls requireGattServer first. Scheduling a retry + // here would poll a server that is still null, so the payload + // waits for the next update, which re-opens one. pendingNotifications.addFirst(next) return } @@ -652,10 +811,18 @@ class UniversalBlePeripheralPlugin( } }.getOrDefault(false) if (!sent) { - // Native queue still busy. Put the payload back at the front and - // wait for onNotificationSent to retry; never drop a release. + // The stack is still busy with this client (or, below API 33, + // refused without saying why). Put the payload back at the front + // and retry on a coalesced delay; never drop a release. Waiting + // for onNotificationSent alone would stall until an unrelated + // update, because a refusal leaves no packet for it to report. notificationsInFlight.remove(deviceAddress) pendingNotifications.addFirst(next) + scheduleNotificationRetryLocked(deviceAddress) + } else { + // Handed to the stack: no retry is needed any more, and the next + // refusal starts the backoff over. + clearNotificationRetryLocked(deviceAddress) } } } @@ -692,6 +859,13 @@ class UniversalBlePeripheralPlugin( } } settleNotifications(removed, IllegalStateException("Notification cancelled")) + // Whatever was queued for the client is gone, so a pending retry has + // nothing left to send. + if (deviceId == null) { + clearNotificationRetries() + } else { + clearNotificationRetry(deviceId) + } } override fun getSubscribedClients( @@ -756,6 +930,8 @@ class UniversalBlePeripheralPlugin( } val removed = dropNotifications { it.device.address == deviceAddress } settleNotifications(removed, IllegalStateException("Device disconnected")) + // The client's queue is gone, so its retry must not wake up against it. + clearNotificationRetry(deviceAddress) } private val advertiseCallback = object : AdvertiseCallback() { @@ -997,6 +1173,9 @@ class UniversalBlePeripheralPlugin( it.device.address == address && it.characteristic === characteristic } settleNotifications(removed, IllegalStateException("Central unsubscribed")) + // A retry for another characteristic of this client may + // still be needed; one for the payloads just dropped is not. + clearNotificationRetryIfIdle(address) } } } diff --git a/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt index 7e50bd1d..8dbd76b4 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt @@ -85,6 +85,8 @@ internal class PeripheralRegressionTest { plugin.setField("mtuByDeviceId", HashMap()) plugin.setField("pendingNotifications", ArrayDeque()) plugin.setField("notificationsInFlight", HashMap()) + plugin.setField("notificationRetries", HashMap()) + plugin.setField("notificationRetryAttempts", HashMap()) return plugin } @@ -97,6 +99,43 @@ internal class PeripheralRegressionTest { } } + /** A runnable the plugin posted with a delay, captured so a test can run it. */ + private data class DelayedPost(val delayMillis: Long, val runnable: Runnable) + + /** + * Captures `handler.postDelayed` calls instead of waiting for a clock, so a + * retry test decides when the retry happens. The returned list grows as the + * plugin schedules more retries. + */ + private fun UniversalBlePeripheralPlugin.captureDelayedRunnables(): MutableList { + val posted = mutableListOf() + val handler = field("handler") + Mockito.`when`(handler.postDelayed(Mockito.any(Runnable::class.java), Mockito.anyLong())) + .thenAnswer { + posted.add(DelayedPost(it.getArgument(1), it.getArgument(0))) + true + } + return posted + } + + private fun UniversalBlePeripheralPlugin.pendingRetries(): Map = + field("notificationRetries") + + private fun UniversalBlePeripheralPlugin.retryAttempts(): Map = + field("notificationRetryAttempts") + + /** + * Drives the private disconnect cleanup directly: the callback that normally + * reaches it also logs through `android.util.Log`, which the JVM unit tests + * do not mock. + */ + private fun UniversalBlePeripheralPlugin.cleanConnection(device: BluetoothDevice) { + val method = UniversalBlePeripheralPlugin::class.java + .getDeclaredMethod("cleanConnection", BluetoothDevice::class.java) + method.isAccessible = true + method.invoke(this, device) + } + private fun UniversalBlePeripheralPlugin.setField(name: String, value: Any?) { val field = UniversalBlePeripheralPlugin::class.java.getDeclaredField(name) field.isAccessible = true @@ -153,6 +192,30 @@ internal class PeripheralRegressionTest { return characteristic } + /** + * Two notify characteristics, each in its own service, subscribed by + * [deviceAddress] as "report-1" and "report-2". + */ + private fun UniversalBlePeripheralPlugin.subscribedNotifyCharacteristics(): + Pair { + val firstService = mockService(hid) + val secondService = mockService(otherService) + val first = mockCharacteristic(report, firstService) + val second = mockCharacteristic(otherReport, secondService) + listOf(first, second).forEach { + Mockito.`when`(it.properties).thenReturn(BluetoothGattCharacteristic.PROPERTY_NOTIFY) + } + characteristics()[report] = first + characteristics()["report-1"] = first + characteristicInstanceIds()[first] = "report-1" + characteristics()[otherReport] = second + characteristics()["report-2"] = second + characteristicInstanceIds()[second] = "report-2" + subscribedCharDevicesMap[deviceAddress] = mutableSetOf("report-1", "report-2") + connectedDevice() + return first to second + } + /** The pre-API-33 path the JVM tests take: the stack accepts the notification. */ private fun BluetoothGattServer.acceptNotifications() { Mockito.`when`( @@ -164,6 +227,21 @@ internal class PeripheralRegressionTest { ).thenReturn(true) } + /** The client's native transmit queue is still busy, so the stack refuses. */ + private fun BluetoothGattServer.refuseNotifications() { + Mockito.`when`( + notifyCharacteristicChanged( + Mockito.any(BluetoothDevice::class.java), + Mockito.any(BluetoothGattCharacteristic::class.java), + Mockito.anyBoolean(), + ), + ).thenReturn(false) + } + + private fun BluetoothGattServer.notifyCalls(): Int = + Mockito.mockingDetails(this).invocations + .count { it.method.name == "notifyCharacteristicChanged" } + /** Every value the plugin assigned to [characteristic], in order. */ private fun valuesSetOn(characteristic: BluetoothGattCharacteristic): List> = Mockito.mockingDetails(characteristic).invocations @@ -296,6 +374,280 @@ internal class PeripheralRegressionTest { assertTrue(results[1].isSuccess, "The in-flight packet is still settled by its callback") } + // #406: a refused send leaves nothing for onNotificationSent to report, so + // without its own retry the client's queue waits for an unrelated update. + @Test fun refusedNotificationIsRetriedWithoutAnotherUpdate() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + val characteristic = plugin.subscribedNotifyCharacteristic() + server.refuseNotifications() + val results = mutableListOf>() + + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + + assertEquals(1, retries.size, "The refusal schedules exactly one retry") + assertEquals(10L, retries.single().delayMillis, "The first retry uses the base delay") + assertTrue(plugin.pendingRetries().containsKey(deviceAddress)) + assertEquals(mapOf(deviceAddress to 1), plugin.retryAttempts()) + assertEquals(1, server.notifyCalls()) + assertTrue(results.isEmpty(), "The Dart callback waits for the retry") + + // The stack has room now: the same payload goes out again. + server.acceptNotifications() + retries.removeAt(0).runnable.run() + + assertEquals(listOf(listOf(1), listOf(1)), valuesSetOn(characteristic)) + assertTrue(results.isEmpty(), "The callback still waits for onNotificationSent") + + plugin.handleNotificationSent(plugin.connectedDevice(), BluetoothGatt.GATT_SUCCESS) + + assertEquals(1, results.size) + assertTrue(results.single().isSuccess) + assertTrue(plugin.pendingRetries().isEmpty()) + assertTrue(plugin.retryAttempts().isEmpty(), "The next refusal starts from the base delay") + } + + // #406: one client, one retry — several queued updates must not post one each. + @Test fun queuedUpdatesForOneClientShareARejectedRetry() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristic() + server.refuseNotifications() + val results = mutableListOf>() + + repeat(3) { index -> + plugin.updateCharacteristic(report, "report-1", byteArrayOf(index.toByte()), deviceAddress) { + results.add(it) + } + } + + assertEquals(1, retries.size, "The updates coalesce into a single retry") + assertEquals(mapOf(deviceAddress to 1), plugin.retryAttempts()) + assertEquals(3, server.notifyCalls(), "Each update tried the send once") + assertTrue(results.isEmpty()) + } + + // #406: the backoff doubles per consecutive refusal, then stays at the cap. + @Test fun refusedRetriesBackOffAndCap() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristic() + server.refuseNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + + val delays = mutableListOf() + // Each run is refused again and schedules the next attempt. + repeat(8) { + val retry = retries.removeAt(0) + delays.add(retry.delayMillis) + retry.runnable.run() + } + + assertEquals(listOf(10L, 20L, 40L, 80L, 160L, 320L, 500L, 500L), delays) + assertEquals(1, retries.size, "Only the latest retry is live") + assertEquals( + 7, + plugin.retryAttempts()[deviceAddress], + "The counter stops at the ceiling instead of overflowing", + ) + assertTrue(results.isEmpty()) + } + + // #406: a client that unsubscribes while the payload waits must not receive + // it, and the retry must not loop forever. + @Test fun retryDropsThePayloadOfAClientThatUnsubscribed() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristic() + server.refuseNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + assertEquals(1, server.notifyCalls()) + + // The central writes the CCCD off before the retry fires. + subscribedCharDevicesMap.remove(deviceAddress) + retries.removeAt(0).runnable.run() + + assertEquals(1, results.size) + assertTrue(results.single().isFailure) + assertEquals("Central unsubscribed", results.single().exceptionOrNull()?.message) + assertEquals(1, server.notifyCalls(), "The stale payload is not sent again") + assertTrue(plugin.pendingRetries().isEmpty()) + assertTrue(plugin.retryAttempts().isEmpty()) + + // Resubscribing does not resurrect it either. + subscribedCharDevicesMap[deviceAddress] = mutableSetOf("report-1") + server.acceptNotifications() + retries.forEach { it.runnable.run() } + assertEquals(1, server.notifyCalls()) + assertEquals(1, results.size) + } + + // #406: resetting the peripheral takes the retry with the queue it belongs to. + @Test fun peripheralResetCancelsThePendingRetry() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristic() + server.refuseNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + val retry = retries.single() + assertTrue(plugin.pendingRetries().containsKey(deviceAddress)) + + plugin.onAdapterStateChanged(BluetoothAdapter.STATE_TURNING_OFF) + + assertEquals(1, results.size, "The queued payload is failed by the cleanup") + assertTrue(results.single().isFailure) + assertTrue(plugin.pendingRetries().isEmpty()) + assertTrue(plugin.retryAttempts().isEmpty()) + Mockito.verify(plugin.field("handler")).removeCallbacks(retry.runnable) + + // A retry that still fires against the torn-down state is a no-op. + retry.runnable.run() + assertEquals(1, server.notifyCalls()) + } + + // #406: a per-client cancel takes the retry too, matching the id's case. + @Test fun clearPendingNotificationsCancelsTheRetry() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristic() + server.refuseNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + val retry = retries.single() + + plugin.clearPendingNotifications(deviceAddress.lowercase()) + + assertEquals(1, results.size) + assertTrue(results.single().isFailure) + assertTrue(plugin.pendingRetries().isEmpty()) + assertTrue(plugin.retryAttempts().isEmpty()) + Mockito.verify(plugin.field("handler")).removeCallbacks(retry.runnable) + } + + // #406: a disconnect takes the client's queue and its retry apart together. + @Test fun disconnectCancelsThePendingRetry() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristic() + server.refuseNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + val retry = retries.single() + + plugin.cleanConnection(plugin.connectedDevice()) + + assertEquals(1, results.size, "The queued payload is failed by the disconnect") + assertTrue(results.single().isFailure) + assertTrue(plugin.pendingRetries().isEmpty()) + assertTrue(plugin.retryAttempts().isEmpty()) + Mockito.verify(plugin.field("handler")).removeCallbacks(retry.runnable) + + retry.runnable.run() + assertEquals(1, server.notifyCalls(), "A retry against the torn-down queue sends nothing") + } + + // #406: removing a service must take the retry only when nothing else of the + // client is queued, so another service's refused payload is still retried. + @Test fun removeServiceCancelsTheRetryOnlyWhenNothingElseIsQueued() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristics() + server.refuseNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + plugin.updateCharacteristic(otherReport, "report-2", byteArrayOf(2), deviceAddress) { + results.add(it) + } + val retry = retries.single() + + plugin.removeService(hid) + + assertEquals(1, results.size, "Only the removed service's payload is failed") + assertTrue(results.single().isFailure) + assertEquals("Service removed", results.single().exceptionOrNull()?.message) + assertTrue( + plugin.pendingRetries().containsKey(deviceAddress), + "The other service's payload still needs its retry", + ) + Mockito.verify(plugin.field("handler"), Mockito.never()) + .removeCallbacks(retry.runnable) + + plugin.removeService(otherService) + + assertEquals(2, results.size) + assertTrue(results[1].isFailure) + assertTrue(plugin.pendingRetries().isEmpty()) + assertTrue(plugin.retryAttempts().isEmpty()) + Mockito.verify(plugin.field("handler")).removeCallbacks(retry.runnable) + } + + // #406: dropping the characteristic the client unsubscribed from must not + // stop the client's other characteristics from draining, and the backoff + // keeps counting across the drop. + @Test fun retryDropsTheUnsubscribedCharacteristicAndDrainsTheOther() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val retries = plugin.captureDelayedRunnables() + plugin.subscribedNotifyCharacteristics() + server.refuseNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + plugin.updateCharacteristic(otherReport, "report-2", byteArrayOf(2), deviceAddress) { + results.add(it) + } + assertEquals(2, server.notifyCalls()) + // The client drops the first characteristic while its payload waits, + // without the queue dropping it (the window this retry covers). + subscribedCharDevicesMap[deviceAddress] = mutableSetOf("report-2") + + retries.removeAt(0).runnable.run() + + assertEquals(1, results.size) + assertTrue(results.single().isFailure) + assertEquals("Central unsubscribed", results.single().exceptionOrNull()?.message) + assertEquals(3, server.notifyCalls(), "The other characteristic is attempted again") + assertEquals(1, retries.size, "The other characteristic's refusal keeps retrying") + assertEquals(20L, retries.single().delayMillis, "The backoff continues across the drop") + + server.acceptNotifications() + retries.removeAt(0).runnable.run() + assertEquals(4, server.notifyCalls()) + assertEquals(1, results.size, "The retried payload still waits for onNotificationSent") + plugin.handleNotificationSent(plugin.connectedDevice(), BluetoothGatt.GATT_SUCCESS) + + assertEquals(2, results.size) + assertTrue(results[1].isSuccess) + assertTrue(plugin.pendingRetries().isEmpty()) + assertTrue(plugin.retryAttempts().isEmpty()) + } + @Test fun resetFailsTheNotificationInFlight() { val server = Mockito.mock(BluetoothGattServer::class.java) val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() }