Modern Apps git

← Modern-Apps.git

auto: wire transport, framing and control session into a connection

Commit
7dbf5e7a79c7b4daa07cf2d60135099a409ce30e
Author
vayun-mathur <[email protected]>
When
2026-09-12 01:36 UTC (2 months ago)
Parents
eee67e1

Diff

auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.ktnew file mode 100644index 0000000000..2d5e843ad7--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt@@ -0,0 +1,85 @@+package com.vayunmathur.auto.protocol++import java.io.Closeable+import javax.net.ssl.SSLContext++/** A message on a service channel, handed to whatever owns that service. */+fun interface ChannelMessageHandler {+    fun onMessage(message: ChannelMessage)+}++/**+ * Ties a [GalTransport] to the control session.+ *+ * Owns the single [javax.net.ssl.SSLEngine] for the connection and therefore the read/write+ * loop: an engine is not thread-safe, so wrapping and unwrapping both happen on whichever+ * thread calls [pump]. Callers drive it rather than it spawning threads, which keeps the+ * whole thing testable over an in-memory transport.+ *+ * The [FrameFlags.ENCRYPTED] flag decides whether a frame goes through TLS, so the same+ * reader handles the plaintext version and handshake frames and the wrapped ones that+ * follow, with no mode switch.+ */+class GalConnection(+    private val transport: GalTransport,+    sslContext: SSLContext,+    deviceName: String,+    private val onChannelMessage: ChannelMessageHandler = ChannelMessageHandler { },+) : Closeable {++    private val engine = GalCredential.serverEngine(sslContext)+    private val tls = TlsCodec(engine)+    private val reader = FrameReader(decrypt = tls::unwrap)+    private val writer = FrameWriter(encrypt = tls::wrap)++    val session: GalControlSession = GalControlSession(engine, deviceName)++    private val buffer = ByteArray(READ_BUFFER_SIZE)++    /**+     * Reads once and handles whatever that produced.+     *+     * @return false at end of stream, when the head unit has gone away.+     */+    fun pump(): Boolean {+        val count = transport.read(buffer, 0, buffer.size)+        if (count < 0) return false++        for (message in reader.offer(buffer, 0, count)) {+            val decoded = MessageCodec.decode(message.channelId, message.payload)+            if (message.isControl) {+                session.onMessage(decoded.type, decoded.payload).forEach(::send)+            } else {+                onChannelMessage.onMessage(decoded)+            }+        }+        return true+    }++    /** Frames a control message and writes it. */+    fun send(message: OutboundMessage) {+        write(CONTROL_CHANNEL, MessageCodec.encode(message.type, message.payload),+            isControl = true, encrypted = message.encrypted)+    }++    /** Frames a service-channel message and writes it. Always encrypted. */+    fun send(channelId: Int, type: Int, payload: ByteArray) {+        write(channelId, MessageCodec.encode(type, payload), isControl = false, encrypted = true)+    }++    private fun write(channelId: Int, payload: ByteArray, isControl: Boolean, encrypted: Boolean) {+        for (frame in writer.frame(channelId, payload, isControl, encrypted)) {+            transport.write(frame, 0, frame.size)+        }+        transport.flush()+    }++    override fun close() = transport.close()++    private companion object {+        const val CONTROL_CHANNEL = 0++        /** Comfortably larger than one frame, so a read rarely splits one. */+        const val READ_BUFFER_SIZE = 32 * 1024+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.ktnew file mode 100644index 0000000000..ddd539dd55--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.kt@@ -0,0 +1,163 @@+package com.vayunmathur.auto.protocol++import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Drives a [GalConnection] over an in-memory transport, so the whole stack -- transport,+ * framing, message codec, session -- runs together with no device.+ */+class GalConnectionTest {++    /** Feeds queued bytes to the connection and captures everything it writes. */+    private class FakeTransport : GalTransport {+        private var inbound = ByteBuffer.allocate(0)+        val written = ByteArrayOutputStream()+        var closed = false+            private set++        fun queue(bytes: ByteArray) {+            val combined = ByteBuffer.allocate(inbound.remaining() + bytes.size)+            combined.put(inbound)+            combined.put(bytes)+            combined.flip()+            inbound = combined+        }++        override fun read(buffer: ByteArray, offset: Int, length: Int): Int {+            if (!inbound.hasRemaining()) return -1 // end of stream+            val count = minOf(length, inbound.remaining())+            inbound.get(buffer, offset, count)+            return count+        }++        override fun write(bytes: ByteArray, offset: Int, length: Int) {+            written.write(bytes, offset, length)+        }++        override fun flush() = Unit++        override fun close() {+            closed = true+        }+    }++    private fun connection(transport: FakeTransport) =+        GalConnection(transport, TestTls.context(), deviceName = "Pixel 8")++    /** A control frame as a head unit would put it on the wire: plaintext, channel 0. */+    private fun headUnitFrame(type: Int, payload: ByteArray): ByteArray =+        FrameWriter().frame(+            channelId = 0,+            payload = MessageCodec.encode(type, payload),+            isControl = true,+            encrypted = false,+        ).single()++    private fun versionRequest(major: Int, minor: Int) =+        ByteBuffer.allocate(4).putShort(major.toShort()).putShort(minor.toShort()).array()++    @Test+    fun `a version request in yields a version response out`() {+        val transport = FakeTransport()+        val connection = connection(transport)+        transport.queue(+            headUnitFrame(GalMessage.Control.VERSION_REQUEST, versionRequest(1, 6)),+        )++        assertTrue(connection.pump())++        // The full frame: 4-byte header, then type 2, major, minor, status. Flags are 0x07,+        // FIRST|LAST|CONTROL -- the control bit is what puts this on the control channel.+        assertContentEquals(+            byteArrayOf(+                0x00, 0x07, 0x00, 0x08, // channel 0, FIRST|LAST|CONTROL, 8-byte payload+                0x00, 0x02, //             VersionResponse+                0x00, 0x01, 0x00, 0x06, // 1.6+                0x00, 0x00, //             STATUS_SUCCESS+            ),+            transport.written.toByteArray(),+        )+        assertEquals(GalVersion(1, 6), connection.session.negotiatedVersion)+        assertEquals(SessionState.HANDSHAKING, connection.session.state)+    }++    @Test+    fun `pump reports end of stream when the head unit goes away`() {+        val transport = FakeTransport()+        val connection = connection(transport)++        assertFalse(connection.pump(), "no queued bytes should read as EOF")+    }++    @Test+    fun `a request split across two reads is still handled`() {+        val transport = FakeTransport()+        val connection = connection(transport)+        val frame = headUnitFrame(GalMessage.Control.VERSION_REQUEST, versionRequest(1, 7))++        // Deliver the header and the payload in separate reads.+        transport.queue(frame.copyOfRange(0, 5))+        assertTrue(connection.pump())+        assertEquals(0, transport.written.size(), "nothing to answer with yet")++        transport.queue(frame.copyOfRange(5, frame.size))+        assertTrue(connection.pump())+        assertTrue(transport.written.size() > 0, "the full request should have been answered")+        assertEquals(GalVersion(1, 7), connection.session.negotiatedVersion)+    }++    @Test+    fun `service channel messages go to the handler rather than the session`() {+        val transport = FakeTransport()+        val received = mutableListOf<ChannelMessage>()+        val connection = GalConnection(+            transport,+            TestTls.context(),+            deviceName = "Pixel 8",+        ) { received += it }++        // A plaintext service-channel frame. Real ones are encrypted, but the routing+        // decision is the control flag, which is what this is checking.+        transport.queue(+            FrameWriter().frame(+                channelId = GalService.VIDEO_SINK.id,+                payload = MessageCodec.encode(GalMessage.Video.FOCUS_INDICATION, byteArrayOf(1)),+                isControl = false,+                encrypted = false,+            ).single(),+        )++        assertTrue(connection.pump())++        val message = received.single()+        assertEquals(GalService.VIDEO_SINK.id, message.channelId)+        assertEquals(GalMessage.Video.FOCUS_INDICATION, message.type)+        assertEquals(0, transport.written.size(), "the session should not have answered")+    }++    @Test+    fun `closing the connection closes the transport`() {+        val transport = FakeTransport()+        connection(transport).close()+        assertTrue(transport.closed)+    }++    @Test+    fun `each connection gets its own TLS engine`() {+        // A shared engine across connections would corrupt both sessions.+        val a = connection(FakeTransport())+        val b = connection(FakeTransport())++        a.session.onMessage(GalMessage.Control.VERSION_REQUEST, versionRequest(1, 6))++        assertEquals(GalVersion(1, 6), a.session.negotiatedVersion)+        assertEquals(null, b.session.negotiatedVersion)+        assertEquals(SessionState.AWAITING_VERSION, b.session.state)+    }+}