diff --git a/README.md b/README.md index 9167620..868b660 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,19 @@ whether the request provably never left the device (`requestNeverSent`), which m | `untrusted` | -1201 to -1204, certificate rejected | `net::` certificate errors -200 to -299, or a pin mismatch (-150) | | `other` | Everything else, timeouts and dropped connections included | Any failure after `onStreamReady` | +No exception in the package should crash the app or leave a call hanging. Failures end the one call they concern: + +- **A request the platform stack rejects** fails that call as `notSent`. For example, Cronet throws on a header value + with a line break. +- **A method call the plugin can't parse** gets an error reply instead of a force-unwrap (iOS) or an uncaught + exception (Android). Uncaught exceptions on the Android bridge's thread would otherwise kill the process. +- **A malformed event** fails its own call with `internal`. +- **An exception from `onResponse`** goes to `FlutterError.onError`, like other errors that have no caller. The call + carries on. + +`NativeHttpClient.create` throws a `PlatformException` if the platform can't create a client, for example when Cronet's +native library fails to load. + ## Server and infrastructure requirements The clients only reach HTTP/3, and only keep bidi working, if the server side meets these requirements. Each was @@ -227,7 +240,8 @@ Neither platform finishes a stream on its own while the client still has its req - **Android (`android/src/androidTest`, instrumented):** writes sent before Cronet is ready go out once it is; a write after the server finished the call is dropped instead of crashing; shutting an engine down lets its calls - finish and refuses new ones. + finish and refuses new ones; a header Cronet rejects fails its call as never sent; an empty write is skipped. + - Both platforms' suites also check that malformed method calls get an error reply and leave the bridge working. - **`example/integration_test/public_server_test.dart`:** HTTP/3 on Android against a server with a public certificate. It also checks that `quicIdleTimeout` ends a quiet connection, against a control without it. It is opt-in because it needs the internet: 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 8aba6e4..af1789b 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 @@ -68,24 +68,85 @@ class CronetBridgeTest { assertEquals(false, refused["streamReady"]) } - private fun invoke(method: String, arguments: Map): Any? { + // Cronet throws from start() on a header it rejects. On the bridge's thread that would have killed the app. + @Test + fun aHeaderCronetRejectsFailsTheCallAsNeverSent() { + val engine = createEngine() + open(engine, 1, SAY, "application/proto", extraHeaders = listOf(listOf("authorization", "Bearer x\r\ny"))) + val outcome = awaitOutcome(1) + assertEquals("failed", outcome["type"]) + assertEquals(false, outcome["streamReady"]) + assertSayWorks(engine, 2) + } + + // Cronet throws on an empty write before the end of the stream. + @Test + fun anEmptyWriteIsSkipped() { + val engine = createEngine() + open(engine, 1, SAY, "application/proto") + invoke("write", mapOf("callId" to 1, "data" to ByteArray(0))) + invoke("write", mapOf("callId" to 1, "data" to sentence("hi"))) + invoke("end", mapOf("callId" to 1)) + assertEquals("done", awaitOutcome(1)["type"]) + assertTrue(received(1).contains("say: hi")) + } + + @Test + fun malformedArgumentsAreRefusedInsteadOfCrashing() { + val engine = createEngine() + val malformed: List>> = listOf( + "open" to emptyMap(), + "open" to mapOf("engineId" to "1", "callId" to 1), + "write" to mapOf("callId" to 1, "data" to "not bytes"), + "end" to mapOf("callId" to null), + "cancel" to emptyMap(), + "shutdownEngine" to mapOf("engineId" to 1.5), + ) + for ((method, arguments) in malformed) { + val reply = reply(method, arguments) + assertTrue("$method $arguments: $reply", reply is CronetBridge.Reply.Error) + } + val badHints = reply("createEngine", mapOf("quicHints" to listOf(listOf("localhost")))) + assertTrue("createEngine with a bad hint: $badHints", badHints is CronetBridge.Reply.Error) + assertSayWorks(engine, 1) + } + + private fun assertSayWorks(engine: Int, callId: Int) { + open(engine, callId, SAY, "application/proto") + invoke("write", mapOf("callId" to callId, "data" to sentence("again"))) + invoke("end", mapOf("callId" to callId)) + assertEquals("done", awaitOutcome(callId)["type"]) + assertTrue(received(callId).contains("say: again")) + } + + private fun reply(method: String, arguments: Map): CronetBridge.Reply { val result = CompletableFuture() bridge.handle(method, arguments) { result.complete(it) } - return when (val reply = result.get(3, TimeUnit.SECONDS)) { + return result.get(3, TimeUnit.SECONDS) + } + + private fun invoke(method: String, arguments: Map): Any? = + when (val reply = reply(method, arguments)) { is CronetBridge.Reply.Success -> reply.value else -> throw AssertionError("$method: $reply") } - } private fun createEngine(): Int = invoke("createEngine", mapOf("quicHints" to emptyList())) as Int - private fun open(engine: Int, callId: Int, path: String, contentType: String) { + private fun open( + engine: Int, + callId: Int, + path: String, + contentType: String, + extraHeaders: List> = emptyList(), + ) { invoke("open", mapOf( "engineId" to engine, "callId" to callId, "url" to serverUrl + path, "method" to "POST", - "headers" to listOf(listOf("content-type", contentType), listOf("connect-protocol-version", "1")), + "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 834fcd6..88c343a 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 @@ -3,6 +3,7 @@ package com.agtonomy.connect_native_http import android.content.Context import android.os.Handler import android.os.Looper +import android.util.Log import org.chromium.net.BidirectionalStream import org.chromium.net.CronetEngine import org.chromium.net.CronetException @@ -48,17 +49,48 @@ class CronetBridge( var responseComplete = false var endQueued = false val pending = ArrayDeque>() + + // Set once Dart has been told how the call ended. After the bridge fails a call itself, Cronet's own final + // callback still follows, to release the stream. + var reported = false } fun cancelAll() { - executor.execute { + execute(null) { calls.values.forEach { it.stream.cancel() } } } - // Handles one method call. [reply] is called on the main thread. + // 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. + private fun execute(callId: Int?, task: () -> Unit) { + executor.execute { + try { + task() + } catch (e: Exception) { + Log.e(TAG, "call $callId failed in the bridge", e) + if (callId != null) { + abort(callId, e) + } + } + } + } + + // Handles one method call. [reply] is called on the main thread, and arguments Dart got wrong are refused with an + // error reply rather than thrown on it. fun handle(method: String, args: Map, reply: (Reply) -> Unit) { - val result = { r: Reply -> main.post { reply(r) } } + val result: (Reply) -> Unit = { r -> main.post { reply(r) } } + try { + dispatch(method, args, result) + } catch (e: Exception) { + // Not the arguments themselves: an open's include the request headers, credentials among them. + Log.e(TAG, "$method: bad arguments", e) + result(Reply.Error("badArguments", "$method: ${e.message}")) + } + } + + @Suppress("UNCHECKED_CAST") + private fun dispatch(method: String, args: Map, result: (Reply) -> Unit) { when (method) { "createEngine" -> { val quicHints = (args["quicHints"] as List>?).orEmpty() @@ -78,14 +110,16 @@ class CronetBridge( val id = nextEngineId++ engines[id] = Engine(builder.build()) result(Reply.Success(id)) - } catch (e: Exception) { - result(Reply.Error("createEngine", e.message)) + } catch (e: Throwable) { + // Throwable, not Exception: failing to load Cronet's native library is an UnsatisfiedLinkError. + Log.e(TAG, "createEngine failed", e) + result(Reply.Error("createEngine", e.toString())) } } } "shutdownEngine" -> { val engineId = args["engineId"] as Int - executor.execute { + execute(null) { engines[engineId]?.let { it.shuttingDown = true shutdownIfIdle(engineId) @@ -98,31 +132,31 @@ class CronetBridge( val callId = args["callId"] as Int val url = args["url"] as String val httpMethod = args["method"] as String - val headers = args["headers"] as List> - executor.execute { open(engineId, callId, url, httpMethod, headers) } + val headers = (args["headers"] as List>).map { it[0] to it[1] } + execute(callId) { open(engineId, callId, url, httpMethod, headers) } result(Reply.Success(null)) } "write" -> { val callId = args["callId"] as Int val data = args["data"] as ByteArray - executor.execute { enqueue(callId, data, false) } + execute(callId) { enqueue(callId, data, false) } result(Reply.Success(null)) } "end" -> { val callId = args["callId"] as Int - executor.execute { enqueue(callId, ByteArray(0), true) } + execute(callId) { enqueue(callId, ByteArray(0), true) } result(Reply.Success(null)) } "cancel" -> { val callId = args["callId"] as Int - executor.execute { calls[callId]?.stream?.cancel() } + execute(callId) { calls[callId]?.stream?.cancel() } result(Reply.Success(null)) } else -> result(Reply.NotImplemented) } } - private fun open(engineId: Int, callId: Int, url: String, method: String, headers: List>) { + private fun open(engineId: Int, callId: Int, url: String, method: String, headers: List>) { val engine = engines[engineId] if (engine == null || engine.shuttingDown) { emit(failure(callId, false, "engine $engineId is shut down", null)) @@ -130,13 +164,30 @@ class CronetBridge( } val c = Call(callId, engineId) val builder = engine.cronet.newBidirectionalStreamBuilder(url, Callback(c), executor).setHttpMethod(method) - for (h in headers) { - builder.addHeader(h[0], h[1]) + for ((name, value) in headers) { + builder.addHeader(name, value) } c.stream = builder.build() + // Throws on a method or header Cronet rejects, such as a value with a line break. The call is registered only + // once it has started, so abort() then reports it as never sent, with no stream to release. + c.stream.start() calls[callId] = c engine.callIds.add(callId) - c.stream.start() + } + + // Fails a call the bridge itself could not carry on with, after an exception on its thread. + private fun abort(callId: Int, e: Exception) { + val message = "connect_native_http bridge: $e" + val c = calls[callId] + if (c == null) { + // Not started, so nothing was sent and there is no stream to release. A call that has already finished + // is gone too; Dart ignores events for calls it no longer has. + emit(failure(callId, false, message, null)) + return + } + report(c, failure(callId, c.ready, message, null)) + // Cronet's onCanceled then releases the call and the stream. + c.stream.cancel() } private fun enqueue(callId: Int, data: ByteArray, endOfStream: Boolean) { @@ -145,8 +196,9 @@ 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. - if (c.endQueued) { + // 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)) { return } c.endQueued = endOfStream @@ -170,18 +222,31 @@ class CronetBridge( c.stream.flush() } + // Cronet's final callback for a call: releases it and, unless the bridge has already failed it, reports [event]. private fun finish(c: Call, event: Map) { calls.remove(c.callId) engines[c.engineId]?.callIds?.remove(c.callId) - emit(event) + report(c, event) shutdownIfIdle(c.engineId) } + private fun report(c: Call, event: Map) { + if (!c.reported) { + c.reported = true + emit(event) + } + } + private fun shutdownIfIdle(engineId: Int) { val engine = engines[engineId] ?: return if (engine.shuttingDown && engine.callIds.isEmpty()) { engines.remove(engineId) - engine.cronet.shutdown() + try { + engine.cronet.shutdown() + } catch (e: Exception) { + // Cronet refuses while it still counts a request as running. The engine is unreachable either way. + Log.w(TAG, "engine $engineId did not shut down", e) + } } } @@ -195,6 +260,8 @@ class CronetBridge( private fun headerPairs(headers: List>) = headers.map { listOf(it.key, it.value) } + // Cronet catches exceptions from these methods itself: one from onStreamReady, onResponseHeadersReceived or + // onReadCompleted fails the stream (onFailed, with a CallbackException), and one from a final callback is logged. private inner class Callback(private val c: Call) : BidirectionalStream.Callback() { override fun onStreamReady(stream: BidirectionalStream) { c.ready = true @@ -272,6 +339,7 @@ class CronetBridge( } private companion object { + const val TAG = "connect_native_http" const val READ_BUFFER_BYTES = 32 * 1024 } } diff --git a/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift b/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift index a9f9729..da137a6 100644 --- a/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift +++ b/ios/connect_native_http/Sources/ConnectNativeHttpCore/URLSessionBridge.swift @@ -6,9 +6,16 @@ import Foundation public final class URLSessionBridge { public enum Reply { case success(Any?) + /// The call's arguments were not what the method takes. Refused rather than force-unwrapped, which would crash the + /// app. + case error(code: String, message: String) case notImplemented } + private struct BadArgument: Error { + let name: String + } + private let emit: ([String: Any]) -> Void private let trustedRoots: [SecCertificate] @@ -61,9 +68,27 @@ public final class URLSessionBridge { /// Handles one method call. `reply` may be called on any thread. public func handle(_ method: String, _ args: [String: Any], reply: @escaping (Reply) -> Void) { + do { + try dispatch(method, args, reply: reply) + } catch let bad as BadArgument { + reply(.error(code: "badArguments", message: "\(method): missing or mistyped argument \(bad.name)")) + } catch { + reply(.error(code: "badArguments", message: "\(method): \(error)")) + } + } + + private func arg(_ args: [String: Any], _ name: String) throws -> T { + guard let value = args[name] as? T else { throw BadArgument(name: name) } + return value + } + + private func dispatch(_ method: String, _ args: [String: Any], reply: @escaping (Reply) -> Void) throws { switch method { case "createEngine": - let origins = (args["http3Origins"] as? [[Any]] ?? []).map { "\($0[0]):\($0[1])" } + 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])" + } queue.async { let configuration = URLSessionConfiguration.ephemeral // URLSession fails a task that receives nothing for this long. Its default of 60 s would end a quiet stream @@ -79,23 +104,24 @@ public final class URLSessionBridge { reply(.success(id)) } case "shutdownEngine": - let engineId = args["engineId"] as! Int + let engineId: Int = try arg(args, "engineId") queue.async { self.sessions.removeValue(forKey: engineId)?.urlSession.finishTasksAndInvalidate() } reply(.success(nil)) case "open": - let engineId = args["engineId"] as! Int - let callId = args["callId"] as! Int - let url = args["url"] as! String - let method = args["method"] as! String - let headers = args["headers"] as! [[String]] - let hasBody = args["hasBody"] as! Bool + let engineId: Int = try arg(args, "engineId") + let callId: Int = try arg(args, "callId") + let url: String = try arg(args, "url") + let method: String = try arg(args, "method") + let headers: [[String]] = try arg(args, "headers") + guard headers.allSatisfy({ $0.count == 2 }) else { throw BadArgument(name: "headers") } + let hasBody: Bool = try arg(args, "hasBody") queue.async { self.open(engineId, callId, url, method, headers, hasBody) } reply(.success(nil)) case "write": - let callId = args["callId"] as! Int - let data = args["data"] as! Data + let callId: Int = try arg(args, "callId") + let data: Data = try arg(args, "data") // Reply once the bytes are in the stream buffer, so a fast producer waits for URLSession to read them. queue.async { guard let c = self.calls[callId], let output = c.output else { @@ -108,14 +134,14 @@ public final class URLSessionBridge { } } case "end": - let callId = args["callId"] as! Int + let callId: Int = try arg(args, "callId") queue.async { guard let c = self.calls[callId], let output = c.output else { return } c.writer.async { output.close() } } reply(.success(nil)) case "cancel": - let callId = args["callId"] as! Int + let callId: Int = try arg(args, "callId") queue.async { self.calls[callId]?.task.cancel() } reply(.success(nil)) default: diff --git a/ios/connect_native_http/Sources/connect_native_http/ConnectNativeHttpPlugin.swift b/ios/connect_native_http/Sources/connect_native_http/ConnectNativeHttpPlugin.swift index 4bf092f..af4daf9 100644 --- a/ios/connect_native_http/Sources/connect_native_http/ConnectNativeHttpPlugin.swift +++ b/ios/connect_native_http/Sources/connect_native_http/ConnectNativeHttpPlugin.swift @@ -37,6 +37,7 @@ public final class ConnectNativeHttpPlugin: NSObject, FlutterPlugin, FlutterStre DispatchQueue.main.async { switch reply { case .success(let value): result(value) + case .error(let code, let message): result(FlutterError(code: code, message: message, details: nil)) case .notImplemented: result(FlutterMethodNotImplemented) } } diff --git a/ios/connect_native_http/Tests/ConnectNativeHttpCoreTests/URLSessionBridgeTests.swift b/ios/connect_native_http/Tests/ConnectNativeHttpCoreTests/URLSessionBridgeTests.swift index 58dedf3..1978fa2 100644 --- a/ios/connect_native_http/Tests/ConnectNativeHttpCoreTests/URLSessionBridgeTests.swift +++ b/ios/connect_native_http/Tests/ConnectNativeHttpCoreTests/URLSessionBridgeTests.swift @@ -89,17 +89,53 @@ final class URLSessionBridgeTests: XCTestCase { XCTAssertEqual(outcome(2)?["domain"] as? String, "ConnectNativeHttp") } + func testMalformedArgumentsAreRefusedInsteadOfCrashing() async throws { + let malformed: [(String, [String: Any])] = [ + ("open", [:]), + ("open", ["engineId": "1", "callId": 1, "url": serverURL, "method": "POST", "headers": [[String]](), "hasBody": true]), + ("open", ["engineId": 1, "callId": 1, "url": serverURL, "method": "POST", "headers": [["one"]], "hasBody": true]), + ("write", ["callId": 1, "data": "not bytes"]), + ("end", ["callId": "1"]), + ("cancel", [:]), + ("shutdownEngine", ["engineId": NSNull()]), + ("createEngine", ["http3Origins": [["localhost"]]]), + ] + for (method, arguments) in malformed { + let result = await reply(method, arguments) + guard case .error(let code, _) = result else { + XCTFail("\(method) \(arguments): \(result)") + continue + } + XCTAssertEqual(code, "badArguments") + } + // The bridge still works afterwards. + let engine = try await createEngine() + try await open(engine, callId: 1, path: Self.say, contentType: "application/proto") + try await write(1, sentence("hi")) + try await invoke("end", ["callId": 1]) + try await waitUntil("the call ended") { self.outcome(1) != nil } + XCTAssertEqual(outcome(1)?["type"] as? String, "done", "\(String(describing: outcome(1)))") + } + // MARK: Bridge calls - @discardableResult - private func invoke(_ method: String, _ arguments: [String: Any]) async throws -> Any? { - let reply = await withCheckedContinuation { (done: CheckedContinuation) in + private func reply(_ method: String, _ arguments: [String: Any]) async -> URLSessionBridge.Reply { + await withCheckedContinuation { (done: CheckedContinuation) in bridge.handle(method, arguments) { done.resume(returning: $0) } } - guard case .success(let value) = reply else { + } + + @discardableResult + private func invoke(_ method: String, _ arguments: [String: Any]) async throws -> Any? { + switch await reply(method, arguments) { + case .success(let value): + return value + case .error(let code, let message): + XCTFail("\(method): \(code): \(message)") + throw CancellationError() + case .notImplemented: throw XCTSkip("\(method) is not implemented") } - return value } private func createEngine() async throws -> Int { diff --git a/lib/src/channel/channel_http_client.dart b/lib/src/channel/channel_http_client.dart index 7a09a59..1e7f1e8 100644 --- a/lib/src/channel/channel_http_client.dart +++ b/lib/src/channel/channel_http_client.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:connectrpc/connect.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../native_http_client.dart'; @@ -85,11 +86,28 @@ final class _Call { } } +/// Reports an error that has no caller to go to, such as one thrown by `onResponse`, through [FlutterError.reportError]: +/// logged in debug builds, and passed to [FlutterError.onError] (an app's crash reporter, typically) in all builds. +/// Nothing in this package lets such an error escape into a zone or a native thread, where it could crash the app. +void reportError(Object error, StackTrace stack, String context) { + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stack, + library: 'connect_native_http', + context: ErrorDescription(context), + ), + ); +} + /// Routes one plugin's event stream to the call each event belongs to. Every client on that plugin shares it, so call /// ids are unique across clients. final class _Dispatcher { _Dispatcher(this.bridge) { - bridge.events.receiveBroadcastStream().listen(_onEvent); + bridge.events.receiveBroadcastStream().listen( + _onEvent, + onError: (Object error, StackTrace stack) => reportError(error, stack, 'while receiving ${bridge.name} events'), + ); } static final _instances = {}; @@ -108,28 +126,70 @@ final class _Dispatcher { return id; } - void _remove(int id) { - calls.remove(id); + _Call? remove(int id) { _onResponse.remove(id); + return calls.remove(id); + } + + /// Asks the plugin to cancel call [id]; its `canceled` event then ends the call. Should the plugin fail to take the + /// request, no event will come, so the call ends here instead. + Future cancel(int id) async { + try { + await bridge.methods.invokeMethod('cancel', {'callId': id}); + } catch (error, stack) { + final call = remove(id); + call?.fail(call.abortError ?? ConnectException(Code.canceled, '${bridge.name}: cancel failed: $error')); + reportError(error, stack, 'while canceling a ${bridge.name} call'); + } } void _onEvent(Object? event) { - final e = (event! as Map).cast(); - final id = e['callId']! as int; - final call = calls[id]; + final int id; + final _Call? call; + try { + id = (event! as Map)['callId']! as int; + call = calls[id]; + } catch (error, stack) { + reportError(error, stack, 'while reading a ${bridge.name} event (${event.runtimeType})'); + return; + } if (call == null) { return; } + try { + _onCallEvent(id, call, (event as Map).cast()); + } catch (error, stack) { + // A malformed event: the call can't go on, but nothing else is affected. + remove(id); + call.fail(ConnectException(Code.internal, '${bridge.name}: bad event: $error', cause: error)); + unawaited(cancel(id)); + // The event's type only: its body bytes and headers can be large, and private. + reportError(error, stack, "while handling a ${bridge.name} '${(event as Map)['type']}' event for call $id"); + } + } + + void _onCallEvent(int id, _Call call, Map e) { switch (e['type']) { case 'headers': final headers = bridge.responseHeaders([ for (final pair in (e['headers']! as List).cast>()) (pair[0]! as String, pair[1]! as String), ]); + final status = e['status']! as int; if (!bridge.endsStreamsItself && isConnectStreamingContentType(headers.get('content-type')?.firstOrNull)) { call.endStream = ConnectEndStreamDetector(); } - _onResponse[id]?.call(NativeHttpResponseInfo(url: call.url, protocol: e['protocol'] as String?)); - call.response.complete(HttpResponse(e['status']! as int, headers, call.body.stream, call.trailer)); + final onResponse = _onResponse[id]; + if (onResponse != null) { + // The caller's own callback: its failure is reported, and doesn't fail the call or leave it hanging. + try { + onResponse(NativeHttpResponseInfo(url: call.url, protocol: e['protocol'] as String?)); + } catch (error, stack) { + reportError(error, stack, 'in NativeHttpConfig.onResponse'); + } + } + if (!call.response.isCompleted) { + call.response.complete(HttpResponse(status, headers, call.body.stream, call.trailer)); + } case 'data': _onData(id, call, e['data']! as Uint8List); case 'trailers': @@ -139,14 +199,14 @@ final class _Dispatcher { case 'responseComplete': call.completeResponse(bridge.name); case 'done': - _remove(id); + remove(id); call.completeResponse(bridge.name); case 'failed': - _remove(id); + remove(id); final cause = bridge.failure(e); call.fail(call.abortError ?? ConnectException(Code.unavailable, cause.message, cause: cause)); case 'canceled': - _remove(id); + remove(id); call.fail(call.abortError ?? ConnectException(Code.canceled, '${bridge.name}: stream canceled')); } } @@ -166,7 +226,7 @@ final class _Dispatcher { } if (detector.done) { call.completeResponse(bridge.name); - unawaited(bridge.methods.invokeMethod('cancel', {'callId': id})); + unawaited(cancel(id)); } } } @@ -195,31 +255,39 @@ base class ChannelHttpClient implements NativeHttpClient { final id = dispatcher.register(call, _config.onResponse); call.body.onCancel = () { if (!call.finished) { - unawaited(methods.invokeMethod('cancel', {'callId': id})); + unawaited(dispatcher.cancel(id)); } }; req.signal?.future.then((error) { if (!call.finished) { call.abortError = error; - unawaited(methods.invokeMethod('cancel', {'callId': id})); + unawaited(dispatcher.cancel(id)); } }); - await methods.invokeMethod('open', { - 'engineId': _engineId, - 'callId': id, - 'url': req.url, - 'method': req.method, - 'headers': [ - for (final (:name, :value) in req.header.entries) [name, value], - ], - 'hasBody': req.body != null, - }); - unawaited(_sendBody(id, call, req.body)); + try { + await methods.invokeMethod('open', { + 'engineId': _engineId, + 'callId': id, + 'url': req.url, + 'method': req.method, + 'headers': [ + for (final (:name, :value) in req.header.entries) [name, value], + ], + 'hasBody': req.body != null, + }); + } catch (error) { + // The plugin refused the call, or isn't there (a background isolate, say): nothing was sent. + dispatcher.remove(id); + call.finished = true; + final cause = NativeHttpException(NativeHttpFailure.notSent, '${_bridge.name}: open failed: $error'); + throw ConnectException(Code.unavailable, cause.message, cause: cause); + } + unawaited(_sendBody(id, call, req.body, dispatcher)); return call.response.future; } /// Streams the request body to the plugin, one chunk per method call. - Future _sendBody(int id, _Call call, Stream? body) async { + Future _sendBody(int id, _Call call, Stream? body, _Dispatcher dispatcher) async { final methods = _bridge.methods; try { if (body != null) { @@ -234,9 +302,12 @@ base class ChannelHttpClient implements NativeHttpClient { await methods.invokeMethod('end', {'callId': id}); } } catch (error) { + // The request stream failed, or the plugin refused a chunk: the call fails with that error. if (!call.finished) { - call.abortError ??= error; - await methods.invokeMethod('cancel', {'callId': id}); + call.abortError ??= error is PlatformException + ? ConnectException(Code.internal, '${_bridge.name}: request body refused: $error', cause: error) + : error; + await dispatcher.cancel(id); } } } diff --git a/lib/src/native_http_client.dart b/lib/src/native_http_client.dart index 8126002..2c01fb5 100644 --- a/lib/src/native_http_client.dart +++ b/lib/src/native_http_client.dart @@ -13,6 +13,9 @@ import 'url_session/url_session_http_client.dart'; /// Requests fail with a `ConnectException` of code `unavailable` whose `cause` is a [NativeHttpException]. abstract interface class NativeHttpClient { /// The client for this platform, or `null` where there is none (anything but iOS and Android). + /// + /// Throws a `PlatformException` if the platform can't create one, such as when Android fails to load Cronet's native + /// library. An app can fall back to another `HttpClient` then. static Future create([NativeHttpConfig config = const NativeHttpConfig()]) async { if (Platform.isIOS) { return UrlSessionHttpClient.create(config); diff --git a/lib/src/native_http_config.dart b/lib/src/native_http_config.dart index f433f3a..1a145f8 100644 --- a/lib/src/native_http_config.dart +++ b/lib/src/native_http_config.dart @@ -29,6 +29,7 @@ final class NativeHttpConfig { /// Android only. URLSession exposes no QUIC settings, so on iOS only the server's advertised idle timeout applies. final Duration? quicIdleTimeout; - /// Called with each response's headers, before its body is read. + /// Called with each response's headers, before its body is read. An exception it throws goes to + /// `FlutterError.onError`, and the call goes on. final void Function(NativeHttpResponseInfo info)? onResponse; } diff --git a/test/cronet_http_client_test.dart b/test/cronet_http_client_test.dart index 5744fea..241f538 100644 --- a/test/cronet_http_client_test.dart +++ b/test/cronet_http_client_test.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:connect_native_http/connect_native_http.dart'; import 'package:connect_native_http/src/cronet/cronet_http_client.dart'; import 'package:connectrpc/connect.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -11,6 +12,9 @@ class FakePlugin { FakePlugin() { _messenger.setMockMethodCallHandler(cronetMethodChannel, (call) async { calls.add(call); + if (refusing.contains(call.method)) { + throw PlatformException(code: 'badArguments', message: '${call.method} refused'); + } return call.method == 'createEngine' ? 7 : null; }); _messenger.setMockMethodCallHandler(MethodChannel(cronetEventChannel.name), (call) async => null); @@ -18,6 +22,9 @@ class FakePlugin { final calls = []; + /// Methods the plugin answers with an error. + final refusing = {}; + TestDefaultBinaryMessenger get _messenger => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; List callsTo(String method) => calls.where((c) => c.method == method).toList(); @@ -299,4 +306,93 @@ void main() { await client.close(); expect(plugin.callsTo('shutdownEngine').single.arguments['engineId'], 7); }); + + group('errors end the call they concern, and nothing else', () { + final reported = []; + late FlutterExceptionHandler? previousOnError; + + setUp(() { + reported.clear(); + previousOnError = FlutterError.onError; + FlutterError.onError = reported.add; + }); + + tearDown(() => FlutterError.onError = previousOnError); + + Future expectSayWorks() async { + final response = client.httpClient(request(null)); + await settle(); + await plugin.headers(plugin.lastCallId); + expect((await response).status, 200); + } + + test('an onResponse callback that throws is reported, and the call goes on', () async { + final throwing = await CronetHttpClient.create(NativeHttpConfig(onResponse: (_) => throw StateError('oops'))); + final responseFuture = throwing.httpClient(request(null)); + await settle(); + await plugin.headers(plugin.lastCallId); + final response = await responseFuture.timeout(const Duration(seconds: 1)); + expect(response.status, 200); + expect(reported.single.exception, isA()); + }); + + test('a plugin that refuses to open the call fails it as never sent', () async { + plugin.refusing.add('open'); + final cause = await failureCause(client.httpClient(request(Stream.value(Uint8List.fromList([1]))))); + expect(cause.failure, NativeHttpFailure.notSent); + expect(cause.message, contains('open refused')); + await settle(); + expect(plugin.callsTo('write'), isEmpty); + plugin.refusing.clear(); + await expectSayWorks(); + }); + + test('a plugin that refuses a chunk cancels the call', () async { + plugin.refusing.add('write'); + final response = client.httpClient(request(Stream.value(Uint8List.fromList([1])))); + await settle(); + await settle(); + final id = plugin.lastCallId; + expect(plugin.callsTo('cancel').single.arguments['callId'], id); + await plugin.emit({'callId': id, 'type': 'canceled'}); + await expectLater(response, throwsA(isA().having((e) => e.code, 'code', Code.internal))); + }); + + test('a cancel the plugin refuses still ends the call', () async { + plugin.refusing.add('cancel'); + final signal = CancelableSignal(); + final response = client.httpClient(request(StreamController().stream, signal: signal)); + await settle(); + signal.cancel('stop'); + await expectLater( + response.timeout(const Duration(seconds: 1)), + throwsA(isA().having((e) => e.code, 'code', Code.canceled)), + ); + expect(reported.single.exception, isA()); + }); + + test('a malformed event fails its own call, and other calls carry on', () async { + final other = client.httpClient(request(null)); + await settle(); + final otherId = plugin.lastCallId; + + final broken = client.httpClient(request(null)); + await settle(); + final brokenId = plugin.lastCallId; + await plugin.emit({'callId': brokenId, 'type': 'headers', 'status': 'two hundred', 'headers': []}); + await expectLater(broken, throwsA(isA().having((e) => e.code, 'code', Code.internal))); + await settle(); + expect(plugin.callsTo('cancel').single.arguments['callId'], brokenId); + expect(reported, hasLength(1)); + + await plugin.headers(otherId); + expect((await other).status, 200); + }); + + test('an event that names no call is reported and ignored', () async { + await plugin.emit({'type': 'data'}); + expect(reported, hasLength(1)); + await expectSayWorks(); + }); + }); }