From 3ed62b35df56cea1af842d82c51eec43508b732a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:12:33 +0000 Subject: [PATCH 1/2] Fix minor bridge issues: stray unhandled error, Android thread and engine leaks, HTTP/3 host case - Dart: a failure event that overtakes the open reply no longer also reports an unhandled error. - Android: the bridge thread catches Throwable, so an OutOfMemoryError fails its call instead of the app. - Android: detaching from the Flutter engine shuts the Cronet engines and the bridge thread down. - iOS: http3Origins match the request host case-insensitively. - Docs: Cronet's BidirectionalStream carries neither HTTP/1.1 nor http:// URLs. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01BqmpXVmhnobv11U2vaqWwX --- README.md | 3 +- .../ConnectNativeHttpPlugin.kt | 2 +- .../connect_native_http/CronetBridge.kt | 34 +++++++++++++++---- .../URLSessionBridge.swift | 5 +-- lib/src/channel/channel_http_client.dart | 6 +++- lib/src/native_http_config.dart | 4 +-- test/cronet_http_client_test.dart | 15 ++++++++ 7 files changed, 56 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index ac5a6d5..57eb01a 100644 --- a/README.md +++ b/README.md @@ -166,9 +166,10 @@ found or verified with the tests in this package. | Stack | URLSession, through the Swift plugin in `ios/` (Swift Package Manager only) | Cronet `BidirectionalStream`, through the Kotlin plugin in `android/` | | HTTP/3 | From the first request for `http3Origins`; otherwise learned from `Alt-Svc` | Same | | Certificates | System trust store | System trust store; QUIC only with certificates that chain to a public root | -| Negotiated protocol | Not exposed (`NativeHttpResponseInfo.protocol` is `null`) | `h2`, `quic/1+spdy/3` (HTTP/3) or `http/1.1` | +| Negotiated protocol | Not exposed (`NativeHttpResponseInfo.protocol` is `null`) | `h2` or `quic/1+spdy/3` (HTTP/3) | | QUIC idle timeout | No setting; the server's advertised value applies | `NativeHttpConfig.quicIdleTimeout`, in whole seconds | | Read-idle timeout | `NativeHttpConfig.readIdleTimeout`, through `URLRequest.timeoutInterval`. Without one, a task that receives nothing for a day fails | `NativeHttpConfig.readIdleTimeout`, through a timer in the bridge. None without one | +| HTTP/1.1 and `http://` | Left to URLSession; not tested | Not carried: Cronet's `BidirectionalStream` fails a call unless HTTP/2 or HTTP/3 is negotiated (`net::ERR_FAILED`), and takes only `https://` URLs (`net::ERR_DISALLOWED_URL_SCHEME`) | | Redirects | Followed only for requests without a body; otherwise the 3xx response is returned, since a streamed body can't be resent | Not tested | ### Dead connections diff --git a/android/src/main/kotlin/com/agtonomy/connect_native_http/ConnectNativeHttpPlugin.kt b/android/src/main/kotlin/com/agtonomy/connect_native_http/ConnectNativeHttpPlugin.kt index cd4c57f..6022b42 100644 --- a/android/src/main/kotlin/com/agtonomy/connect_native_http/ConnectNativeHttpPlugin.kt +++ b/android/src/main/kotlin/com/agtonomy/connect_native_http/ConnectNativeHttpPlugin.kt @@ -43,6 +43,6 @@ class ConnectNativeHttpPlugin : FlutterPlugin { override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { methods.setMethodCallHandler(null) events.setStreamHandler(null) - bridge.cancelAll() + bridge.close() } } diff --git a/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt b/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt index 8d60dc7..10fa8fa 100644 --- a/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt +++ b/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt @@ -14,6 +14,7 @@ import java.net.URI import java.net.URISyntaxException import java.nio.ByteBuffer import java.util.concurrent.Executors +import java.util.concurrent.RejectedExecutionException import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit @@ -38,6 +39,7 @@ class CronetBridge( private val engines = HashMap() private val calls = HashMap() private var nextEngineId = 1 + private var closed = false private class EngineOptions(val quicHints: List>, val quicIdleTimeoutSeconds: Int?) @@ -81,19 +83,38 @@ class CronetBridge( var reported = false } - fun cancelAll() { - execute(null) { - calls.values.forEach { it.stream.cancel() } + // Ends the bridge when its Flutter engine goes away: cancels the calls in flight and shuts every engine down. Cronet's + // final callbacks for those calls still run on the bridge's thread, so it stops once the last engine has shut down. + fun close() { + try { + execute(null) { + closed = true + calls.values.forEach { it.stream.cancel() } + engines.keys.toList().forEach { id -> + engines[id]?.shuttingDown = true + shutdownIfIdle(id) + } + stopIfDone() + } + } catch (e: RejectedExecutionException) { + // Already closed, and stopped. + } + } + + private fun stopIfDone() { + if (closed && engines.isEmpty()) { + executor.shutdown() } } // Runs [task] on the bridge's thread. An exception escaping it would end that thread, and with it the app: Android's // default handler for uncaught exceptions kills the process. So it is logged, and fails the call it concerns. + // Throwable, not Exception: allocating a buffer for a large chunk can throw OutOfMemoryError. private fun execute(callId: Int?, task: () -> Unit) { executor.execute { try { task() - } catch (e: Exception) { + } catch (e: Throwable) { Log.e(TAG, "call $callId failed in the bridge", e) if (callId != null) { abort(callId, e) @@ -249,7 +270,7 @@ class CronetBridge( val check = Runnable { try { checkReadIdle(c) - } catch (e: Exception) { + } catch (e: Throwable) { Log.e(TAG, "call ${c.callId} failed in the bridge", e) abort(c.callId, e) } @@ -308,7 +329,7 @@ class CronetBridge( } // Fails a call the bridge itself could not carry on with, after an exception on its thread. - private fun abort(callId: Int, e: Exception) { + private fun abort(callId: Int, e: Throwable) { val message = "connect_native_http bridge: $e" val c = calls[callId] if (c == null) { @@ -380,6 +401,7 @@ class CronetBridge( if (engine.shuttingDown && engine.current.callIds.isEmpty() && engine.retired.isEmpty()) { engines.remove(engineId) shutdown(engineId, engine.current) + stopIfDone() } } diff --git a/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift b/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift index d5fa580..f0d1772 100644 --- a/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift +++ b/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift @@ -96,7 +96,7 @@ public final class URLSessionBridge { case "createEngine": let origins = try (args["http3Origins"] as? [[Any]] ?? []).map { origin -> String in guard origin.count == 2 else { throw BadArgument(name: "http3Origins") } - return "\(origin[0]):\(origin[1])" + return "\(origin[0])".lowercased() + ":\(origin[1])" } queue.async { let id = self.nextSessionId @@ -213,7 +213,8 @@ public final class URLSessionBridge { request.addValue(h[1], forHTTPHeaderField: h[0]) } let port = target.port ?? (target.scheme == "http" ? 80 : 443) - let origin = "\(target.host ?? ""):\(port)" + // Lowercased, as Dart's Uri gives the hosts in http3Origins; URL keeps the case the caller wrote. + let origin = "\((target.host ?? "").lowercased()):\(port)" request.assumesHTTP3Capable = session.http3Origins.contains(origin) // The request's read-idle timeout: URLSession fails the task once it has received nothing for this long, with // NSURLErrorTimedOut. diff --git a/lib/src/channel/channel_http_client.dart b/lib/src/channel/channel_http_client.dart index ec6386a..5adff7d 100644 --- a/lib/src/channel/channel_http_client.dart +++ b/lib/src/channel/channel_http_client.dart @@ -49,7 +49,11 @@ Headers plainHeaders(List<(String, String)> pairs) { } final class _Call { - _Call(this.url); + _Call(this.url) { + // A failure event can arrive before the `open` reply, so before `_send` has handed this future to its caller. + // The caller still gets the error; this keeps it from also being reported as unhandled in the meantime. + response.future.ignore(); + } final Uri url; final response = Completer(); diff --git a/lib/src/native_http_config.dart b/lib/src/native_http_config.dart index c453e84..32fd8c5 100644 --- a/lib/src/native_http_config.dart +++ b/lib/src/native_http_config.dart @@ -4,8 +4,8 @@ final class NativeHttpResponseInfo { final Uri url; - /// The protocol the platform negotiated, as the platform names it: Cronet reports `h2`, `quic/1+spdy/3` (HTTP/3) - /// or `http/1.1`. `null` when the platform does not expose it, as with URLSession. + /// The protocol the platform negotiated, as the platform names it: Cronet reports `h2` or `quic/1+spdy/3` (HTTP/3). + /// `null` when the platform does not expose it, as with URLSession. final String? protocol; } diff --git a/test/cronet_http_client_test.dart b/test/cronet_http_client_test.dart index efd0539..78104a0 100644 --- a/test/cronet_http_client_test.dart +++ b/test/cronet_http_client_test.dart @@ -12,6 +12,7 @@ class FakePlugin { FakePlugin() { _messenger.setMockMethodCallHandler(cronetMethodChannel, (call) async { calls.add(call); + await beforeReply?.call(call); if (refusing.contains(call.method)) { throw PlatformException(code: 'badArguments', message: '${call.method} refused'); } @@ -22,6 +23,9 @@ class FakePlugin { final calls = []; + /// Runs before the plugin answers a method call, for events that overtake the reply. + Future Function(MethodCall call)? beforeReply; + /// Methods the plugin answers with an error. final refusing = {}; @@ -209,6 +213,17 @@ void main() { expect(cause.platformCode, -102); }); + test('a failure that overtakes the open reply fails the call, and is not reported as unhandled', () async { + plugin.beforeReply = (call) async { + if (call.method == 'open') { + await plugin.failed((call.arguments as Map)['callId'] as int, streamReady: false, internalErrorCode: -102); + await settle(); + } + }; + final cause = await failureCause(client.httpClient(request(null))); + expect(cause.failure, NativeHttpFailure.notSent); + }); + test('a certificate error is untrusted', () async { final response = client.httpClient(request(null)); await settle(); From 1a932807bb39c8ef843336670853224b6c45a701 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:22:46 +0000 Subject: [PATCH 2/2] Keep a GET from crashing the Android bridge; start call ids at a random value - Android: no write to a GET's or HEAD's request side. Cronet ends it with the headers, and the empty write that ends a request then hit a CHECK in Chromium's SpdyStream::SendData, which aborts the process. Connect GET (useHttpGet) took this path on every call. - Dart: call ids start at a random value, so after a hot restart a new call doesn't get the id of a call the plugin still carries, and with it that call's events. - Tests: a GET in the Android bridge tests and the Dart integration tests; the test server reports the request method in X-Method. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01BqmpXVmhnobv11U2vaqWwX --- .../connect_native_http/CronetBridgeTest.kt | 17 +++++++++++++- .../connect_native_http/CronetBridge.kt | 23 +++++++++++++++---- example/integration_test/eliza_test.dart | 18 +++++++++++++++ lib/src/channel/channel_http_client.dart | 6 ++++- test_server/main.go | 1 + 5 files changed, 58 insertions(+), 7 deletions(-) diff --git a/android/src/androidTest/kotlin/com/agtonomy/connect_native_http/CronetBridgeTest.kt b/android/src/androidTest/kotlin/com/agtonomy/connect_native_http/CronetBridgeTest.kt index 3abd162..0043e3b 100644 --- a/android/src/androidTest/kotlin/com/agtonomy/connect_native_http/CronetBridgeTest.kt +++ b/android/src/androidTest/kotlin/com/agtonomy/connect_native_http/CronetBridgeTest.kt @@ -91,6 +91,20 @@ class CronetBridgeTest { assertTrue(received(1).contains("say: hi")) } + @Test + fun aGetEndsWithoutAWriteToItsRequestSide() { + val engine = createEngine() + // Cronet ends a GET's request side with its headers. Ending it again, as Dart does for every call and the + // bridge does once the response is complete, would abort the process. + invoke("open", openArguments(engine, 1, SAY, "application/proto", method = "GET")) + invoke("write", mapOf("callId" to 1, "data" to sentence("ignored"))) + invoke("end", mapOf("callId" to 1)) + // Whatever the server makes of a GET without a message, it answers, and the call ends with that answer. + assertEquals("done", awaitOutcome(1)["type"]) + await(1, "headers") + assertSayWorks(engine, 2) + } + @Test fun aReadIdleTimeoutFailsAQuietCallAndTheEngineCarriesOn() { val engine = createEngine() @@ -204,11 +218,12 @@ class CronetBridgeTest { path: String, contentType: String, extraHeaders: List> = emptyList(), + method: String = "POST", ): Map = mapOf( "engineId" to engine, "callId" to callId, "url" to serverUrl + path, - "method" to "POST", + "method" to method, "headers" to listOf(listOf("content-type", contentType), listOf("connect-protocol-version", "1")) + extraHeaders, ) diff --git a/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt b/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt index 10fa8fa..b9150e7 100644 --- a/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt +++ b/android/src/main/kotlin/com/agtonomy/connect_native_http/CronetBridge.kt @@ -64,6 +64,10 @@ class CronetBridge( val pool: Pool, val origin: String, val readIdleTimeoutNanos: Long?, + // Whether the request has a body side to write to and end. Cronet ends a GET's or HEAD's with the headers, and + // a write after that, even the empty one that ends a request, aborts the process (a CHECK in Chromium's + // SpdyStream::SendData). + val writable: Boolean, ) { lateinit var stream: BidirectionalStream @@ -83,8 +87,9 @@ class CronetBridge( var reported = false } - // Ends the bridge when its Flutter engine goes away: cancels the calls in flight and shuts every engine down. Cronet's - // final callbacks for those calls still run on the bridge's thread, so it stops once the last engine has shut down. + // Ends the bridge when its Flutter engine goes away: cancels the calls in flight and shuts every engine down. + // Cronet's final callbacks for those calls still run on the bridge's thread, so it stops once the last engine has + // shut down. fun close() { try { execute(null) { @@ -234,7 +239,15 @@ class CronetBridge( return } val pool = engine.current - val c = Call(callId, engineId, pool, origin(url), readIdleTimeoutMs?.let { TimeUnit.MILLISECONDS.toNanos(it) }) + val c = Call( + callId, + engineId, + pool, + origin(url), + readIdleTimeoutMs?.let { TimeUnit.MILLISECONDS.toNanos(it) }, + // The methods Cronet itself takes to have no body (CronetBidirectionalStream.doesMethodAllowWriteData). + writable = method != "GET" && method != "HEAD", + ) val builder = pool.cronet.newBidirectionalStreamBuilder(url, Callback(c), executor).setHttpMethod(method) for ((name, value) in headers) { builder.addHeader(name, value) @@ -350,8 +363,8 @@ class CronetBridge( private fun enqueue(c: Call, data: ByteArray, endOfStream: Boolean) { // Cronet rejects writes after the end of the request, which the bridge may already have sent itself, and an - // empty write before it, which has nothing to send anyway. - if (c.endQueued || c.reported || (data.isEmpty() && !endOfStream)) { + // empty write before it, which has nothing to send anyway. A GET or HEAD has no request side to write to. + if (!c.writable || c.endQueued || c.reported || (data.isEmpty() && !endOfStream)) { return } c.endQueued = endOfStream diff --git a/example/integration_test/eliza_test.dart b/example/integration_test/eliza_test.dart index aad77a7..b446fef 100644 --- a/example/integration_test/eliza_test.dart +++ b/example/integration_test/eliza_test.dart @@ -44,6 +44,7 @@ final class Harness { Duration? readIdleTimeout, Duration? deadlineStep, bool evictOnDeadline = false, + bool useHttpGet = false, }) async { late final Harness harness; final native = await NativeHttpClient.create( @@ -62,6 +63,7 @@ final class Harness { baseUrl: baseUrl, codec: const ProtoCodec(), httpClient: native.httpClient, + useHttpGet: useHttpGet, ); return harness = Harness._(native, ElizaServiceClient(transport)); } @@ -231,6 +233,22 @@ void main() { expect(harness.serverProtocols.single, startsWith('HTTP/')); }); + testCase('unary call over GET', (_) async { + // A request without a body. On Android, Cronet ends a GET's request side itself, and a write to it would abort + // the process. + final get = await Harness.create(serverUrl, http3Origins: {Uri.parse(serverUrl)}, useHttpGet: true); + addTearDown(get.native.close); + String? method; + final res = await get.eliza.say( + SayRequest(sentence: 'hi'), + onHeader: (headers) => method = headers.get('x-method')?.firstOrNull, + ); + expect(res.sentence, 'say: hi'); + expect(method, 'GET'); + // The client carries on. + expect((await get.eliza.say(SayRequest(sentence: 'again'))).sentence, 'say: again'); + }); + testCase('unary error code comes through', (_) async { await expectLater( harness.eliza.say(SayRequest(sentence: 'error:failed_precondition')), diff --git a/lib/src/channel/channel_http_client.dart b/lib/src/channel/channel_http_client.dart index 5adff7d..d3a3844 100644 --- a/lib/src/channel/channel_http_client.dart +++ b/lib/src/channel/channel_http_client.dart @@ -125,7 +125,11 @@ final class _Dispatcher { final PlatformBridge bridge; final calls = {}; final _onResponse = {}; - int _nextCallId = 1; + + /// Starts at a random id rather than 1. A hot restart starts Dart afresh while the plugin's calls live on, and + /// would otherwise hand a new call the id of an old one, whose events it would then receive. Under 2^30, so ids stay + /// within the 32 bits the plugins read them as. + int _nextCallId = 1 + math.Random().nextInt(1 << 30); int register(_Call call, void Function(NativeHttpResponseInfo)? onResponse) { final id = _nextCallId++; diff --git a/test_server/main.go b/test_server/main.go index 8bb0b16..d23a3fe 100644 --- a/test_server/main.go +++ b/test_server/main.go @@ -154,6 +154,7 @@ func protocolHeaders(next http.Handler, altSvc string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s %s %s from %s", r.Proto, r.Method, r.URL.Path, r.RemoteAddr) w.Header().Set("X-Proto", r.Proto) + w.Header().Set("X-Method", r.Method) w.Header().Set("X-Remote-Addr", r.RemoteAddr) if r.ProtoMajor < 3 && altSvc != "" { w.Header().Set("Alt-Svc", altSvc)