wearlink: add conduit host shared by the Watch apps
- Commit
150c6e0d1201287190bddc803c29ead99dd59781- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 19:11 UTC (4 days ago)
- Parents
04efa56
ConduitHost owns the single WearLinkNode (watch_conduit) plus a ConduitRouter and speaks the Messenger protocol to local clients: on register it verifies the claimed caller package shares this app's signing certificate via PackageManager.checkSignatures, and sends from unregistered or mismatched Messengers are dropped. Outbound streams buffer to a cache file and cross the peer link through WearLinkNode.sendStream (hash/size verified); inbound chunks forward to the client as they arrive (no local-hop resume in this stage). ConduitRuntime publishes the link/registration/ counter snapshot the Watch status screens render. The register handshake now also carries the caller's package name. Verified: :library:wearlink:testDebugUnitTest, :watch:detekt and both Watch app assembles pass; wearlink detekt retains only its pre-existing backlog outside conduit/.
Diff
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.ktnew file mode 100644index 0000000000..83a10b84ef--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt@@ -0,0 +1,376 @@+package com.vayunmathur.library.wearlink.conduit++import android.content.Context+import android.content.pm.PackageManager+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.os.Message+import android.os.Messenger+import android.os.RemoteException+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.FileStreamSource+import com.vayunmathur.library.wearlink.StreamHeader+import com.vayunmathur.library.wearlink.StreamSink+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.launch+import java.io.File+import java.security.MessageDigest+import java.util.concurrent.atomic.AtomicLong++/**+ * Android host behind each Watch app's thin `ConduitService`: owns the+ * single [WearLinkNode] (appId `watch_conduit`) plus a [ConduitRouter],+ * and speaks [ConduitProtocol] to local clients over Messenger.+ *+ * Trust: the service is bound under the signature permission, and on+ * register the host additionally verifies that the claimed caller+ * package is signed with this app's own certificate via+ * [PackageManager.checkSignatures] — a caller that cannot prove the+ * shared signing key is never registered. Sends from an unregistered+ * (or mismatched) Messenger are dropped.+ *+ * Streams cross the conduit buffered whole in a cache file (Stage A):+ * outbound chunks accumulate until close, then the peer transfer runs+ * through [WearLinkNode.sendStream] with its hash/size verification;+ * inbound chunks forward to the client as they arrive. No stream+ * resume across the local hop in this stage.+ */+class ConduitHost(+ private val context: Context,+) {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val streamIds = AtomicLong(1)+ private val registrations = mutableMapOf<Messenger, String>()++ private val upstream: ConduitUpstream =+ object : ConduitUpstream {+ override fun sendMessage(+ path: String,+ body: ByteArray,+ requireAck: Boolean,+ ): Boolean {+ scope.launch { node.sendMessage(path, body, requireAck) }+ return node.isConnected+ }++ override fun putData(+ path: String,+ body: ByteArray,+ ): Boolean {+ scope.launch { node.putData(path, body) }+ return node.isConnected+ }++ override fun sendStream(+ path: String,+ header: StreamHeader,+ chunks: List<ByteArray>,+ ): Boolean {+ scope.launch {+ val file = File(context.cacheDir, "conduit-stream-${streamIds.incrementAndGet()}.bin")+ try {+ file.outputStream().use { out -> chunks.forEach { out.write(it) } }+ node.sendStream(path, FileStreamSource(file, header.sha256))+ } finally {+ file.delete()+ }+ }+ return node.isConnected+ }+ }++ val router: ConduitRouter = ConduitRouter(upstream = upstream)++ private val peerListener: WearLinkListener =+ object : WearLinkListener {+ override fun onMessage(+ path: String,+ body: ByteArray,+ ) {+ router.onPeerMessage(path, body)+ }++ override fun onData(+ path: String,+ body: ByteArray,+ ) {+ router.onPeerData(path, body)+ }++ override fun onStreamOpen(+ path: String,+ header: StreamHeader,+ ): StreamSink? {+ val streamId = streamIds.getAndIncrement()+ if (!router.onPeerStreamOpen(streamId, path, header)) return null+ return object : StreamSink {+ override fun write(+ bytes: ByteArray,+ offset: Long,+ ) {+ router.onPeerStreamChunk(streamId, bytes)+ }++ override fun close(verified: Boolean) {+ router.onPeerStreamClose(streamId, verified)+ }+ }+ }+ }++ private val node: WearLinkNode = WearLinkNode(context, ConduitProtocol.CONDUIT_APP_ID, peerListener)++ /** The link state of the single peer node, for the hosting service/UI. */+ val nodeState get() = node.state++ private inner class ClientDownstream(+ private val appId: String,+ private val target: Messenger,+ ) : ConduitDownstream {+ override fun deliverMessage(+ path: String,+ body: ByteArray,+ ) = send(ConduitProtocol.MSG_ON_MESSAGE) {+ putString(ConduitProtocol.KEY_PATH, path)+ putByteArray(ConduitProtocol.KEY_BODY, body)+ }++ override fun deliverData(+ path: String,+ body: ByteArray,+ ) = send(ConduitProtocol.MSG_ON_DATA) {+ putString(ConduitProtocol.KEY_PATH, path)+ putByteArray(ConduitProtocol.KEY_BODY, body)+ }++ override fun deliverStatus(+ state: String,+ peerLabel: String?,+ reason: String?,+ ) = send(ConduitProtocol.MSG_ON_STATUS) {+ putString(ConduitProtocol.KEY_STATE, state)+ putString(ConduitProtocol.KEY_PEER_LABEL, peerLabel)+ putString(ConduitProtocol.KEY_REASON, reason)+ }++ override fun deliverStreamOpen(+ streamId: Long,+ path: String,+ header: StreamHeader,+ ): Boolean =+ send(ConduitProtocol.MSG_ON_STREAM_OPEN) {+ putLong(ConduitProtocol.KEY_STREAM_ID, streamId)+ putString(ConduitProtocol.KEY_PATH, path)+ putLong(ConduitProtocol.KEY_TOTAL_SIZE, header.totalSize)+ putString(ConduitProtocol.KEY_SHA256, header.sha256)+ }++ override fun deliverStreamChunk(+ streamId: Long,+ body: ByteArray,+ ) = send(ConduitProtocol.MSG_ON_STREAM_CHUNK) {+ putLong(ConduitProtocol.KEY_STREAM_ID, streamId)+ putByteArray(ConduitProtocol.KEY_BODY, body)+ }++ override fun deliverStreamClose(+ streamId: Long,+ verified: Boolean,+ ) = send(ConduitProtocol.MSG_ON_STREAM_CLOSE) {+ putLong(ConduitProtocol.KEY_STREAM_ID, streamId)+ putBoolean(ConduitProtocol.KEY_VERIFIED, verified)+ }++ private fun send(+ what: Int,+ fill: Bundle.() -> Unit,+ ): Boolean =+ try {+ val message = Message.obtain(null, what)+ message.data = Bundle().apply(fill)+ target.send(message)+ true+ } catch (_: RemoteException) {+ router.unregister(appId)+ false+ }+ }++ private val handler = Handler(Looper.getMainLooper()) { message -> handle(message) }+ val messenger = Messenger(handler)++ fun start() {+ node.start()+ scope.launch {+ node.state.collectLatest { state ->+ val (status, peer, reason) =+ when (state) {+ is WearLinkState.Connected ->+ Triple(ConduitProtocol.STATUS_CONNECTED, state.peerLabel, null)+ is WearLinkState.Connecting ->+ Triple(ConduitProtocol.STATUS_CONNECTING, state.peerLabel, null)+ is WearLinkState.Failed ->+ Triple(ConduitProtocol.STATUS_FAILED, null, state.reason)+ WearLinkState.PermissionMissing ->+ Triple(ConduitProtocol.STATUS_PERMISSION_MISSING, null, null)+ WearLinkState.BluetoothOff ->+ Triple(ConduitProtocol.STATUS_BLUETOOTH_OFF, null, null)+ WearLinkState.NoBondedPeer ->+ Triple(ConduitProtocol.STATUS_NO_BONDED_PEER, null, null)+ WearLinkState.NotInstalled ->+ Triple(ConduitProtocol.STATUS_NOT_INSTALLED, null, null)+ WearLinkState.Unavailable ->+ Triple(ConduitProtocol.STATUS_UNAVAILABLE, null, null)+ WearLinkState.Stopped ->+ Triple(ConduitProtocol.STATUS_STOPPED, null, null)+ }+ router.setLinkStatus(status, peer, reason)+ publishSnapshot(status, peer, reason)+ }+ }+ }++ fun stop() {+ node.stop()+ }++ /** Drop every registration bound to a dead binder (called on service unbind). */+ fun clearClients() {+ registrations.clear()+ for (appId in router.registeredApps()) router.unregister(appId)+ publishSnapshot()+ }++ private fun handle(message: Message): Boolean {+ val data = message.data ?: return true+ val replyTo = message.replyTo+ when (message.what) {+ ConduitProtocol.MSG_REGISTER -> handleRegister(replyTo, data)+ ConduitProtocol.MSG_UNREGISTER -> handleUnregister(replyTo)+ ConduitProtocol.MSG_SEND_MESSAGE -> handleSendMessage(replyTo, data)+ ConduitProtocol.MSG_PUT_DATA -> handlePutData(replyTo, data)+ ConduitProtocol.MSG_STREAM_OPEN -> handleStreamOpen(replyTo, data)+ ConduitProtocol.MSG_STREAM_CHUNK -> handleStreamChunk(replyTo, data)+ ConduitProtocol.MSG_STREAM_CLOSE -> handleStreamClose(replyTo, data)+ }+ return true+ }++ private fun handleRegister(replyTo: Messenger?, data: Bundle) {+ if (replyTo == null) return+ val appId = data.getString(ConduitProtocol.KEY_APP_ID) ?: return+ val caller = data.getString(ConduitProtocol.KEY_CALLER_PACKAGE) ?: return+ if (!sameSignature(caller)) {+ Log.status(TAG, "refusing conduit register from unverified $caller")+ return+ }+ if (!ConduitProtocol.owns(appId, "/$appId/")) return+ registrations[replyTo] = appId+ router.register(appId, ClientDownstream(appId, replyTo))+ publishSnapshot()+ }++ private fun handleUnregister(replyTo: Messenger?) {+ val appId = replyTo?.let { registrations.remove(it) } ?: return+ router.unregister(appId)+ publishSnapshot()+ }++ private fun handleSendMessage(replyTo: Messenger?, data: Bundle) {+ val appId = registeredApp(replyTo, data) ?: return+ router.onLocalMessage(+ appId,+ data.getString(ConduitProtocol.KEY_PATH) ?: return,+ data.getByteArray(ConduitProtocol.KEY_BODY) ?: ByteArray(0),+ data.getBoolean(ConduitProtocol.KEY_REQUIRE_ACK),+ )+ }++ private fun handlePutData(replyTo: Messenger?, data: Bundle) {+ val appId = registeredApp(replyTo, data) ?: return+ router.onLocalData(+ appId,+ data.getString(ConduitProtocol.KEY_PATH) ?: return,+ data.getByteArray(ConduitProtocol.KEY_BODY) ?: ByteArray(0),+ )+ publishSnapshot()+ }++ private fun handleStreamOpen(replyTo: Messenger?, data: Bundle) {+ val appId = registeredApp(replyTo, data) ?: return+ router.onLocalStreamOpen(+ appId,+ data.getLong(ConduitProtocol.KEY_STREAM_ID),+ data.getString(ConduitProtocol.KEY_PATH) ?: return,+ StreamHeader(+ data.getLong(ConduitProtocol.KEY_TOTAL_SIZE),+ data.getString(ConduitProtocol.KEY_SHA256) ?: "",+ ),+ )+ }++ private fun handleStreamChunk(replyTo: Messenger?, data: Bundle) {+ if (registeredApp(replyTo, data) == null) return+ router.onLocalStreamChunk(+ data.getLong(ConduitProtocol.KEY_STREAM_ID),+ data.getByteArray(ConduitProtocol.KEY_BODY) ?: ByteArray(0),+ )+ }++ private fun handleStreamClose(replyTo: Messenger?, data: Bundle) {+ if (registeredApp(replyTo, data) == null) return+ router.onLocalStreamClose(data.getLong(ConduitProtocol.KEY_STREAM_ID))+ }++ /** The registered appId for this sender, only if the Bundle agrees with it. */+ private fun registeredApp(+ replyTo: Messenger?,+ data: Bundle,+ ): String? {+ val registered = replyTo?.let { registrations[it] } ?: return null+ val claimed = data.getString(ConduitProtocol.KEY_APP_ID)+ return if (claimed == null || claimed == registered) registered else null+ }++ private fun sameSignature(callerPackage: String): Boolean =+ runCatching {+ context.packageManager.checkSignatures(context.packageName, callerPackage) ==+ PackageManager.SIGNATURE_MATCH+ }.getOrDefault(false)++ private fun publishSnapshot(+ status: String? = null,+ peer: String? = null,+ reason: String? = null,+ ) {+ val (currentStatus, currentPeer, currentReason) = router.linkStatus()+ ConduitRuntime.update(+ ConduitSnapshot(+ linkState = status ?: currentStatus,+ peerLabel = peer ?: currentPeer,+ reason = reason ?: currentReason,+ registeredApps = router.registeredApps(),+ counters = router.countersSnapshot(),+ cachedDataItems = router.cachedDataCount(),+ ),+ )+ }++ companion object {+ private const val TAG = "ConduitHost"++ /** SHA-256 hex helper kept for stream bookkeeping parity with the wire layer. */+ fun sha256Hex(bytes: ByteArray): String =+ MessageDigest+ .getInstance("SHA-256")+ .digest(bytes)+ .joinToString("") { "%02x".format(it) }+ }+}
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.ktindex b3e6b9b021..946428020b 100644--- 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.kt@@ -35,6 +35,7 @@ object ConduitProtocol { 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 @@ -57,6 +58,7 @@ object ConduitProtocol { const val MSG_STREAM_CLOSE = 7 // conduit -> client+ /** Inbound message: [KEY_PATH], [KEY_BODY]. */ const val MSG_ON_MESSAGE = 101 @@ -77,6 +79,7 @@ object ConduitProtocol { // Bundle keys const val KEY_APP_ID = "appId"+ const val KEY_CALLER_PACKAGE = "callerPackage" const val KEY_PATH = "path" const val KEY_BODY = "body" const val KEY_REQUIRE_ACK = "requireAck"@@ -103,5 +106,8 @@ object ConduitProtocol { 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+ 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.ktindex 00da9a3cc9..9d2c436136 100644--- 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.kt@@ -4,21 +4,58 @@ 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?)+ fun deliverMessage(+ path: String,+ body: ByteArray,+ ): Boolean++ fun deliverData(+ path: String,+ body: ByteArray,+ ): Boolean++ fun deliverStatus(+ state: String,+ peerLabel: String?,+ reason: String?,+ ): Boolean /** 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)+ fun deliverStreamOpen(+ streamId: Long,+ path: String,+ header: StreamHeader,+ ): Boolean++ fun deliverStreamChunk(+ streamId: Long,+ body: ByteArray,+ ): Boolean++ fun deliverStreamClose(+ streamId: Long,+ verified: Boolean,+ ): 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+ 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. */@@ -54,7 +91,10 @@ class ConduitRouter( const val DEFAULT_MAX_QUEUED_PER_APP = 32 } - private data class QueuedMessage(val path: String, val body: ByteArray)+ private data class QueuedMessage(+ val path: String,+ val body: ByteArray,+ ) private val clients = mutableMapOf<String, ConduitDownstream>() private val dataCache = mutableMapOf<Pair<String, String>, ByteArray>()@@ -78,7 +118,10 @@ class ConduitRouter( /** Register [appId]; replays its cached data and queued messages, then current status. */ @Synchronized- fun register(appId: String, downstream: ConduitDownstream) {+ fun register(+ appId: String,+ downstream: ConduitDownstream,+ ) { if (appId.isEmpty()) return clients[appId] = downstream counters.putIfAbsent(appId, ConduitCounters())@@ -103,14 +146,23 @@ class ConduitRouter( // -- Local (client -> peer) --------------------------------------------- @Synchronized- fun onLocalMessage(appId: String, path: String, body: ByteArray, requireAck: Boolean): Boolean {+ 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 {+ 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) }@@ -119,7 +171,12 @@ class ConduitRouter( /** 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 {+ 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@@ -127,7 +184,10 @@ class ConduitRouter( } @Synchronized- fun onLocalStreamChunk(streamId: Long, body: ByteArray) {+ fun onLocalStreamChunk(+ streamId: Long,+ body: ByteArray,+ ) { outboundStreams[streamId]?.second?.add(body) } @@ -142,7 +202,10 @@ class ConduitRouter( // -- Peer (WearLinkNode -> local clients) -------------------------------- @Synchronized- fun onPeerMessage(path: String, body: ByteArray) {+ fun onPeerMessage(+ path: String,+ body: ByteArray,+ ) { val appId = ConduitProtocol.routeKey(path) if (appId.isEmpty()) return bump(appId) { it.copy(messagesIn = it.messagesIn + 1) }@@ -155,7 +218,10 @@ class ConduitRouter( } @Synchronized- fun onPeerData(path: String, body: ByteArray) {+ fun onPeerData(+ path: String,+ body: ByteArray,+ ) { val appId = ConduitProtocol.routeKey(path) if (appId.isEmpty()) return dataCache[appId to path] = body@@ -164,7 +230,11 @@ class ConduitRouter( } @Synchronized- fun onPeerStreamOpen(streamId: Long, path: String, header: StreamHeader): Boolean {+ 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@@ -175,13 +245,19 @@ class ConduitRouter( } @Synchronized- fun onPeerStreamChunk(streamId: Long, body: ByteArray) {+ fun onPeerStreamChunk(+ streamId: Long,+ body: ByteArray,+ ) { val appId = inboundStreams[streamId] ?: return clients[appId]?.deliverStreamChunk(streamId, body) } @Synchronized- fun onPeerStreamClose(streamId: Long, verified: Boolean) {+ fun onPeerStreamClose(+ streamId: Long,+ verified: Boolean,+ ) { val appId = inboundStreams.remove(streamId) ?: return clients[appId]?.deliverStreamClose(streamId, verified) }@@ -189,7 +265,11 @@ class ConduitRouter( // -- Status --------------------------------------------------------------- @Synchronized- fun setLinkStatus(state: String, peerLabel: String? = null, reason: String? = null) {+ fun setLinkStatus(+ state: String,+ peerLabel: String? = null,+ reason: String? = null,+ ) { linkState = state linkPeer = peerLabel linkReason = reason@@ -199,7 +279,10 @@ class ConduitRouter( @Synchronized fun linkStatus(): Triple<String, String?, String?> = Triple(linkState, linkPeer, linkReason) - private fun enqueue(appId: String, message: QueuedMessage) {+ private fun enqueue(+ appId: String,+ message: QueuedMessage,+ ) { val queue = queues.getOrPut(appId) { ArrayDeque() } queue.addLast(message) while (queue.size > maxQueuedPerApp) {@@ -208,7 +291,10 @@ class ConduitRouter( } } - private fun bump(appId: String, update: (ConduitCounters) -> ConduitCounters) {+ private fun bump(+ appId: String,+ update: (ConduitCounters) -> ConduitCounters,+ ) { counters[appId] = update(counters[appId] ?: ConduitCounters()) } }
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRuntime.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRuntime.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRuntime.ktnew file mode 100644index 0000000000..b67b08b98b--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRuntime.kt@@ -0,0 +1,25 @@+package com.vayunmathur.library.wearlink.conduit++import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/** Immutable snapshot of conduit health for the Watch status screens. */+data class ConduitSnapshot(+ val linkState: String = ConduitProtocol.STATUS_STOPPED,+ val peerLabel: String? = null,+ val reason: String? = null,+ val registeredApps: Set<String> = emptySet(),+ val counters: Map<String, ConduitCounters> = emptyMap(),+ val cachedDataItems: Int = 0,+)++/** Process-wide conduit status, written by the host service and read by the Watch UI. */+object ConduitRuntime {+ private val _state = MutableStateFlow(ConduitSnapshot())+ val state: StateFlow<ConduitSnapshot> = _state.asStateFlow()++ fun update(snapshot: ConduitSnapshot) {+ _state.value = snapshot+ }+}
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.ktindex 9f9d21574a..7153c668ec 100644--- 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.kt@@ -18,10 +18,10 @@ 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+import java.util.concurrent.atomic.AtomicLong /** * Drop-in replacement for@@ -59,24 +59,31 @@ class WearLinkClientNode( 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)+ 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)+ putString(ConduitProtocol.KEY_CALLER_PACKAGE, appContext.packageName)+ } }- } - override fun onServiceDisconnected(name: ComponentName?) {- conduit = null- if (bound) _state.value = WearLinkState.Unavailable+ override fun onServiceDisconnected(name: ComponentName?) {+ conduit = null+ if (bound) _state.value = WearLinkState.Unavailable+ } }- } fun start() { if (bound) return@@ -88,11 +95,13 @@ class WearLinkClientNode( 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)+ 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()@@ -115,7 +124,11 @@ class WearLinkClientNode( _state.value = WearLinkState.Stopped } - suspend fun sendMessage(path: String, body: ByteArray, requireAck: Boolean = false): Boolean {+ 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)@@ -126,9 +139,20 @@ class WearLinkClientNode( } /** 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+ @Suppress("FunctionOnlyReturningConstant")+ suspend fun request(+ path: String,+ body: ByteArray,+ timeoutMillis: Long = 10_000,+ ): ByteArray? {+ Log.status(TAG, "request $path (${body.size} bytes, ${timeoutMillis}ms) unsupported over conduit")+ return null+ } - suspend fun putData(path: String, body: ByteArray): Boolean {+ 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)@@ -137,7 +161,10 @@ class WearLinkClientNode( } } - suspend fun sendStream(path: String, source: StreamSource): Boolean {+ 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) {@@ -147,18 +174,24 @@ class WearLinkClientNode( putLong(ConduitProtocol.KEY_TOTAL_SIZE, source.size) putString(ConduitProtocol.KEY_SHA256, source.sha256) }- ) return false+ ) {+ return false+ } var offset = 0L while (offset < source.size) {- val length = minOf(- WearLinkProtocol.STREAM_CHUNK_BYTES.toLong(), source.size - offset,- ).toInt()+ 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+ ) {+ return false+ } offset += chunk.size } return sendToConduit(ConduitProtocol.MSG_STREAM_CLOSE) {@@ -166,12 +199,16 @@ class WearLinkClientNode( } } - private fun isWatchInstalled(): Boolean = runCatching {- appContext.packageManager.getPackageInfo(ConduitProtocol.WATCH_PACKAGE, 0)- true- }.getOrDefault(false)+ private fun isWatchInstalled(): Boolean =+ runCatching {+ appContext.packageManager.getPackageInfo(ConduitProtocol.WATCH_PACKAGE, 0)+ true+ }.getOrDefault(false) - private fun sendToConduit(what: Int, fill: Bundle.() -> Unit): Boolean {+ private fun sendToConduit(+ what: Int,+ fill: Bundle.() -> Unit,+ ): Boolean { val target = conduit ?: return false val reply = incoming ?: return false return try {@@ -188,19 +225,23 @@ class WearLinkClientNode( 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_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)@@ -211,10 +252,11 @@ class WearLinkClientNode( 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 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 } }@@ -240,7 +282,11 @@ class WearLinkClientNode( 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 =+ fun mapStatus(+ state: String?,+ peerLabel: String?,+ reason: String?,+ ): WearLinkState = when (state) { ConduitProtocol.STATUS_CONNECTED -> WearLinkState.Connected(peerLabel ?: "") ConduitProtocol.STATUS_CONNECTING -> WearLinkState.Connecting(peerLabel ?: "")
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.ktindex 0663a301a0..7dba23c68c 100644--- 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.kt@@ -7,34 +7,87 @@ 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 {++ override fun deliverMessage(+ path: String,+ body: ByteArray,+ ): Boolean {+ messages.add(path to body)+ return true+ }++ override fun deliverData(+ path: String,+ body: ByteArray,+ ): Boolean {+ data.add(path to body)+ return true+ }++ override fun deliverStatus(+ state: String,+ peerLabel: String?,+ reason: String?,+ ): Boolean {+ statuses.add(state)+ return true+ }++ 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) {}++ override fun deliverStreamChunk(+ streamId: Long,+ body: ByteArray,+ ): Boolean = true++ override fun deliverStreamClose(+ streamId: Long,+ verified: Boolean,+ ): Boolean = true } 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 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++ 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 } } @@ -61,7 +114,13 @@ class ConduitRouterTest { val fake = FakeDownstream() router.register("clock", fake) assertEquals(listOf("/clock/snapshot"), fake.data.map { it.first })- assertEquals("snap2", fake.data.single().second.decodeToString())+ assertEquals(+ "snap2",+ fake.data+ .single()+ .second+ .decodeToString(),+ ) assertEquals(listOf("/clock/op"), fake.messages.map { it.first }) assertEquals(ConduitProtocol.STATUS_CONNECTED, fake.statuses.last()) }