Modern Apps git

← Modern-Apps.git

wearlink: add Watch conduit protocol, router and client node

Commit
04efa56d6bffe78ea6342efb82fbdfed15c22f2d
Author
Vayun Mathur <[email protected]>
When
2026-12-01 18:48 UTC (4 days ago)
Parents
398450d
Stage A of the Watch conduit: the Watch apps become the sole
phone<->watch messaging holders, and every other app reaches the
link through a local Messenger conduit instead of its own RFCOMM
WearLinkNode.

- ConduitProtocol: shared Messenger codes/Bundle keys, explicit
  Watch service component, signature permission name, and the
  first-path-segment route key.
- ConduitRouter (pure, unit-tested with fake sinks): registrations
  by appId, latest-data cache replayed on register, bounded
  per-appId queue for unregistered apps, path-prefix routing with
  sender-namespace enforcement, stream routing, status fan-out and
  per-app traffic counters.
- WearLinkClientNode: drop-in for WearLinkNode over the conduit
  binding; NotInstalled/Unavailable states (new WearLinkState
  subtypes, existing consumers only check Connected) instead of
  crashing when the Watch app is absent. request() returns null as
  unsupported - it is unused repo-wide.
- WearLinkState gains NotInstalled/Unavailable for client nodes.

Verified: :library:wearlink:testDebugUnitTest passes, including
the new ConduitRouterTest suite.

Diff

library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.ktindex 41e78c8a9e..d8434486c7 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt@@ -106,4 +106,10 @@ sealed interface WearLinkState {     data class Connecting(val peerLabel: String) : WearLinkState     data class Connected(val peerLabel: String) : WearLinkState     data class Failed(val reason: String) : WearLinkState++    /** The Watch conduit app is not installed on this device (client nodes only). */+    data object NotInstalled : WearLinkState++    /** The Watch conduit app is installed but its service is not bound (client nodes only). */+    data object Unavailable : WearLinkState }
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitProtocol.ktnew file mode 100644index 0000000000..b3e6b9b021--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitProtocol.kt@@ -0,0 +1,107 @@+package com.vayunmathur.library.wearlink.conduit++/**+ * Messenger wire contract for the Watch conduit (Stage A).+ *+ * The Watch apps (`watch/` phone, `watch-wear/` watch, both+ * `applicationId com.vayunmathur.watch`) are the sole holders of the+ * Bluetooth permissions and the sole owners of a real+ * [com.vayunmathur.library.wearlink.WearLinkNode] (appId+ * [CONDUIT_APP_ID]). Every other app talks to its local conduit over a+ * signature-permission Messenger bound service instead of opening its+ * own RFCOMM link. This object is the shared contract: both the conduit+ * services and [WearLinkClientNode] depend on `:library:wearlink`, so+ * the codes live here exactly once (the FamilyLocationService precedent+ * duplicated them per app because no shared module fit; here one does).+ *+ * Routing key: the first path segment (`/clock/...` -> `clock`) names+ * the owning appId. A client may only register for, and send on, paths+ * under its own appId.+ */+object ConduitProtocol {+    /** WearLink handshake appId used by the two conduit services. */+    const val CONDUIT_APP_ID = "watch_conduit"++    /** Package / applicationId of both Watch apps. */+    const val WATCH_PACKAGE = "com.vayunmathur.watch"++    /** Explicit component of the conduit service in the Watch app. */+    const val SERVICE_CLASS = "com.vayunmathur.watch.service.ConduitService"++    /** Bind action (the component is set explicitly as well). */+    const val ACTION = "com.vayunmathur.watch.action.CONDUIT"++    /** Signature permission guarding the bound service, declared in both Watch manifests. */+    const val PERMISSION = "com.vayunmathur.watch.permissions.CONDUIT"++    // client -> conduit+    /** Register [KEY_APP_ID]; `replyTo` is the client's callback Messenger. */+    const val MSG_REGISTER = 1++    /** Unregister the sender's previously registered appId. */+    const val MSG_UNREGISTER = 2++    /** Send a message: [KEY_PATH], [KEY_BODY], optional [KEY_REQUIRE_ACK]. */+    const val MSG_SEND_MESSAGE = 3++    /** Publish a data item: [KEY_PATH], [KEY_BODY]. */+    const val MSG_PUT_DATA = 4++    /** Open an outbound stream: [KEY_STREAM_ID], [KEY_PATH], [KEY_TOTAL_SIZE], [KEY_SHA256]. */+    const val MSG_STREAM_OPEN = 5++    /** One outbound stream chunk: [KEY_STREAM_ID], [KEY_BODY]. */+    const val MSG_STREAM_CHUNK = 6++    /** Close an outbound stream: [KEY_STREAM_ID]. */+    const val MSG_STREAM_CLOSE = 7++    // conduit -> client+    /** Inbound message: [KEY_PATH], [KEY_BODY]. */+    const val MSG_ON_MESSAGE = 101++    /** Inbound (or replayed) data item: [KEY_PATH], [KEY_BODY]. */+    const val MSG_ON_DATA = 102++    /** Link status fan-out: [KEY_STATE], optional [KEY_REASON] / [KEY_PEER_LABEL]. */+    const val MSG_ON_STATUS = 103++    /** Inbound stream opening: [KEY_STREAM_ID], [KEY_PATH], [KEY_TOTAL_SIZE], [KEY_SHA256]. */+    const val MSG_ON_STREAM_OPEN = 104++    /** Inbound stream chunk: [KEY_STREAM_ID], [KEY_BODY]. */+    const val MSG_ON_STREAM_CHUNK = 105++    /** Inbound stream closed: [KEY_STREAM_ID], [KEY_VERIFIED]. */+    const val MSG_ON_STREAM_CLOSE = 106++    // Bundle keys+    const val KEY_APP_ID = "appId"+    const val KEY_PATH = "path"+    const val KEY_BODY = "body"+    const val KEY_REQUIRE_ACK = "requireAck"+    const val KEY_STREAM_ID = "streamId"+    const val KEY_TOTAL_SIZE = "totalSize"+    const val KEY_SHA256 = "sha256"+    const val KEY_STATE = "state"+    const val KEY_REASON = "reason"+    const val KEY_PEER_LABEL = "peerLabel"+    const val KEY_VERIFIED = "verified"++    // Status values carried by KEY_STATE (mirror WearLinkState names).+    const val STATUS_STOPPED = "Stopped"+    const val STATUS_PERMISSION_MISSING = "PermissionMissing"+    const val STATUS_BLUETOOTH_OFF = "BluetoothOff"+    const val STATUS_NO_BONDED_PEER = "NoBondedPeer"+    const val STATUS_CONNECTING = "Connecting"+    const val STATUS_CONNECTED = "Connected"+    const val STATUS_FAILED = "Failed"+    const val STATUS_NOT_INSTALLED = "NotInstalled"+    const val STATUS_UNAVAILABLE = "Unavailable"++    /** First path segment: `/clock/snapshot` -> `clock`; `clock/x` -> `clock`. */+    fun routeKey(path: String): String = path.trimStart('/').substringBefore('/')++    /** True when [path] is namespaced under [appId]. */+    fun owns(appId: String, path: String): Boolean = appId.isNotEmpty() && routeKey(path) == appId+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.ktnew file mode 100644index 0000000000..00da9a3cc9--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt@@ -0,0 +1,214 @@+package com.vayunmathur.library.wearlink.conduit++import com.vayunmathur.library.wearlink.StreamHeader++/** Local client endpoint the router delivers inbound traffic to. Pure: no Android types. */+interface ConduitDownstream {+    fun deliverMessage(path: String, body: ByteArray)+    fun deliverData(path: String, body: ByteArray)+    fun deliverStatus(state: String, peerLabel: String?, reason: String?)++    /** Accept an inbound stream; false refuses it. Chunks/close follow by stream id. */+    fun deliverStreamOpen(streamId: Long, path: String, header: StreamHeader): Boolean+    fun deliverStreamChunk(streamId: Long, body: ByteArray)+    fun deliverStreamClose(streamId: Long, verified: Boolean)+}++/** Peer endpoint (the single WearLinkNode) the router forwards outbound traffic to. */+interface ConduitUpstream {+    fun sendMessage(path: String, body: ByteArray, requireAck: Boolean): Boolean+    fun putData(path: String, body: ByteArray): Boolean+    fun sendStream(path: String, header: StreamHeader, chunks: List<ByteArray>): Boolean+}++/** Per-app traffic counters surfaced by the Watch status UI. */+data class ConduitCounters(+    val messagesOut: Long = 0,+    val messagesIn: Long = 0,+    val dataOut: Long = 0,+    val dataIn: Long = 0,+    val streamsOut: Long = 0,+    val streamsIn: Long = 0,+    val queuedDropped: Long = 0,+)++/**+ * Pure routing core of the conduit, shared verbatim by the phone and+ * watch services and unit-tested with fake messengers (sinks).+ *+ * Holds: registrations by appId; the latest verified data item per+ * (appId, path), replayed to a client the moment it registers; a bounded+ * per-appId queue of messages that arrived for an app with no local+ * registration (flushed on register, oldest dropped past the bound);+ * inbound stream routing by stream id; and link-status fan-out to every+ * registered client. Outbound traffic whose route key does not match the+ * sending registration is refused, so one app cannot speak for another.+ * All methods are synchronized; sinks are called under the lock and must+ * not block (Messenger sends satisfy this).+ */+class ConduitRouter(+    private val maxQueuedPerApp: Int = DEFAULT_MAX_QUEUED_PER_APP,+    private val upstream: ConduitUpstream,+) {+    companion object {+        const val DEFAULT_MAX_QUEUED_PER_APP = 32+    }++    private data class QueuedMessage(val path: String, val body: ByteArray)++    private val clients = mutableMapOf<String, ConduitDownstream>()+    private val dataCache = mutableMapOf<Pair<String, String>, ByteArray>()+    private val queues = mutableMapOf<String, ArrayDeque<QueuedMessage>>()+    private val inboundStreams = mutableMapOf<Long, String>()+    private val outboundStreams = mutableMapOf<Long, Pair<String, MutableList<ByteArray>>>()+    private val outboundHeaders = mutableMapOf<Long, Pair<String, StreamHeader>>()+    private val counters = mutableMapOf<String, ConduitCounters>()+    private var linkState: String = ConduitProtocol.STATUS_STOPPED+    private var linkPeer: String? = null+    private var linkReason: String? = null++    @Synchronized+    fun registeredApps(): Set<String> = clients.keys.toSet()++    @Synchronized+    fun countersSnapshot(): Map<String, ConduitCounters> = counters.toMap()++    @Synchronized+    fun cachedDataCount(): Int = dataCache.size++    /** Register [appId]; replays its cached data and queued messages, then current status. */+    @Synchronized+    fun register(appId: String, downstream: ConduitDownstream) {+        if (appId.isEmpty()) return+        clients[appId] = downstream+        counters.putIfAbsent(appId, ConduitCounters())+        for ((key, body) in dataCache) {+            if (key.first == appId) downstream.deliverData(key.second, body)+        }+        queues.remove(appId)?.let { queued ->+            for (message in queued) downstream.deliverMessage(message.path, message.body)+        }+        downstream.deliverStatus(linkState, linkPeer, linkReason)+    }++    @Synchronized+    fun unregister(appId: String) {+        clients.remove(appId)+        inboundStreams.entries.removeAll { it.value == appId }+    }++    @Synchronized+    fun isRegistered(appId: String): Boolean = clients.containsKey(appId)++    // -- Local (client -> peer) ---------------------------------------------++    @Synchronized+    fun onLocalMessage(appId: String, path: String, body: ByteArray, requireAck: Boolean): Boolean {+        if (!ConduitProtocol.owns(appId, path)) return false+        bump(appId) { it.copy(messagesOut = it.messagesOut + 1) }+        return upstream.sendMessage(path, body, requireAck)+    }++    @Synchronized+    fun onLocalData(appId: String, path: String, body: ByteArray): Boolean {+        if (!ConduitProtocol.owns(appId, path)) return false+        dataCache[appId to path] = body+        bump(appId) { it.copy(dataOut = it.dataOut + 1) }+        return upstream.putData(path, body)+    }++    /** Buffer an outbound stream; forwarded whole to the peer on close (Stage A). */+    @Synchronized+    fun onLocalStreamOpen(appId: String, streamId: Long, path: String, header: StreamHeader): Boolean {+        if (!ConduitProtocol.owns(appId, path)) return false+        outboundStreams[streamId] = appId to mutableListOf()+        outboundHeaders[streamId] = path to header+        return true+    }++    @Synchronized+    fun onLocalStreamChunk(streamId: Long, body: ByteArray) {+        outboundStreams[streamId]?.second?.add(body)+    }++    @Synchronized+    fun onLocalStreamClose(streamId: Long): Boolean {+        val (appId, chunks) = outboundStreams.remove(streamId) ?: return false+        val (path, header) = outboundHeaders.remove(streamId) ?: return false+        bump(appId) { it.copy(streamsOut = it.streamsOut + 1) }+        return upstream.sendStream(path, header, chunks)+    }++    // -- Peer (WearLinkNode -> local clients) --------------------------------++    @Synchronized+    fun onPeerMessage(path: String, body: ByteArray) {+        val appId = ConduitProtocol.routeKey(path)+        if (appId.isEmpty()) return+        bump(appId) { it.copy(messagesIn = it.messagesIn + 1) }+        val client = clients[appId]+        if (client != null) {+            client.deliverMessage(path, body)+        } else {+            enqueue(appId, QueuedMessage(path, body))+        }+    }++    @Synchronized+    fun onPeerData(path: String, body: ByteArray) {+        val appId = ConduitProtocol.routeKey(path)+        if (appId.isEmpty()) return+        dataCache[appId to path] = body+        bump(appId) { it.copy(dataIn = it.dataIn + 1) }+        clients[appId]?.deliverData(path, body)+    }++    @Synchronized+    fun onPeerStreamOpen(streamId: Long, path: String, header: StreamHeader): Boolean {+        val appId = ConduitProtocol.routeKey(path)+        if (appId.isEmpty()) return false+        val client = clients[appId] ?: return false+        if (!client.deliverStreamOpen(streamId, path, header)) return false+        inboundStreams[streamId] = appId+        bump(appId) { it.copy(streamsIn = it.streamsIn + 1) }+        return true+    }++    @Synchronized+    fun onPeerStreamChunk(streamId: Long, body: ByteArray) {+        val appId = inboundStreams[streamId] ?: return+        clients[appId]?.deliverStreamChunk(streamId, body)+    }++    @Synchronized+    fun onPeerStreamClose(streamId: Long, verified: Boolean) {+        val appId = inboundStreams.remove(streamId) ?: return+        clients[appId]?.deliverStreamClose(streamId, verified)+    }++    // -- Status ---------------------------------------------------------------++    @Synchronized+    fun setLinkStatus(state: String, peerLabel: String? = null, reason: String? = null) {+        linkState = state+        linkPeer = peerLabel+        linkReason = reason+        for (client in clients.values) client.deliverStatus(state, peerLabel, reason)+    }++    @Synchronized+    fun linkStatus(): Triple<String, String?, String?> = Triple(linkState, linkPeer, linkReason)++    private fun enqueue(appId: String, message: QueuedMessage) {+        val queue = queues.getOrPut(appId) { ArrayDeque() }+        queue.addLast(message)+        while (queue.size > maxQueuedPerApp) {+            queue.removeFirst()+            bump(appId) { it.copy(queuedDropped = it.queuedDropped + 1) }+        }+    }++    private fun bump(appId: String, update: (ConduitCounters) -> ConduitCounters) {+        counters[appId] = update(counters[appId] ?: ConduitCounters())+    }+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/WearLinkClientNode.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/WearLinkClientNode.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/WearLinkClientNode.ktnew file mode 100644index 0000000000..9f9d21574a--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/WearLinkClientNode.kt@@ -0,0 +1,256 @@+package com.vayunmathur.library.wearlink.conduit++import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.content.ServiceConnection+import android.os.Bundle+import android.os.Handler+import android.os.HandlerThread+import android.os.IBinder+import android.os.Message+import android.os.Messenger+import android.os.RemoteException+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.StreamHeader+import com.vayunmathur.library.wearlink.StreamSink+import com.vayunmathur.library.wearlink.StreamSource+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkProtocol+import com.vayunmathur.library.wearlink.WearLinkState+import java.util.concurrent.atomic.AtomicLong+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * Drop-in replacement for+ * [com.vayunmathur.library.wearlink.WearLinkNode] with the same used API+ * (constructor, [start]/[stop], [state], [sendMessage], [putData],+ * [sendStream] and the [WearLinkListener] callbacks), implemented over a+ * Messenger binding to the Watch app's conduit service instead of owning+ * an RFCOMM link. Only the Watch apps hold Bluetooth permissions; client+ * apps hold none for this channel.+ *+ * If the Watch app is absent the node reports [WearLinkState.NotInstalled];+ * if it is present but the service cannot be bound it reports+ * [WearLinkState.Unavailable]. Neither case crashes or blocks: sends+ * simply return false, exactly as an unconnected node does today.+ *+ * [request] is unsupported: it returns null. It is unused repo-wide (all+ * thirteen pairs use putData snapshots + sendMessage ops), so the conduit+ * protocol carries no request/response correlation; adding one later is+ * additive (a new message code), not a redesign.+ *+ * Ack semantics: with `requireAck = true`, [sendMessage] returns true once+ * the conduit has accepted the message for forwarding, not once the peer+ * app has processed it — the conduit has no per-message peer ack today.+ */+class WearLinkClientNode(+    context: Context,+    private val appId: String,+    private val listener: WearLinkListener,+) {+    private val appContext = context.applicationContext+    private val _state = MutableStateFlow<WearLinkState>(WearLinkState.Stopped)+    val state: StateFlow<WearLinkState> = _state.asStateFlow()+    val isConnected: Boolean get() = _state.value is WearLinkState.Connected++    private val streamIds = AtomicLong(1)+    private var thread: HandlerThread? = null+    private var incoming: Messenger? = null+    @Volatile private var conduit: Messenger? = null+    @Volatile private var bound = false+    private val inboundSinks = mutableMapOf<Long, Pair<StreamSink, Long>>()++    private val connection = object : ServiceConnection {+        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {+            val target = service?.let { Messenger(it) } ?: return+            conduit = target+            sendToConduit(ConduitProtocol.MSG_REGISTER) {+                putString(ConduitProtocol.KEY_APP_ID, appId)+            }+        }++        override fun onServiceDisconnected(name: ComponentName?) {+            conduit = null+            if (bound) _state.value = WearLinkState.Unavailable+        }+    }++    fun start() {+        if (bound) return+        if (!isWatchInstalled()) {+            _state.value = WearLinkState.NotInstalled+            Log.status(TAG, "Watch app not installed; conduit unavailable for $appId")+            return+        }+        val worker = HandlerThread("WearLinkClient-$appId").also { it.start() }+        thread = worker+        incoming = Messenger(Handler(worker.looper) { msg -> handleConduitMessage(msg) })+        val intent = Intent(ConduitProtocol.ACTION).apply {+            component = ComponentName(ConduitProtocol.WATCH_PACKAGE, ConduitProtocol.SERVICE_CLASS)+        }+        bound = runCatching { appContext.bindService(intent, connection, Context.BIND_AUTO_CREATE) }+            .getOrDefault(false)+        if (!bound) {+            _state.value = WearLinkState.Unavailable+            worker.quitSafely()+            thread = null+        }+    }++    fun stop() {+        if (bound) {+            sendToConduit(ConduitProtocol.MSG_UNREGISTER) {+                putString(ConduitProtocol.KEY_APP_ID, appId)+            }+            runCatching { appContext.unbindService(connection) }+        }+        bound = false+        conduit = null+        thread?.quitSafely()+        thread = null+        synchronized(inboundSinks) { inboundSinks.clear() }+        _state.value = WearLinkState.Stopped+    }++    suspend fun sendMessage(path: String, body: ByteArray, requireAck: Boolean = false): Boolean {+        if (body.size > WearLinkProtocol.MAX_MESSAGE_BYTES) return false+        return sendToConduit(ConduitProtocol.MSG_SEND_MESSAGE) {+            putString(ConduitProtocol.KEY_APP_ID, appId)+            putString(ConduitProtocol.KEY_PATH, path)+            putByteArray(ConduitProtocol.KEY_BODY, body)+            putBoolean(ConduitProtocol.KEY_REQUIRE_ACK, requireAck)+        }+    }++    /** Unsupported over the conduit (unused repo-wide); always returns null. See class KDoc. */+    suspend fun request(path: String, body: ByteArray, timeoutMillis: Long = 10_000): ByteArray? = null++    suspend fun putData(path: String, body: ByteArray): Boolean {+        if (body.size > WearLinkProtocol.MAX_DATA_ITEM_BYTES) return false+        return sendToConduit(ConduitProtocol.MSG_PUT_DATA) {+            putString(ConduitProtocol.KEY_APP_ID, appId)+            putString(ConduitProtocol.KEY_PATH, path)+            putByteArray(ConduitProtocol.KEY_BODY, body)+        }+    }++    suspend fun sendStream(path: String, source: StreamSource): Boolean {+        if (source.size > WearLinkProtocol.MAX_STREAM_BYTES) return false+        val streamId = streamIds.getAndIncrement()+        if (!sendToConduit(ConduitProtocol.MSG_STREAM_OPEN) {+                putString(ConduitProtocol.KEY_APP_ID, appId)+                putLong(ConduitProtocol.KEY_STREAM_ID, streamId)+                putString(ConduitProtocol.KEY_PATH, path)+                putLong(ConduitProtocol.KEY_TOTAL_SIZE, source.size)+                putString(ConduitProtocol.KEY_SHA256, source.sha256)+            }+        ) return false+        var offset = 0L+        while (offset < source.size) {+            val length = minOf(+                WearLinkProtocol.STREAM_CHUNK_BYTES.toLong(), source.size - offset,+            ).toInt()+            val chunk = source.readAt(offset, length)+            if (!sendToConduit(ConduitProtocol.MSG_STREAM_CHUNK) {+                    putLong(ConduitProtocol.KEY_STREAM_ID, streamId)+                    putByteArray(ConduitProtocol.KEY_BODY, chunk)+                }+            ) return false+            offset += chunk.size+        }+        return sendToConduit(ConduitProtocol.MSG_STREAM_CLOSE) {+            putLong(ConduitProtocol.KEY_STREAM_ID, streamId)+        }+    }++    private fun isWatchInstalled(): Boolean = runCatching {+        appContext.packageManager.getPackageInfo(ConduitProtocol.WATCH_PACKAGE, 0)+        true+    }.getOrDefault(false)++    private fun sendToConduit(what: Int, fill: Bundle.() -> Unit): Boolean {+        val target = conduit ?: return false+        val reply = incoming ?: return false+        return try {+            val message = Message.obtain(null, what)+            message.replyTo = reply+            message.data = Bundle().apply(fill)+            target.send(message)+            true+        } catch (_: RemoteException) {+            false+        }+    }++    private fun handleConduitMessage(message: Message): Boolean {+        val data = message.data ?: return true+        when (message.what) {+            ConduitProtocol.MSG_ON_MESSAGE -> listener.onMessage(+                data.getString(ConduitProtocol.KEY_PATH) ?: return true,+                data.getByteArray(ConduitProtocol.KEY_BODY) ?: ByteArray(0),+            )+            ConduitProtocol.MSG_ON_DATA -> listener.onData(+                data.getString(ConduitProtocol.KEY_PATH) ?: return true,+                data.getByteArray(ConduitProtocol.KEY_BODY) ?: ByteArray(0),+            )+            ConduitProtocol.MSG_ON_STATUS -> _state.value = mapStatus(+                data.getString(ConduitProtocol.KEY_STATE),+                data.getString(ConduitProtocol.KEY_PEER_LABEL),+                data.getString(ConduitProtocol.KEY_REASON),+            )+            ConduitProtocol.MSG_ON_STREAM_OPEN -> onStreamOpen(data)+            ConduitProtocol.MSG_ON_STREAM_CHUNK -> onStreamChunk(data)+            ConduitProtocol.MSG_ON_STREAM_CLOSE -> onStreamClose(data)+        }+        return true+    }++    private fun onStreamOpen(data: Bundle) {+        val streamId = data.getLong(ConduitProtocol.KEY_STREAM_ID)+        val path = data.getString(ConduitProtocol.KEY_PATH) ?: return+        val header = StreamHeader(+            data.getLong(ConduitProtocol.KEY_TOTAL_SIZE),+            data.getString(ConduitProtocol.KEY_SHA256) ?: "",+        )+        val sink = listener.onStreamOpen(path, header) ?: return+        synchronized(inboundSinks) { inboundSinks[streamId] = sink to sink.resumeOffset }+    }++    private fun onStreamChunk(data: Bundle) {+        val streamId = data.getLong(ConduitProtocol.KEY_STREAM_ID)+        val bytes = data.getByteArray(ConduitProtocol.KEY_BODY) ?: return+        synchronized(inboundSinks) {+            val (sink, offset) = inboundSinks[streamId] ?: return+            runCatching { sink.write(bytes, offset) }+            inboundSinks[streamId] = sink to offset + bytes.size+        }+    }++    private fun onStreamClose(data: Bundle) {+        val streamId = data.getLong(ConduitProtocol.KEY_STREAM_ID)+        val verified = data.getBoolean(ConduitProtocol.KEY_VERIFIED)+        val sink = synchronized(inboundSinks) { inboundSinks.remove(streamId)?.first } ?: return+        runCatching { sink.close(verified) }+    }++    companion object {+        private const val TAG = "WearLinkClient"++        /** Map a conduit status string onto the shared link-state type. */+        fun mapStatus(state: String?, peerLabel: String?, reason: String?): WearLinkState =+            when (state) {+                ConduitProtocol.STATUS_CONNECTED -> WearLinkState.Connected(peerLabel ?: "")+                ConduitProtocol.STATUS_CONNECTING -> WearLinkState.Connecting(peerLabel ?: "")+                ConduitProtocol.STATUS_PERMISSION_MISSING -> WearLinkState.PermissionMissing+                ConduitProtocol.STATUS_BLUETOOTH_OFF -> WearLinkState.BluetoothOff+                ConduitProtocol.STATUS_NO_BONDED_PEER -> WearLinkState.NoBondedPeer+                ConduitProtocol.STATUS_NOT_INSTALLED -> WearLinkState.NotInstalled+                ConduitProtocol.STATUS_UNAVAILABLE -> WearLinkState.Unavailable+                ConduitProtocol.STATUS_STOPPED -> WearLinkState.Stopped+                else -> WearLinkState.Failed(reason ?: state ?: "unknown conduit status")+            }+    }+}
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.ktnew file mode 100644index 0000000000..0663a301a0--- /dev/null+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.library.wearlink.conduit++import com.vayunmathur.library.wearlink.StreamHeader+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class ConduitRouterTest {++    private class FakeDownstream : ConduitDownstream {+        val messages = mutableListOf<Pair<String, ByteArray>>()+        val data = mutableListOf<Pair<String, ByteArray>>()+        val statuses = mutableListOf<String>()+        val streamOpens = mutableListOf<Long>()+        var acceptStreams = true+        override fun deliverMessage(path: String, body: ByteArray) { messages.add(path to body) }+        override fun deliverData(path: String, body: ByteArray) { data.add(path to body) }+        override fun deliverStatus(state: String, peerLabel: String?, reason: String?) { statuses.add(state) }+        override fun deliverStreamOpen(streamId: Long, path: String, header: StreamHeader): Boolean {+            if (acceptStreams) streamOpens.add(streamId)+            return acceptStreams+        }+        override fun deliverStreamChunk(streamId: Long, body: ByteArray) {}+        override fun deliverStreamClose(streamId: Long, verified: Boolean) {}+    }++    private class FakeUpstream : ConduitUpstream {+        val messages = mutableListOf<Pair<String, ByteArray>>()+        val data = mutableListOf<Pair<String, ByteArray>>()+        var streams = 0+        override fun sendMessage(path: String, body: ByteArray, requireAck: Boolean): Boolean {+            messages.add(path to body); return true+        }+        override fun putData(path: String, body: ByteArray): Boolean { data.add(path to body); return true }+        override fun sendStream(path: String, header: StreamHeader, chunks: List<ByteArray>): Boolean {+            streams++; return true+        }+    }++    private fun bytes(text: String) = text.encodeToByteArray()++    @Test+    fun `route key is first path segment`() {+        assertEquals("clock", ConduitProtocol.routeKey("/clock/snapshot"))+        assertEquals("clock", ConduitProtocol.routeKey("clock/x"))+        assertEquals("", ConduitProtocol.routeKey("/"))+        assertTrue(ConduitProtocol.owns("clock", "/clock/a"))+        assertFalse(ConduitProtocol.owns("clock", "/notes/a"))+    }++    @Test+    fun `register replays cached data and queued messages then status`() {+        val upstream = FakeUpstream()+        val router = ConduitRouter(upstream = upstream)+        router.onPeerData("/clock/snapshot", bytes("snap"))+        router.onPeerData("/clock/snapshot", bytes("snap2"))+        router.onPeerData("/notes/snapshot", bytes("other"))+        router.onPeerMessage("/clock/op", bytes("op1"))+        router.setLinkStatus(ConduitProtocol.STATUS_CONNECTED, "watch", null)+        val fake = FakeDownstream()+        router.register("clock", fake)+        assertEquals(listOf("/clock/snapshot"), fake.data.map { it.first })+        assertEquals("snap2", fake.data.single().second.decodeToString())+        assertEquals(listOf("/clock/op"), fake.messages.map { it.first })+        assertEquals(ConduitProtocol.STATUS_CONNECTED, fake.statuses.last())+    }++    @Test+    fun `queued messages are bounded with oldest dropped`() {+        val router = ConduitRouter(maxQueuedPerApp = 2, upstream = FakeUpstream())+        router.onPeerMessage("/todo/a", bytes("1"))+        router.onPeerMessage("/todo/a", bytes("2"))+        router.onPeerMessage("/todo/a", bytes("3"))+        val fake = FakeDownstream()+        router.register("todo", fake)+        assertEquals(listOf("2", "3"), fake.messages.map { it.second.decodeToString() })+        assertEquals(1, router.countersSnapshot()["todo"]?.queuedDropped)+    }++    @Test+    fun `local traffic must be namespaced under the sender appId`() {+        val upstream = FakeUpstream()+        val router = ConduitRouter(upstream = upstream)+        val fake = FakeDownstream()+        router.register("clock", fake)+        assertTrue(router.onLocalMessage("clock", "/clock/op", bytes("x"), false))+        assertFalse(router.onLocalMessage("clock", "/notes/op", bytes("x"), false))+        assertFalse(router.onLocalData("clock", "/notes/snap", bytes("x")))+        assertEquals(1, upstream.messages.size)+        assertEquals(0, upstream.data.size)+    }++    @Test+    fun `peer data updates cache and status fans out to all clients`() {+        val router = ConduitRouter(upstream = FakeUpstream())+        val clock = FakeDownstream()+        val notes = FakeDownstream()+        router.register("clock", clock)+        router.register("notes", notes)+        router.onPeerData("/clock/snapshot", bytes("s"))+        assertEquals(1, clock.data.size)+        assertEquals(0, notes.data.size)+        router.setLinkStatus(ConduitProtocol.STATUS_FAILED, null, "gone")+        assertEquals(ConduitProtocol.STATUS_FAILED, clock.statuses.last())+        assertEquals(ConduitProtocol.STATUS_FAILED, notes.statuses.last())+        router.unregister("clock")+        assertFalse(router.isRegistered("clock"))+        assertEquals(setOf("notes"), router.registeredApps())+    }++    @Test+    fun `stream open is refused for unregistered app and routed when registered`() {+        val router = ConduitRouter(upstream = FakeUpstream())+        val header = StreamHeader(3, "abc")+        assertFalse(router.onPeerStreamOpen(7, "/camera/stream", header))+        val fake = FakeDownstream()+        router.register("camera", fake)+        assertTrue(router.onPeerStreamOpen(7, "/camera/stream", header))+        assertEquals(listOf(7L), fake.streamOpens)+        fake.acceptStreams = false+        assertFalse(router.onPeerStreamOpen(8, "/camera/stream", header))+    }+}